Unnamed: 0
int64 0
409
| Code
stringlengths 131
27.3k
| Unit Test
stringlengths 89
30.5k
|
---|---|---|
300 | #ifndef TENSORFLOW_CORE_KERNELS_STOCHASTIC_CAST_OP_H_
#define TENSORFLOW_CORE_KERNELS_STOCHASTIC_CAST_OP_H_
#include <limits>
#include <type_traits>
#include "Eigen/Core"
#include "unsupported/Eigen/CXX11/Tensor"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/rng_alg.h"
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/lib/random/random_distributions.h"
#include "tensorflow/core/platform/macros.h"
namespace tensorflow {
namespace internal {
class StochasticCastOpBase : public OpKernel {
public:
explicit StochasticCastOpBase(OpKernelConstruction* ctx) : OpKernel(ctx) {}
void Compute(OpKernelContext* ctx) override;
protected:
virtual void RoundOff(OpKernelContext* ctx, Algorithm alg, const Tensor& key,
const Tensor& counter, Tensor* output) = 0;
};
}
}
namespace Eigen {
namespace internal {
template <typename Scalar, typename IntResultType, typename Generator>
struct StochasticRoundToIntOp {
static_assert(std::is_integral<IntResultType>::value,
"Integer type expected");
typedef tensorflow::random::UniformDistribution<Generator, Scalar>
Distribution;
const Scalar max =
static_cast<Scalar>(std::numeric_limits<IntResultType>::max());
const Scalar min =
static_cast<Scalar>(std::numeric_limits<IntResultType>::min());
EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC explicit StochasticRoundToIntOp(
Generator* g)
: gen(g) {}
EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Scalar
operator()(const Scalar& s) const {
if (TF_PREDICT_FALSE(Eigen::numext::isnan(s))) {
return Scalar{0};
}
if (s >= max) {
return max;
}
if (s <= min) {
return min;
}
if (Eigen::numext::floor(s) == s) {
return s;
}
Distribution dist;
Scalar random = dist(gen)[0];
if (s < 0) {
return Eigen::numext::floor(s + random);
} else {
return Eigen::numext::floor(s + Scalar{1} - random);
}
}
template <typename Packet>
EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Packet packetOp(const Packet& p) const {
constexpr size_t kPacketSize =
Eigen::internal::unpacket_traits<Packet>::size;
Scalar unpacked_random[kPacketSize];
Distribution dist;
auto const sample = dist(gen);
for (int i = 0; i < kPacketSize; i += Distribution::kResultElementCount) {
int granularity = std::min(Distribution::kResultElementCount,
static_cast<int>(kPacketSize - i));
std::copy(&sample[0], &sample[0] + granularity, &unpacked_random[i]);
}
Packet random = pload<Packet>(unpacked_random);
Packet rounded =
pselect(pcmp_eq(pfloor(p), p), p,
pselect(pcmp_lt(p, pzero(p)), pfloor(padd(p, random)),
pfloor(padd(p, psub(pset1<Packet>(1), random)))));
Packet result =
pselect(pcmp_le(pset1<Packet>(max), p), pset1<Packet>(max), rounded);
result =
pselect(pcmp_le(p, pset1<Packet>(min)), pset1<Packet>(min), result);
return pselect(pcmp_eq(p, p), result, pset1<Packet>(0));
}
Generator* gen;
};
template <typename Scalar, typename IntResultType, typename Generator>
struct functor_traits<
StochasticRoundToIntOp<Scalar, IntResultType, Generator>> {
enum {
Cost = 3 * NumTraits<Scalar>::AddCost,
PacketAccess =
packet_traits<Scalar>::HasCmp && packet_traits<Scalar>::HasRound,
};
};
}
}
#endif
#include "tensorflow/core/framework/op.h"
#include "tensorflow/core/framework/rng_alg.h"
#include "tensorflow/core/framework/shape_inference.h"
#include "tensorflow/core/lib/core/status.h"
#include "tsl/platform/errors.h"
namespace tensorflow {
using shape_inference::DimensionHandle;
using shape_inference::InferenceContext;
using shape_inference::ShapeHandle;
REGISTER_OP("StochasticCastToInt")
.Input("input: Tin")
.Input("key: uint64")
.Input("counter: uint64")
.Input("alg: int32")
.Output("output: Tout")
.Attr("Tin: {half, bfloat16, float32, float64}")
.Attr("Tout: {int8, int16, int32}")
.SetShapeFn([](InferenceContext* c) {
ShapeHandle key;
ShapeHandle shape;
TF_RETURN_IF_ERROR(c->WithRank(c->input(1), 1, &key));
TF_RETURN_IF_ERROR(c->WithRank(c->input(2), 1, &shape));
TF_RETURN_IF_ERROR(c->WithRank(c->input(3), 0, &shape));
DimensionHandle dim;
TF_RETURN_IF_ERROR(
c->WithValue(c->Dim(key, 0), RNG_KEY_SIZE, &dim));
c->set_output(0, c->input(0));
return absl::OkStatus();
});
} | #include "tensorflow/core/framework/shape_inference_testutil.h"
#include "tensorflow/core/platform/test.h"
namespace tensorflow {
TEST(StochasticCastOpTest, StochasticCastToIntShapeInference) {
ShapeInferenceTestOp op("StochasticCastToInt");
INFER_OK(op, "[4,2];[1];[1];[]", "in0");
INFER_ERROR("Shape must be rank 1 but is rank 2", op, "[4,2];[1,2];[1];[]");
INFER_ERROR("Shape must be rank 1 but is rank 2", op, "[4,2];[1];[1,2];[]");
INFER_ERROR("Shape must be rank 0 but is rank 1", op, "[4,2];[1];[1];[1]");
}
} |
301 | #ifndef STORAGE_LEVELDB_INCLUDE_ENV_H_
#define STORAGE_LEVELDB_INCLUDE_ENV_H_
#include <cstdarg>
#include <cstdint>
#include <string>
#include <vector>
#include "leveldb/export.h"
#include "leveldb/status.h"
#if defined(_WIN32)
#if defined(DeleteFile)
#undef DeleteFile
#define LEVELDB_DELETEFILE_UNDEFINED
#endif
#endif
namespace leveldb {
class FileLock;
class Logger;
class RandomAccessFile;
class SequentialFile;
class Slice;
class WritableFile;
class LEVELDB_EXPORT Env {
public:
Env();
Env(const Env&) = delete;
Env& operator=(const Env&) = delete;
virtual ~Env();
static Env* Default();
virtual Status NewSequentialFile(const std::string& fname,
SequentialFile** result) = 0;
virtual Status NewRandomAccessFile(const std::string& fname,
RandomAccessFile** result) = 0;
virtual Status NewWritableFile(const std::string& fname,
WritableFile** result) = 0;
virtual Status NewAppendableFile(const std::string& fname,
WritableFile** result);
virtual bool FileExists(const std::string& fname) = 0;
virtual Status GetChildren(const std::string& dir,
std::vector<std::string>* result) = 0;
virtual Status RemoveFile(const std::string& fname);
virtual Status DeleteFile(const std::string& fname);
virtual Status CreateDir(const std::string& dirname) = 0;
virtual Status RemoveDir(const std::string& dirname);
virtual Status DeleteDir(const std::string& dirname);
virtual Status GetFileSize(const std::string& fname, uint64_t* file_size) = 0;
virtual Status RenameFile(const std::string& src,
const std::string& target) = 0;
virtual Status LockFile(const std::string& fname, FileLock** lock) = 0;
virtual Status UnlockFile(FileLock* lock) = 0;
virtual void Schedule(void (*function)(void* arg), void* arg) = 0;
virtual void StartThread(void (*function)(void* arg), void* arg) = 0;
virtual Status GetTestDirectory(std::string* path) = 0;
virtual Status NewLogger(const std::string& fname, Logger** result) = 0;
virtual uint64_t NowMicros() = 0;
virtual void SleepForMicroseconds(int micros) = 0;
};
class LEVELDB_EXPORT SequentialFile {
public:
SequentialFile() = default;
SequentialFile(const SequentialFile&) = delete;
SequentialFile& operator=(const SequentialFile&) = delete;
virtual ~SequentialFile();
virtual Status Read(size_t n, Slice* result, char* scratch) = 0;
virtual Status Skip(uint64_t n) = 0;
};
class LEVELDB_EXPORT RandomAccessFile {
public:
RandomAccessFile() = default;
RandomAccessFile(const RandomAccessFile&) = delete;
RandomAccessFile& operator=(const RandomAccessFile&) = delete;
virtual ~RandomAccessFile();
virtual Status Read(uint64_t offset, size_t n, Slice* result,
char* scratch) const = 0;
};
class LEVELDB_EXPORT WritableFile {
public:
WritableFile() = default;
WritableFile(const WritableFile&) = delete;
WritableFile& operator=(const WritableFile&) = delete;
virtual ~WritableFile();
virtual Status Append(const Slice& data) = 0;
virtual Status Close() = 0;
virtual Status Flush() = 0;
virtual Status Sync() = 0;
};
class LEVELDB_EXPORT Logger {
public:
Logger() = default;
Logger(const Logger&) = delete;
Logger& operator=(const Logger&) = delete;
virtual ~Logger();
virtual void Logv(const char* format, std::va_list ap) = 0;
};
class LEVELDB_EXPORT FileLock {
public:
FileLock() = default;
FileLock(const FileLock&) = delete;
FileLock& operator=(const FileLock&) = delete;
virtual ~FileLock();
};
void Log(Logger* info_log, const char* format, ...)
#if defined(__GNUC__) || defined(__clang__)
__attribute__((__format__(__printf__, 2, 3)))
#endif
;
LEVELDB_EXPORT Status WriteStringToFile(Env* env, const Slice& data,
const std::string& fname);
LEVELDB_EXPORT Status ReadFileToString(Env* env, const std::string& fname,
std::string* data);
class LEVELDB_EXPORT EnvWrapper : public Env {
public:
explicit EnvWrapper(Env* t) : target_(t) {}
virtual ~EnvWrapper();
Env* target() const { return target_; }
Status NewSequentialFile(const std::string& f, SequentialFile** r) override {
return target_->NewSequentialFile(f, r);
}
Status NewRandomAccessFile(const std::string& f,
RandomAccessFile** r) override {
return target_->NewRandomAccessFile(f, r);
}
Status NewWritableFile(const std::string& f, WritableFile** r) override {
return target_->NewWritableFile(f, r);
}
Status NewAppendableFile(const std::string& f, WritableFile** r) override {
return target_->NewAppendableFile(f, r);
}
bool FileExists(const std::string& f) override {
return target_->FileExists(f);
}
Status GetChildren(const std::string& dir,
std::vector<std::string>* r) override {
return target_->GetChildren(dir, r);
}
Status RemoveFile(const std::string& f) override {
return target_->RemoveFile(f);
}
Status CreateDir(const std::string& d) override {
return target_->CreateDir(d);
}
Status RemoveDir(const std::string& d) override {
return target_->RemoveDir(d);
}
Status GetFileSize(const std::string& f, uint64_t* s) override {
return target_->GetFileSize(f, s);
}
Status RenameFile(const std::string& s, const std::string& t) override {
return target_->RenameFile(s, t);
}
Status LockFile(const std::string& f, FileLock** l) override {
return target_->LockFile(f, l);
}
Status UnlockFile(FileLock* l) override { return target_->UnlockFile(l); }
void Schedule(void (*f)(void*), void* a) override {
return target_->Schedule(f, a);
}
void StartThread(void (*f)(void*), void* a) override {
return target_->StartThread(f, a);
}
Status GetTestDirectory(std::string* path) override {
return target_->GetTestDirectory(path);
}
Status NewLogger(const std::string& fname, Logger** result) override {
return target_->NewLogger(fname, result);
}
uint64_t NowMicros() override { return target_->NowMicros(); }
void SleepForMicroseconds(int micros) override {
target_->SleepForMicroseconds(micros);
}
private:
Env* target_;
};
}
#if defined(_WIN32) && defined(LEVELDB_DELETEFILE_UNDEFINED)
#if defined(UNICODE)
#define DeleteFile DeleteFileW
#else
#define DeleteFile DeleteFileA
#endif
#endif
#endif
#include "leveldb/env.h"
#include <cstdarg>
#if defined(_WIN32) && defined(LEVELDB_DELETEFILE_UNDEFINED)
#undef DeleteFile
#endif
namespace leveldb {
Env::Env() = default;
Env::~Env() = default;
Status Env::NewAppendableFile(const std::string& fname, WritableFile** result) {
return Status::NotSupported("NewAppendableFile", fname);
}
Status Env::RemoveDir(const std::string& dirname) { return DeleteDir(dirname); }
Status Env::DeleteDir(const std::string& dirname) { return RemoveDir(dirname); }
Status Env::RemoveFile(const std::string& fname) { return DeleteFile(fname); }
Status Env::DeleteFile(const std::string& fname) { return RemoveFile(fname); }
SequentialFile::~SequentialFile() = default;
RandomAccessFile::~RandomAccessFile() = default;
WritableFile::~WritableFile() = default;
Logger::~Logger() = default;
FileLock::~FileLock() = default;
void Log(Logger* info_log, const char* format, ...) {
if (info_log != nullptr) {
std::va_list ap;
va_start(ap, format);
info_log->Logv(format, ap);
va_end(ap);
}
}
static Status DoWriteStringToFile(Env* env, const Slice& data,
const std::string& fname, bool should_sync) {
WritableFile* file;
Status s = env->NewWritableFile(fname, &file);
if (!s.ok()) {
return s;
}
s = file->Append(data);
if (s.ok() && should_sync) {
s = file->Sync();
}
if (s.ok()) {
s = file->Close();
}
delete file;
if (!s.ok()) {
env->RemoveFile(fname);
}
return s;
}
Status WriteStringToFile(Env* env, const Slice& data,
const std::string& fname) {
return DoWriteStringToFile(env, data, fname, false);
}
Status WriteStringToFileSync(Env* env, const Slice& data,
const std::string& fname) {
return DoWriteStringToFile(env, data, fname, true);
}
Status ReadFileToString(Env* env, const std::string& fname, std::string* data) {
data->clear();
SequentialFile* file;
Status s = env->NewSequentialFile(fname, &file);
if (!s.ok()) {
return s;
}
static const int kBufferSize = 8192;
char* space = new char[kBufferSize];
while (true) {
Slice fragment;
s = file->Read(kBufferSize, &fragment, space);
if (!s.ok()) {
break;
}
data->append(fragment.data(), fragment.size());
if (fragment.empty()) {
break;
}
}
delete[] space;
delete file;
return s;
}
EnvWrapper::~EnvWrapper() {}
} | #include "leveldb/env.h"
#include <algorithm>
#include "gtest/gtest.h"
#include "port/port.h"
#include "port/thread_annotations.h"
#include "util/mutexlock.h"
#include "util/testutil.h"
namespace leveldb {
class EnvTest : public testing::Test {
public:
EnvTest() : env_(Env::Default()) {}
Env* env_;
};
TEST_F(EnvTest, ReadWrite) {
Random rnd(test::RandomSeed());
std::string test_dir;
ASSERT_LEVELDB_OK(env_->GetTestDirectory(&test_dir));
std::string test_file_name = test_dir + "/open_on_read.txt";
WritableFile* writable_file;
ASSERT_LEVELDB_OK(env_->NewWritableFile(test_file_name, &writable_file));
static const size_t kDataSize = 10 * 1048576;
std::string data;
while (data.size() < kDataSize) {
int len = rnd.Skewed(18);
std::string r;
test::RandomString(&rnd, len, &r);
ASSERT_LEVELDB_OK(writable_file->Append(r));
data += r;
if (rnd.OneIn(10)) {
ASSERT_LEVELDB_OK(writable_file->Flush());
}
}
ASSERT_LEVELDB_OK(writable_file->Sync());
ASSERT_LEVELDB_OK(writable_file->Close());
delete writable_file;
SequentialFile* sequential_file;
ASSERT_LEVELDB_OK(env_->NewSequentialFile(test_file_name, &sequential_file));
std::string read_result;
std::string scratch;
while (read_result.size() < data.size()) {
int len = std::min<int>(rnd.Skewed(18), data.size() - read_result.size());
scratch.resize(std::max(len, 1));
Slice read;
ASSERT_LEVELDB_OK(sequential_file->Read(len, &read, &scratch[0]));
if (len > 0) {
ASSERT_GT(read.size(), 0);
}
ASSERT_LE(read.size(), len);
read_result.append(read.data(), read.size());
}
ASSERT_EQ(read_result, data);
delete sequential_file;
}
TEST_F(EnvTest, RunImmediately) {
struct RunState {
port::Mutex mu;
port::CondVar cvar{&mu};
bool called = false;
static void Run(void* arg) {
RunState* state = reinterpret_cast<RunState*>(arg);
MutexLock l(&state->mu);
ASSERT_EQ(state->called, false);
state->called = true;
state->cvar.Signal();
}
};
RunState state;
env_->Schedule(&RunState::Run, &state);
MutexLock l(&state.mu);
while (!state.called) {
state.cvar.Wait();
}
}
TEST_F(EnvTest, RunMany) {
struct RunState {
port::Mutex mu;
port::CondVar cvar{&mu};
int run_count = 0;
};
struct Callback {
RunState* const state_;
bool run = false;
Callback(RunState* s) : state_(s) {}
static void Run(void* arg) {
Callback* callback = reinterpret_cast<Callback*>(arg);
RunState* state = callback->state_;
MutexLock l(&state->mu);
state->run_count++;
callback->run = true;
state->cvar.Signal();
}
};
RunState state;
Callback callback1(&state);
Callback callback2(&state);
Callback callback3(&state);
Callback callback4(&state);
env_->Schedule(&Callback::Run, &callback1);
env_->Schedule(&Callback::Run, &callback2);
env_->Schedule(&Callback::Run, &callback3);
env_->Schedule(&Callback::Run, &callback4);
MutexLock l(&state.mu);
while (state.run_count != 4) {
state.cvar.Wait();
}
ASSERT_TRUE(callback1.run);
ASSERT_TRUE(callback2.run);
ASSERT_TRUE(callback3.run);
ASSERT_TRUE(callback4.run);
}
struct State {
port::Mutex mu;
port::CondVar cvar{&mu};
int val GUARDED_BY(mu);
int num_running GUARDED_BY(mu);
State(int val, int num_running) : val(val), num_running(num_running) {}
};
static void ThreadBody(void* arg) {
State* s = reinterpret_cast<State*>(arg);
s->mu.Lock();
s->val += 1;
s->num_running -= 1;
s->cvar.Signal();
s->mu.Unlock();
}
TEST_F(EnvTest, StartThread) {
State state(0, 3);
for (int i = 0; i < 3; i++) {
env_->StartThread(&ThreadBody, &state);
}
MutexLock l(&state.mu);
while (state.num_running != 0) {
state.cvar.Wait();
}
ASSERT_EQ(state.val, 3);
}
TEST_F(EnvTest, TestOpenNonExistentFile) {
std::string test_dir;
ASSERT_LEVELDB_OK(env_->GetTestDirectory(&test_dir));
std::string non_existent_file = test_dir + "/non_existent_file";
ASSERT_TRUE(!env_->FileExists(non_existent_file));
RandomAccessFile* random_access_file;
Status status =
env_->NewRandomAccessFile(non_existent_file, &random_access_file);
#if defined(LEVELDB_PLATFORM_CHROMIUM)
ASSERT_TRUE(status.IsIOError());
#else
ASSERT_TRUE(status.IsNotFound());
#endif
SequentialFile* sequential_file;
status = env_->NewSequentialFile(non_existent_file, &sequential_file);
#if defined(LEVELDB_PLATFORM_CHROMIUM)
ASSERT_TRUE(status.IsIOError());
#else
ASSERT_TRUE(status.IsNotFound());
#endif
}
TEST_F(EnvTest, ReopenWritableFile) {
std::string test_dir;
ASSERT_LEVELDB_OK(env_->GetTestDirectory(&test_dir));
std::string test_file_name = test_dir + "/reopen_writable_file.txt";
env_->RemoveFile(test_file_name);
WritableFile* writable_file;
ASSERT_LEVELDB_OK(env_->NewWritableFile(test_file_name, &writable_file));
std::string data("hello world!");
ASSERT_LEVELDB_OK(writable_file->Append(data));
ASSERT_LEVELDB_OK(writable_file->Close());
delete writable_file;
ASSERT_LEVELDB_OK(env_->NewWritableFile(test_file_name, &writable_file));
data = "42";
ASSERT_LEVELDB_OK(writable_file->Append(data));
ASSERT_LEVELDB_OK(writable_file->Close());
delete writable_file;
ASSERT_LEVELDB_OK(ReadFileToString(env_, test_file_name, &data));
ASSERT_EQ(std::string("42"), data);
env_->RemoveFile(test_file_name);
}
TEST_F(EnvTest, ReopenAppendableFile) {
std::string test_dir;
ASSERT_LEVELDB_OK(env_->GetTestDirectory(&test_dir));
std::string test_file_name = test_dir + "/reopen_appendable_file.txt";
env_->RemoveFile(test_file_name);
WritableFile* appendable_file;
ASSERT_LEVELDB_OK(env_->NewAppendableFile(test_file_name, &appendable_file));
std::string data("hello world!");
ASSERT_LEVELDB_OK(appendable_file->Append(data));
ASSERT_LEVELDB_OK(appendable_file->Close());
delete appendable_file;
ASSERT_LEVELDB_OK(env_->NewAppendableFile(test_file_name, &appendable_file));
data = "42";
ASSERT_LEVELDB_OK(appendable_file->Append(data));
ASSERT_LEVELDB_OK(appendable_file->Close());
delete appendable_file;
ASSERT_LEVELDB_OK(ReadFileToString(env_, test_file_name, &data));
ASSERT_EQ(std::string("hello world!42"), data);
env_->RemoveFile(test_file_name);
}
} |
302 | #include "phonenumbers/phonenumbermatch.h"
#include <string>
#include "phonenumbers/phonenumber.h"
#include "phonenumbers/phonenumber.pb.h"
#include "phonenumbers/stringutil.h"
namespace i18n {
namespace phonenumbers {
PhoneNumberMatch::PhoneNumberMatch(int start,
const string& raw_string,
const PhoneNumber& number)
: start_(start), raw_string_(raw_string), number_(number) {
}
PhoneNumberMatch::PhoneNumberMatch()
: start_(-1), raw_string_(""), number_(PhoneNumber::default_instance()) {
}
const PhoneNumber& PhoneNumberMatch::number() const {
return number_;
}
int PhoneNumberMatch::start() const {
return start_;
}
int PhoneNumberMatch::end() const {
return static_cast<int>(start_ + raw_string_.length());
}
int PhoneNumberMatch::length() const {
return static_cast<int>(raw_string_.length());
}
const string& PhoneNumberMatch::raw_string() const {
return raw_string_;
}
void PhoneNumberMatch::set_start(int start) {
start_ = start;
}
void PhoneNumberMatch::set_raw_string(const string& raw_string) {
raw_string_ = raw_string;
}
void PhoneNumberMatch::set_number(const PhoneNumber& number) {
number_.CopyFrom(number);
}
string PhoneNumberMatch::ToString() const {
return StrCat("PhoneNumberMatch [", start(), ",", end(), ") ",
raw_string_.c_str());
}
bool PhoneNumberMatch::Equals(const PhoneNumberMatch& match) const {
return ExactlySameAs(match.number_, number_) &&
match.raw_string_.compare(raw_string_) == 0 &&
match.start_ == start_;
}
void PhoneNumberMatch::CopyFrom(const PhoneNumberMatch& match) {
raw_string_ = match.raw_string();
start_ = match.start();
number_ = match.number();
}
}
} | #include "phonenumbers/phonenumber.h"
#include "phonenumbers/phonenumbermatch.h"
#include <gtest/gtest.h>
#include "phonenumbers/phonenumber.pb.h"
namespace i18n {
namespace phonenumbers {
TEST(PhoneNumberMatch, TestGetterMethods) {
PhoneNumber number;
const int start_index = 10;
const string raw_phone_number("1 800 234 45 67");
PhoneNumberMatch match1(start_index, raw_phone_number, number);
EXPECT_EQ(start_index, match1.start());
EXPECT_EQ(start_index + static_cast<int>(raw_phone_number.length()),
match1.end());
EXPECT_EQ(static_cast<int>(raw_phone_number.length()), match1.length());
EXPECT_EQ(raw_phone_number, match1.raw_string());
EXPECT_EQ("PhoneNumberMatch [10,25) 1 800 234 45 67", match1.ToString());
}
TEST(PhoneNumberMatch, TestEquals) {
PhoneNumber number;
PhoneNumberMatch match1(10, "1 800 234 45 67", number);
PhoneNumberMatch match2(10, "1 800 234 45 67", number);
match2.set_start(11);
ASSERT_FALSE(match1.Equals(match2));
match2.set_start(match1.start());
EXPECT_TRUE(match1.Equals(match2));
PhoneNumber number2;
number2.set_raw_input("123");
match2.set_number(number2);
ASSERT_FALSE(match1.Equals(match2));
match2.set_number(match1.number());
EXPECT_TRUE(ExactlySameAs(match1.number(), match2.number()));
EXPECT_TRUE(match1.Equals(match2));
match2.set_raw_string("123");
ASSERT_FALSE(match1.Equals(match2));
}
TEST(PhoneNumberMatch, TestAssignmentOverload) {
PhoneNumber number;
PhoneNumberMatch match1(10, "1 800 234 45 67", number);
PhoneNumberMatch match2;
ASSERT_FALSE(match1.Equals(match2));
match2.CopyFrom(match1);
ASSERT_TRUE(match1.Equals(match2));
PhoneNumberMatch match3;
PhoneNumberMatch match4;
match4.CopyFrom(match2);
match3.CopyFrom(match2);
ASSERT_TRUE(match3.Equals(match4));
ASSERT_TRUE(match4.Equals(match2));
}
TEST(PhoneNumberMatch, TestCopyConstructor) {
PhoneNumber number;
PhoneNumberMatch match1(10, "1 800 234 45 67", number);
PhoneNumberMatch match2;
match2.CopyFrom(match1);
ASSERT_TRUE(match1.Equals(match2));
}
}
} |
303 | #ifndef XLA_TOOLS_HLO_EXTRACTOR_H_
#define XLA_TOOLS_HLO_EXTRACTOR_H_
#include <cstdint>
#include <functional>
#include <memory>
#include "xla/hlo/ir/hlo_computation.h"
#include "xla/hlo/ir/hlo_instruction.h"
#include "xla/hlo/ir/hlo_module.h"
namespace xla {
using ExtractSelector = std::function<bool(const HloInstruction*)>;
enum class ReplaceType {
kReplaceParam,
kReplaceConst,
kReplaceZeroBroadcast,
kReplaceRandomBroadcast
};
using ReplaceTypeSelector = std::function<ReplaceType(const HloInstruction*)>;
std::unique_ptr<HloModule> ExtractModule(
const HloInstruction* instruction, int64_t height = -1,
ExtractSelector extract_selector = nullptr,
ReplaceTypeSelector replace_type_selector = nullptr,
bool cross_computation = false);
}
#endif
#include "xla/tools/hlo_extractor.h"
#ifndef _WIN32
#include <unistd.h>
#endif
#include <cstdint>
#include <deque>
#include <memory>
#include <utility>
#include <vector>
#include "absl/container/flat_hash_map.h"
#include "absl/container/flat_hash_set.h"
#include "absl/log/check.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "xla/hlo/ir/dfs_hlo_visitor_with_default.h"
#include "xla/hlo/ir/hlo_clone_context.h"
#include "xla/hlo/ir/hlo_computation.h"
#include "xla/hlo/ir/hlo_instruction.h"
#include "xla/hlo/ir/hlo_module.h"
#include "xla/literal.h"
#include "xla/literal_util.h"
#include "xla/service/compilation_environments.h"
#include "xla/service/hlo_module_config.h"
#include "xla/service/hlo_verifier.h"
#include "xla/shape.h"
#include "xla/shape_util.h"
#include "xla/tests/test_utils.h"
#include "tsl/platform/status.h"
namespace xla {
namespace {
class ExtractionVisitor : public ConstDfsHloVisitorWithDefault {
public:
explicit ExtractionVisitor(
const HloInstruction* root_instruction,
absl::flat_hash_set<const HloInstruction*>* boundary,
ExtractSelector extract_selector,
ReplaceTypeSelector replace_type_selector)
: root_instruction_(root_instruction),
old_module_(root_instruction->GetModule()),
module_(std::make_unique<HloModule>(
"extracted", config_,
std::make_unique<CompilationEnvironments>(
old_module_->comp_envs()))),
clone_context_(module_.get()),
boundary_(boundary),
extract_selector_(extract_selector),
replace_type_selector_(replace_type_selector) {
for (auto computation : old_module_->computations()) {
old_computations_to_builders_.insert(
{computation,
std::make_unique<HloComputation::Builder>(computation->name())});
}
for (auto computation : old_module_->computations()) {
parameter_numbers_[computation] = 0;
}
}
absl::Status HandleParameter(const HloInstruction* parameter) override {
return ReplaceWithParameter(parameter);
}
absl::Status DefaultAction(const HloInstruction* hlo) override {
if ((boundary_ != nullptr && boundary_->contains(hlo) > 0) ||
(extract_selector_ != nullptr && !extract_selector_(hlo))) {
if (replace_type_selector_ != nullptr) {
switch (replace_type_selector_(hlo)) {
case ReplaceType::kReplaceConst:
return ReplaceWithConstant(hlo);
case ReplaceType::kReplaceParam:
CHECK(hlo->parent() == root_instruction_->parent())
<< "Replacing instructions at non-entry computation with "
"parameters is not supported.";
return ReplaceWithParameter(hlo);
case ReplaceType::kReplaceZeroBroadcast:
return ReplaceWithConstantBroadcast(
hlo, ReplaceType::kReplaceZeroBroadcast);
case ReplaceType::kReplaceRandomBroadcast:
return ReplaceWithConstantBroadcast(
hlo, ReplaceType::kReplaceRandomBroadcast);
default:
QCHECK(false) << "Unsupported replacement type";
}
}
return ReplaceWithParameter(hlo);
}
std::vector<HloInstruction*> new_operands;
for (auto operand : hlo->operands()) {
new_operands.push_back(clone_context_.GetInstruction(operand));
}
auto instruction =
hlo->CloneWithNewOperands(hlo->shape(), new_operands, &clone_context_);
auto it = old_computations_to_builders_.find(hlo->parent());
CHECK(it != old_computations_to_builders_.end());
auto builder = it->second.get();
builder->AddInstruction(std::move(instruction));
if (hlo->IsRoot() && hlo != root_instruction_) {
CHECK(clone_context_.FindComputation(hlo->parent()) == nullptr);
auto new_computation = module_->AddEmbeddedComputation(builder->Build());
clone_context_.MapComputation(hlo->parent(), new_computation);
}
return absl::OkStatus();
}
absl::Status FinishVisit(const HloInstruction* ) override {
auto new_entry_computation = module_->AddEntryComputation(
old_computations_to_builders_.at(root_instruction_->parent())->Build());
clone_context_.MapComputation(root_instruction_->parent(),
new_entry_computation);
for (auto computation : old_module_->MakeComputationPostOrder()) {
for (auto old_instruction : computation->MakeInstructionPostOrder()) {
if (auto new_instruction =
clone_context_.FindInstruction(old_instruction)) {
new_instruction->SetAndSanitizeName(old_instruction->name());
}
}
}
for (HloInstruction* instruction : extra_created_instructions_) {
module_->SetAndUniquifyInstrName(instruction, instruction->name());
}
return absl::OkStatus();
}
HloModule* module() { return module_.get(); }
std::unique_ptr<HloModule> ConsumeModule() { return std::move(module_); }
private:
absl::Status ReplaceWithConstant(const HloInstruction* hlo) {
absl::StatusOr<Literal> literal_status = MakeFakeLiteral(hlo->shape());
TF_CHECK_OK(literal_status.status());
auto new_const =
HloInstruction::CreateConstant(std::move(literal_status.value()));
clone_context_.MapInstruction(hlo, new_const.get());
auto it = old_computations_to_builders_.find(hlo->parent());
CHECK(it != old_computations_to_builders_.end());
auto builder = it->second.get();
builder->AddInstruction(std::move(new_const));
return absl::OkStatus();
}
absl::Status ReplaceWithParameter(const HloInstruction* hlo) {
CHECK(parameter_numbers_.contains(hlo->parent()));
auto new_parameter = HloInstruction::CreateParameter(
parameter_numbers_.at(hlo->parent())++, hlo->shape(), hlo->name());
clone_context_.MapInstruction(hlo, new_parameter.get());
CHECK(old_computations_to_builders_.contains(hlo->parent()));
auto builder = old_computations_to_builders_[hlo->parent()].get();
builder->AddInstruction(std::move(new_parameter));
return absl::OkStatus();
}
HloInstruction* ReplaceWithConstantBroadcastHelper(
const Shape& shape, HloComputation::Builder* builder,
ReplaceType replace_type) {
if (shape.IsTuple()) {
std::vector<HloInstruction*> tuple_operands;
for (const auto& subshape : shape.tuple_shapes()) {
tuple_operands.push_back(ReplaceWithConstantBroadcastHelper(
subshape, builder, replace_type));
}
auto zero_tuple =
builder->AddInstruction(HloInstruction::CreateTuple(tuple_operands));
extra_created_instructions_.push_back(zero_tuple);
return zero_tuple;
} else {
Shape constant_shape = ShapeUtil::MakeShape(shape.element_type(), {});
HloInstruction* constant_instruction;
CHECK(replace_type == ReplaceType::kReplaceZeroBroadcast ||
replace_type == ReplaceType::kReplaceRandomBroadcast);
if (replace_type == ReplaceType::kReplaceZeroBroadcast) {
constant_instruction =
builder->AddInstruction(HloInstruction::CreateConstant(
LiteralUtil::Zero(constant_shape.element_type())));
} else {
absl::StatusOr<Literal> literal_status =
MakeFakeLiteral(constant_shape);
TF_CHECK_OK(literal_status.status());
constant_instruction = builder->AddInstruction(
HloInstruction::CreateConstant(std::move(literal_status.value())));
}
extra_created_instructions_.push_back(constant_instruction);
auto broadcast_constant_instruction = builder->AddInstruction(
HloInstruction::CreateBroadcast(shape, constant_instruction, {}));
extra_created_instructions_.push_back(broadcast_constant_instruction);
return broadcast_constant_instruction;
}
}
absl::Status ReplaceWithConstantBroadcast(const HloInstruction* hlo,
ReplaceType replace_type) {
CHECK(replace_type == ReplaceType::kReplaceZeroBroadcast ||
replace_type == ReplaceType::kReplaceRandomBroadcast);
CHECK(old_computations_to_builders_.contains(hlo->parent()));
auto builder = old_computations_to_builders_[hlo->parent()].get();
HloInstruction* zero_broadcast =
ReplaceWithConstantBroadcastHelper(hlo->shape(), builder, replace_type);
clone_context_.MapInstruction(hlo, zero_broadcast);
return absl::OkStatus();
}
const HloInstruction* root_instruction_;
HloModule* old_module_;
HloModuleConfig config_;
std::unique_ptr<HloModule> module_;
HloCloneContext clone_context_;
absl::flat_hash_map<const HloComputation*,
std::unique_ptr<HloComputation::Builder>>
old_computations_to_builders_;
absl::flat_hash_map<const HloComputation*, int> parameter_numbers_;
absl::flat_hash_set<const HloInstruction*>* boundary_;
ExtractSelector extract_selector_;
ReplaceTypeSelector replace_type_selector_;
std::vector<HloInstruction*> extra_created_instructions_;
};
void ComputeBoundary(const HloInstruction* root, int64_t limit,
absl::flat_hash_set<const HloInstruction*>* boundary) {
std::deque<const HloInstruction*> worklist;
absl::flat_hash_map<const HloInstruction*, int64_t> visited;
worklist.push_back(root);
visited.emplace(root, 0);
while (!worklist.empty()) {
auto hlo = worklist.front();
worklist.pop_front();
int64_t hops = visited[hlo];
if (hops > limit) {
boundary->insert(hlo);
continue;
}
for (const HloInstruction* operand : hlo->operands()) {
if (visited.count(operand)) {
continue;
}
worklist.push_back(operand);
visited.emplace(operand, hops + 1);
}
}
}
}
std::unique_ptr<HloModule> ExtractModule(
const HloInstruction* instruction, int64_t height,
ExtractSelector extract_selector, ReplaceTypeSelector replace_type_selector,
bool cross_computation) {
QCHECK(height == -1 || !cross_computation)
<< "Boundary cannnot be calculated across the computations.";
absl::flat_hash_set<const HloInstruction*> boundary;
if (height != -1) {
ComputeBoundary(instruction, height, &boundary);
}
ExtractionVisitor visitor(instruction, &boundary, extract_selector,
replace_type_selector);
TF_CHECK_OK(instruction->Accept(&visitor, true,
false,
cross_computation));
ExtractionVisitor cleanup_visitor(
visitor.module()->entry_computation()->root_instruction(),
nullptr,
nullptr,
nullptr);
TF_CHECK_OK(visitor.module()->entry_computation()->root_instruction()->Accept(
&cleanup_visitor, true,
false,
false));
HloVerifier verifier(false,
true);
TF_CHECK_OK(verifier.Run(cleanup_visitor.module()).status());
return cleanup_visitor.ConsumeModule();
}
} | #include "xla/tools/hlo_extractor.h"
#include <memory>
#include <string>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "xla/hlo/ir/hlo_instruction.h"
#include "xla/hlo/ir/hlo_opcode.h"
#include "xla/hlo/utils/hlo_matchers.h"
#include "xla/tests/hlo_test_base.h"
#include "tsl/platform/statusor.h"
namespace xla {
namespace {
namespace op = testing::opcode_matchers;
using HloExtractorTest = HloTestBase;
TEST_F(HloExtractorTest, ExtractTopLevel) {
const std::string& hlo_string = R"(
HloModule test
ENTRY %entry {
param.0 = f32[4]{0} parameter(0)
negate = f32[4]{0} negate(f32[4]{0} param.0)
ROOT exp = f32[4]{0} exponential(f32[4]{0} negate)
}
)";
TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> hlo_module,
ParseAndReturnVerifiedModule(hlo_string));
{
auto extracted_module =
ExtractModule(FindInstruction(hlo_module.get(), "exp"));
EXPECT_THAT(extracted_module->entry_computation()->root_instruction(),
op::Exp(op::Negate(op::Parameter(0))));
}
{
auto extracted_module =
ExtractModule(FindInstruction(hlo_module.get(), "exp"), 0);
EXPECT_THAT(extracted_module->entry_computation()->root_instruction(),
op::Exp(op::Parameter(0)));
}
{
auto extracted_module = ExtractModule(
FindInstruction(hlo_module.get(), "negate"), 0);
EXPECT_THAT(extracted_module->entry_computation()->root_instruction(),
op::Negate(op::Parameter(0)));
}
}
TEST_F(HloExtractorTest, ExtractDag) {
const std::string& hlo_string = R"(
HloModule test
ENTRY %entry {
param.0 = f32[4]{0} parameter(0)
tanh = f32[4]{0} tanh(f32[4]{0} param.0)
negate = f32[4]{0} negate(f32[4]{0} tanh)
exp = f32[4]{0} exponential(f32[4]{0} negate)
ROOT add = f32[4]{0} add(f32[4]{0} negate, f32[4]{0} exp)
}
)";
TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> hlo_module,
ParseAndReturnVerifiedModule(hlo_string));
{
auto extracted_module =
ExtractModule(FindInstruction(hlo_module.get(), "exp"));
EXPECT_THAT(extracted_module->entry_computation()->root_instruction(),
op::Exp(op::Negate(op::Tanh(op::Parameter(0)))));
}
{
auto extracted_module =
ExtractModule(FindInstruction(hlo_module.get(), "add"), 0);
EXPECT_THAT(extracted_module->entry_computation()->root_instruction(),
op::Add(op::Parameter(0), op::Parameter(1)));
}
{
auto extracted_module =
ExtractModule(FindInstruction(hlo_module.get(), "add"), 1);
EXPECT_THAT(extracted_module->entry_computation()->root_instruction(),
op::Add(op::Negate(op::Parameter(0)),
op::Exp(op::Negate(op::Parameter(0)))));
}
{
auto extracted_module =
ExtractModule(FindInstruction(hlo_module.get(), "add"), 2);
EXPECT_THAT(extracted_module->entry_computation()->root_instruction(),
op::Add(op::Negate(op::Tanh(op::Parameter(0))),
op::Exp(op::Negate(op::Tanh(op::Parameter(0))))));
}
}
TEST_F(HloExtractorTest, ExtractWithConstant) {
const std::string& hlo_string = R"(
HloModule test
ENTRY %entry {
p = f32[4]{0} parameter(0)
tanh = f32[4]{0} tanh(p)
c = f32[4]{0} constant({1, 2, 3, 4})
ROOT add = f32[4]{0} add(tanh, c)
}
)";
TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> hlo_module,
ParseAndReturnVerifiedModule(hlo_string));
{
auto extracted_module =
ExtractModule(FindInstruction(hlo_module.get(), "add"), 0);
EXPECT_THAT(extracted_module->entry_computation()->root_instruction(),
op::Add(op::Parameter(0), op::Parameter(1)));
}
{
auto extracted_module =
ExtractModule(FindInstruction(hlo_module.get(), "add"), 1);
EXPECT_THAT(extracted_module->entry_computation()->root_instruction(),
op::Add(op::Tanh(op::Parameter(0)), op::Constant()));
}
}
TEST_F(HloExtractorTest, ExtractFromMultipleComputation) {
const std::string& hlo_string = R"(
HloModule axpy_module
calculate_alpha {
c.1 = f32[] constant(1)
c.2 = f32[] constant(2)
add.0 = f32[] add(c.1, c.2)
c.3 = f32[] constant(4)
ROOT ret = f32[] subtract(add.0, c.3)
}
ENTRY axpy_computation {
alpha = f32[] call(), to_apply=calculate_alpha
broadcast = f32[10] broadcast(alpha), dimensions={}
x = f32[10] parameter(0)
ax = f32[10] multiply(broadcast, x)
y = f32[10] parameter(1)
ROOT add.1 = f32[10] add(ax, y)
}
)";
TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> hlo_module,
ParseAndReturnVerifiedModule(hlo_string));
HloInstruction* inst = FindInstruction(hlo_module.get(), "add.0");
EXPECT_THAT(inst, op::Add());
auto extract_selector = [&inst](const HloInstruction* hlo_inst) {
return hlo_inst != inst;
};
{
auto replace_type_selector = [](const HloInstruction* hlo_inst) {
return ReplaceType::kReplaceConst;
};
auto extracted_module =
ExtractModule(hlo_module->entry_computation()->root_instruction(),
-1, extract_selector,
replace_type_selector,
true);
EXPECT_EQ(extracted_module->computation_count(), 2);
auto calculate_alpha_root_instruction =
FindComputation(extracted_module.get(), "calculate_alpha")
->root_instruction();
EXPECT_THAT(calculate_alpha_root_instruction,
op::Subtract(op::Constant(), op::Constant()));
}
{
auto replace_type_selector = [](const HloInstruction* hlo_inst) {
return ReplaceType::kReplaceZeroBroadcast;
};
auto extracted_module =
ExtractModule(hlo_module->entry_computation()->root_instruction(),
-1, extract_selector,
replace_type_selector,
true);
EXPECT_EQ(extracted_module->computation_count(), 2);
auto calculate_alpha_root_instruction =
FindComputation(extracted_module.get(), "calculate_alpha")
->root_instruction();
EXPECT_THAT(calculate_alpha_root_instruction,
op::Subtract(op::Broadcast(op::Constant()), op::Constant()));
}
}
TEST_F(HloExtractorTest, HloSelector) {
const std::string& hlo_string = R"(
HloModule axpy_module
calculate_alpha {
c.1 = f32[] constant(1)
c.2 = f32[] constant(2)
c.3 = f32[] add(c.1, c.2)
c.4 = f32[] constant(4)
ROOT ret = f32[] multiply(c.4, c.3)
}
ENTRY axpy_computation {
p.0 = f32[10] parameter(0)
p.1 = f32[10] parameter(1)
add.0 = f32[10] add(p.0, p.1)
alpha = f32[] call(), to_apply=calculate_alpha
broadcast = f32[10] broadcast(alpha), dimensions={}
p.2 = f32[10] parameter(2)
y = f32[10] multiply(broadcast, p.2)
x = f32[10] subtract(y, add.0)
p.3 = f32[10] parameter(3)
ROOT add = f32[10] add(x, p.3)
}
)";
TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> hlo_module,
ParseAndReturnVerifiedModule(hlo_string));
HloInstruction* inst =
FindInstruction(hlo_module.get(), HloOpcode::kSubtract);
EXPECT_NE(inst, nullptr);
EXPECT_THAT(inst, op::Subtract(op::Multiply(), op::Add()));
{
auto hlo_selector = [](const HloInstruction* hlo_inst) -> bool {
return hlo_inst->opcode() != HloOpcode::kCall;
};
auto extracted_module = ExtractModule(inst, -1, hlo_selector);
EXPECT_EQ(extracted_module->computation_count(), 1);
EXPECT_THAT(extracted_module->entry_computation()->root_instruction(),
op::Subtract(op::Multiply(op::Broadcast(op::Parameter()),
op::Parameter()),
op::Add(op::Parameter(), op::Parameter())));
}
{
auto hlo_selector = [](const HloInstruction* hlo_inst) -> bool {
return hlo_inst->opcode() != HloOpcode::kBroadcast;
};
auto extracted_module = ExtractModule(inst, 2, hlo_selector);
EXPECT_EQ(extracted_module->computation_count(), 1);
EXPECT_THAT(extracted_module->entry_computation()->root_instruction(),
op::Subtract(op::Multiply(op::Parameter(), op::Parameter()),
op::Add(op::Parameter(), op::Parameter())));
}
{
auto hlo_selector = [](const HloInstruction* hlo_inst) -> bool {
return hlo_inst->opcode() != HloOpcode::kBroadcast;
};
auto replace_type_selector =
[](const HloInstruction* hlo_inst) -> ReplaceType {
return ReplaceType::kReplaceConst;
};
auto extracted_module =
ExtractModule(inst, 2, hlo_selector, replace_type_selector);
EXPECT_EQ(extracted_module->computation_count(), 1);
EXPECT_THAT(extracted_module->entry_computation()->root_instruction(),
op::Subtract(op::Multiply(op::Constant(), op::Parameter()),
op::Add(op::Parameter(), op::Parameter())));
}
{
auto hlo_selector = [](const HloInstruction* hlo_inst) -> bool {
return hlo_inst->opcode() != HloOpcode::kAdd;
};
auto extracted_module = ExtractModule(inst, -1, hlo_selector);
EXPECT_EQ(extracted_module->computation_count(), 2);
EXPECT_THAT(extracted_module->entry_computation()->root_instruction(),
op::Subtract(op::Multiply(), op::Parameter()));
}
{
auto hlo_selector = [](const HloInstruction* hlo_inst) -> bool {
return hlo_inst->opcode() != HloOpcode::kSubtract;
};
auto replace_type_selector =
[](const HloInstruction* hlo_inst) -> ReplaceType {
return ReplaceType::kReplaceConst;
};
auto extracted_module =
ExtractModule(hlo_module->entry_computation()->root_instruction(),
2, hlo_selector, replace_type_selector);
EXPECT_EQ(extracted_module->computation_count(), 1);
EXPECT_THAT(extracted_module->entry_computation()->root_instruction(),
op::Add(op::Constant(), op::Parameter()));
}
{
auto hlo_selector = [](const HloInstruction* hlo_inst) -> bool {
if (hlo_inst->opcode() != HloOpcode::kBroadcast &&
hlo_inst->opcode() != HloOpcode::kAdd) {
return true;
}
return false;
};
auto replace_type_selector =
[](const HloInstruction* hlo_inst) -> ReplaceType {
if (hlo_inst->opcode() == HloOpcode::kBroadcast) {
return ReplaceType::kReplaceConst;
}
return ReplaceType::kReplaceParam;
};
auto extracted_module =
ExtractModule(inst, 2, hlo_selector, replace_type_selector);
EXPECT_EQ(extracted_module->computation_count(), 1);
EXPECT_THAT(extracted_module->entry_computation()->root_instruction(),
op::Subtract(op::Multiply(op::Constant(), op::Parameter()),
op::Parameter()));
}
}
TEST_F(HloExtractorTest, ReplaceTupleWithConstant) {
const std::string& hlo_string = R"(
HloModule test
ENTRY %entry {
param.0 = f32[4]{0} parameter(0)
tuple.0 = (f32[4]{0}, f32[4]{0}) rng-bit-generator(f32[4]{0} param.0), algorithm=rng_default
negate = f32[4]{0} negate(f32[4]{0} param.0)
tuple.1 = ((f32[4]{0}, f32[4]{0}), f32[4]{0}) tuple(tuple.0, negate)
element = f32[4]{0} get-tuple-element(((f32[4]{0}, f32[4]{0}), f32[4]{0}) tuple.1), index=1
ROOT add = f32[4]{0} add(element, param.0)
}
)";
TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> hlo_module,
ParseAndReturnVerifiedModule(hlo_string));
{
auto hlo_selector = [](const HloInstruction* hlo_inst) -> bool {
return hlo_inst->opcode() != HloOpcode::kTuple;
};
auto replace_type_selector =
[](const HloInstruction* hlo_inst) -> ReplaceType {
return ReplaceType::kReplaceConst;
};
auto extracted_module =
ExtractModule(FindInstruction(hlo_module.get(), "add"),
-1, hlo_selector, replace_type_selector);
EXPECT_THAT(extracted_module->entry_computation()->root_instruction(),
op::Add(op::GetTupleElement(op::Constant()), op::Parameter()));
}
{
auto hlo_selector = [](const HloInstruction* hlo_inst) -> bool {
return hlo_inst->opcode() != HloOpcode::kGetTupleElement;
};
auto replace_type_selector =
[](const HloInstruction* hlo_inst) -> ReplaceType {
return ReplaceType::kReplaceZeroBroadcast;
};
auto extracted_module =
ExtractModule(FindInstruction(hlo_module.get(), "add"),
-1, hlo_selector, replace_type_selector);
EXPECT_THAT(extracted_module->entry_computation()->root_instruction(),
op::Add(op::Broadcast(), op::Parameter()));
}
{
auto hlo_selector = [](const HloInstruction* hlo_inst) -> bool {
return hlo_inst->opcode() != HloOpcode::kGetTupleElement;
};
auto replace_type_selector =
[](const HloInstruction* hlo_inst) -> ReplaceType {
return ReplaceType::kReplaceRandomBroadcast;
};
auto extracted_module =
ExtractModule(FindInstruction(hlo_module.get(), "add"),
-1, hlo_selector, replace_type_selector);
EXPECT_THAT(extracted_module->entry_computation()->root_instruction(),
op::Add(op::Broadcast(), op::Parameter()));
}
{
auto hlo_selector = [](const HloInstruction* hlo_inst) -> bool {
return hlo_inst->opcode() != HloOpcode::kTuple;
};
auto replace_type_selector =
[](const HloInstruction* hlo_inst) -> ReplaceType {
return ReplaceType::kReplaceZeroBroadcast;
};
auto extracted_module =
ExtractModule(FindInstruction(hlo_module.get(), "add"),
-1, hlo_selector, replace_type_selector);
EXPECT_THAT(
extracted_module->entry_computation()->root_instruction(),
op::Add(op::GetTupleElement(op::Tuple(op::Tuple(), op::Broadcast())),
op::Parameter()));
}
{
auto hlo_selector = [](const HloInstruction* hlo_inst) -> bool {
return hlo_inst->opcode() != HloOpcode::kTuple;
};
auto replace_type_selector =
[](const HloInstruction* hlo_inst) -> ReplaceType {
return ReplaceType::kReplaceRandomBroadcast;
};
auto extracted_module =
ExtractModule(FindInstruction(hlo_module.get(), "add"),
-1, hlo_selector, replace_type_selector);
EXPECT_THAT(
extracted_module->entry_computation()->root_instruction(),
op::Add(op::GetTupleElement(op::Tuple(op::Tuple(), op::Broadcast())),
op::Parameter()));
}
}
}
} |
304 | #ifndef XLA_PJRT_CPU_TRACKED_TFRT_CPU_DEVICE_BUFFER_H_
#define XLA_PJRT_CPU_TRACKED_TFRT_CPU_DEVICE_BUFFER_H_
#include <cstddef>
#include <cstdint>
#include <cstdlib>
#include <memory>
#include <utility>
#include "absl/container/inlined_vector.h"
#include "absl/functional/any_invocable.h"
#include "absl/status/statusor.h"
#include "absl/types/span.h"
#include "xla/cpu_function_runtime.h"
#include "xla/service/cpu/cpu_event.h"
#include "xla/shape_util.h"
#include "xla/tsl/concurrency/async_value_ref.h"
#include "xla/util.h"
#include "tsl/platform/mem.h"
#include "tsl/platform/statusor.h"
namespace xla {
class MaybeOwningCpuMemory {
public:
using OwnedDataPtr = std::unique_ptr<uint8_t[], void (*)(void*)>;
MaybeOwningCpuMemory() = default;
MaybeOwningCpuMemory(void* buf, size_t size) : buf_(buf), size_(size) {}
MaybeOwningCpuMemory(OwnedDataPtr data, size_t size)
: buf_(data.get()), data_(std::move(data)), size_(size) {}
MaybeOwningCpuMemory(MaybeOwningCpuMemory&&) = default;
MaybeOwningCpuMemory& operator=(MaybeOwningCpuMemory&&) = default;
MaybeOwningCpuMemory(const MaybeOwningCpuMemory&) = delete;
MaybeOwningCpuMemory& operator=(const MaybeOwningCpuMemory&) = delete;
static absl::StatusOr<tsl::AsyncValueRef<MaybeOwningCpuMemory>>
AllocateAvailableAvr(size_t size) {
TF_ASSIGN_OR_RETURN(auto memory, Allocate(size));
return tsl::MakeAvailableAsyncValueRef<MaybeOwningCpuMemory>(
std::move(memory));
}
static absl::StatusOr<MaybeOwningCpuMemory> Allocate(size_t size) {
uint8_t* data = static_cast<uint8_t*>(
tsl::port::AlignedMalloc(size, cpu_function_runtime::MinAlign()));
if (!data) {
return ResourceExhausted("Out of memory allocating %d bytes.", size);
}
return MaybeOwningCpuMemory(OwnedDataPtr{data, tsl::port::AlignedFree},
size);
}
void* data() const { return buf_; }
size_t size() const { return size_; }
bool owns_data() const { return data_ != nullptr; }
private:
void* buf_ = nullptr;
OwnedDataPtr data_ = {nullptr, free};
size_t size_ = 0;
};
class TrackedTfrtCpuDeviceBuffer {
public:
TrackedTfrtCpuDeviceBuffer(
bool is_tuple, bool owns_buffers,
absl::InlinedVector<tsl::AsyncValueRef<MaybeOwningCpuMemory>, 4> buffers,
absl::InlinedVector<tsl::AsyncValueRef<CpuEvent>, 4> definition_events,
absl::AnyInvocable<void() &&> on_delete_callback = nullptr);
TrackedTfrtCpuDeviceBuffer(
bool is_tuple, bool owns_buffers,
absl::InlinedVector<tsl::AsyncValueRef<MaybeOwningCpuMemory>, 4> buffers,
tsl::AsyncValueRef<CpuEvent> definition_event,
absl::AnyInvocable<void() &&> on_delete_callback = nullptr);
TrackedTfrtCpuDeviceBuffer(
bool is_tuple, bool owns_buffers,
absl::InlinedVector<tsl::AsyncValueRef<MaybeOwningCpuMemory>, 4> buffers,
absl::InlinedVector<size_t, 4> buffer_sizes,
absl::InlinedVector<tsl::AsyncValueRef<CpuEvent>, 4> definition_events,
absl::AnyInvocable<void() &&> on_delete_callback = nullptr);
TrackedTfrtCpuDeviceBuffer(
bool is_tuple, bool owns_buffers,
absl::InlinedVector<tsl::AsyncValueRef<MaybeOwningCpuMemory>, 4> buffers,
absl::InlinedVector<size_t, 4> buffer_sizes,
tsl::AsyncValueRef<CpuEvent> definition_event,
absl::AnyInvocable<void() &&> on_delete_callback = nullptr);
TrackedTfrtCpuDeviceBuffer(TrackedTfrtCpuDeviceBuffer&&) = default;
TrackedTfrtCpuDeviceBuffer& operator=(TrackedTfrtCpuDeviceBuffer&&) = default;
TrackedTfrtCpuDeviceBuffer(const TrackedTfrtCpuDeviceBuffer&) = delete;
TrackedTfrtCpuDeviceBuffer& operator=(const TrackedTfrtCpuDeviceBuffer&) =
delete;
~TrackedTfrtCpuDeviceBuffer();
absl::Span<const tsl::AsyncValueRef<MaybeOwningCpuMemory>> Buffers() {
return buffers_;
}
absl::Span<const size_t> BufferSizes() { return buffer_sizes_; }
tsl::AsyncValueRef<MaybeOwningCpuMemory> Buffer(
const ShapeIndex& shape_index);
size_t BufferSize(const ShapeIndex& shape_index);
const tsl::AsyncValueRef<CpuEvent>& definition_event() const {
return definition_event_;
}
absl::Span<const tsl::AsyncValueRef<CpuEvent>> UsageEvents() const {
return usage_events_;
}
void AddUsageEvents(absl::Span<tsl::AsyncValueRef<CpuEvent>> events);
absl::InlinedVector<tsl::AsyncValueRef<CpuEvent>, 4>
LockUseAndTransferUsageEvents();
void ReleaseDeviceMemory();
bool owns_buffers() const { return owns_buffers_; }
private:
bool is_tuple_;
bool owns_buffers_;
tsl::AsyncValueRef<MaybeOwningCpuMemory> tuple_index_table_;
absl::InlinedVector<tsl::AsyncValueRef<MaybeOwningCpuMemory>, 4> buffers_;
absl::InlinedVector<size_t, 4> buffer_sizes_;
tsl::AsyncValueRef<CpuEvent> definition_event_;
absl::InlinedVector<tsl::AsyncValueRef<CpuEvent>, 4> usage_events_;
absl::AnyInvocable<void() &&> on_delete_callback_;
};
}
#endif
#include "xla/pjrt/cpu/tracked_tfrt_cpu_device_buffer.h"
#include <atomic>
#include <cstddef>
#include <cstdint>
#include <utility>
#include "absl/base/casts.h"
#include "absl/container/inlined_vector.h"
#include "absl/functional/any_invocable.h"
#include "absl/log/check.h"
#include "absl/status/status.h"
#include "absl/synchronization/mutex.h"
#include "absl/types/span.h"
#include "xla/service/cpu/cpu_event.h"
#include "xla/shape_util.h"
#include "xla/tsl/concurrency/async_value_ref.h"
namespace xla {
namespace {
tsl::AsyncValueRef<CpuEvent> AfterAll(
absl::Span<const tsl::AsyncValueRef<CpuEvent>> events) {
if (events.empty()) return tsl::MakeAvailableAsyncValueRef<CpuEvent>();
struct State {
State(int count, tsl::AsyncValueRef<CpuEvent> after_all)
: count(count), after_all(std::move(after_all)) {}
std::atomic<int> count;
tsl::AsyncValueRef<CpuEvent> after_all;
absl::Mutex mutex;
absl::Status error;
};
auto after_all = tsl::MakeConstructedAsyncValueRef<CpuEvent>();
auto* state = new State(events.size(), after_all);
for (auto& event : events) {
event.AndThen([state, event = event.AsPtr()]() {
if (event.IsError()) {
absl::MutexLock lock(&state->mutex);
state->error = event.GetError();
}
if (state->count.fetch_sub(1, std::memory_order_acq_rel) == 1) {
if (!state->error.ok()) {
state->after_all.SetError(state->error);
} else {
state->after_all.SetStateConcrete();
}
delete state;
}
});
}
return after_all;
}
}
TrackedTfrtCpuDeviceBuffer::TrackedTfrtCpuDeviceBuffer(
bool is_tuple, bool owns_buffers,
absl::InlinedVector<tsl::AsyncValueRef<MaybeOwningCpuMemory>, 4> buffers,
absl::InlinedVector<tsl::AsyncValueRef<CpuEvent>, 4> definition_events,
absl::AnyInvocable<void() &&> on_delete_callback)
: TrackedTfrtCpuDeviceBuffer(is_tuple, owns_buffers, std::move(buffers),
AfterAll(definition_events),
std::move(on_delete_callback)) {}
TrackedTfrtCpuDeviceBuffer::TrackedTfrtCpuDeviceBuffer(
bool is_tuple, bool owns_buffers,
absl::InlinedVector<tsl::AsyncValueRef<MaybeOwningCpuMemory>, 4> buffers,
absl::InlinedVector<size_t, 4> buffer_sizes,
absl::InlinedVector<tsl::AsyncValueRef<CpuEvent>, 4> definition_events,
absl::AnyInvocable<void() &&> on_delete_callback)
: TrackedTfrtCpuDeviceBuffer(
is_tuple, owns_buffers, std::move(buffers), std::move(buffer_sizes),
AfterAll(definition_events), std::move(on_delete_callback)) {}
TrackedTfrtCpuDeviceBuffer::TrackedTfrtCpuDeviceBuffer(
bool is_tuple, bool owns_buffers,
absl::InlinedVector<tsl::AsyncValueRef<MaybeOwningCpuMemory>, 4> buffers,
tsl::AsyncValueRef<CpuEvent> definition_event,
absl::AnyInvocable<void() &&> on_delete_callback)
: is_tuple_(is_tuple),
owns_buffers_(owns_buffers),
buffers_(std::move(buffers)),
definition_event_(std::move(definition_event)),
on_delete_callback_(std::move(on_delete_callback)) {
DCHECK(definition_event_);
for (const auto& buffer : buffers_) {
CHECK(buffer.IsConcrete());
buffer_sizes_.push_back(buffer->size());
}
if (is_tuple) {
size_t index_table_byte_size = buffers_.size() * sizeof(void*);
tuple_index_table_ =
MaybeOwningCpuMemory::AllocateAvailableAvr(index_table_byte_size)
.value();
uintptr_t* index_table =
reinterpret_cast<uintptr_t*>(tuple_index_table_->data());
for (int i = 0; i < buffers_.size(); ++i) {
index_table[i] = absl::bit_cast<uintptr_t>(buffers_[i]->data());
}
}
}
TrackedTfrtCpuDeviceBuffer::TrackedTfrtCpuDeviceBuffer(
bool is_tuple, bool owns_buffers,
absl::InlinedVector<tsl::AsyncValueRef<MaybeOwningCpuMemory>, 4> buffers,
absl::InlinedVector<size_t, 4> buffer_sizes,
tsl::AsyncValueRef<CpuEvent> definition_event,
absl::AnyInvocable<void() &&> on_delete_callback)
: is_tuple_(is_tuple),
owns_buffers_(owns_buffers),
buffers_(std::move(buffers)),
buffer_sizes_(std::move(buffer_sizes)),
definition_event_(std::move(definition_event)),
on_delete_callback_(std::move(on_delete_callback)) {
DCHECK(definition_event_);
if (is_tuple) {
tuple_index_table_ =
tsl::MakeUnconstructedAsyncValueRef<MaybeOwningCpuMemory>();
tsl::RunWhenReady(
absl::MakeConstSpan(buffers_),
[buffers = buffers_, tuple_index_table = tuple_index_table_] {
size_t index_table_byte_size = buffers.size() * sizeof(void*);
tuple_index_table.emplace(
MaybeOwningCpuMemory::Allocate(index_table_byte_size).value());
uintptr_t* index_table =
reinterpret_cast<uintptr_t*>(tuple_index_table->data());
for (int i = 0; i < buffers.size(); ++i) {
index_table[i] = absl::bit_cast<uintptr_t>(buffers[i]->data());
}
});
}
}
TrackedTfrtCpuDeviceBuffer::~TrackedTfrtCpuDeviceBuffer() {
ReleaseDeviceMemory();
if (on_delete_callback_) {
std::move(on_delete_callback_)();
}
}
tsl::AsyncValueRef<MaybeOwningCpuMemory> TrackedTfrtCpuDeviceBuffer::Buffer(
const ShapeIndex& shape_index) {
if (shape_index.empty()) {
if (is_tuple_) return tuple_index_table_;
return buffers_[0];
}
CHECK(is_tuple_);
CHECK_EQ(shape_index.size(), 1) << "nested tuple not supported";
return buffers_[shape_index[0]];
}
size_t TrackedTfrtCpuDeviceBuffer::BufferSize(const ShapeIndex& shape_index) {
if (shape_index.empty()) {
if (is_tuple_) return buffers_.size() * sizeof(void*);
return buffer_sizes_[0];
}
CHECK(is_tuple_);
CHECK_EQ(shape_index.size(), 1) << "nested tuple not supported";
return buffer_sizes_[shape_index[0]];
}
void TrackedTfrtCpuDeviceBuffer::AddUsageEvents(
absl::Span<tsl::AsyncValueRef<CpuEvent>> events) {
if (usage_events_.size() >= 1024) {
int i = 0;
while (i < usage_events_.size()) {
auto& event = usage_events_[i];
if (event.IsAvailable()) {
using std::swap;
swap(event, usage_events_.back());
usage_events_.pop_back();
continue;
}
++i;
}
}
for (auto& ev : events) {
usage_events_.push_back(std::move(ev));
}
}
absl::InlinedVector<tsl::AsyncValueRef<CpuEvent>, 4>
TrackedTfrtCpuDeviceBuffer::LockUseAndTransferUsageEvents() {
return std::move(usage_events_);
}
void TrackedTfrtCpuDeviceBuffer::ReleaseDeviceMemory() {
tuple_index_table_.reset();
buffers_.clear();
definition_event_.reset();
usage_events_.clear();
}
} | #include "xla/pjrt/cpu/tracked_tfrt_cpu_device_buffer.h"
#include <cstring>
#include <string>
#include <gtest/gtest.h>
#include "xla/service/cpu/cpu_event.h"
#include "xla/tsl/concurrency/async_value.h"
#include "xla/tsl/concurrency/async_value_ref.h"
#include "tsl/platform/env.h"
#include "tsl/platform/statusor.h"
#include "tsl/platform/threadpool.h"
namespace xla {
namespace {
using ::tsl::BlockUntilReady;
using ::tsl::MakeConstructedAsyncValueRef;
using ::tsl::MakeUnconstructedAsyncValueRef;
using ::tsl::thread::ThreadPool;
TEST(TrackedTfrtCpuDeviceBufferTest, Basic) {
std::string expected = "tracked_tfrt_cpu_device_buffer_test";
TF_ASSERT_OK_AND_ASSIGN(
auto buffer, MaybeOwningCpuMemory::AllocateAvailableAvr(expected.size()));
auto definition_event = MakeConstructedAsyncValueRef<CpuEvent>();
ThreadPool thread_pool(tsl::Env::Default(), "tracked_buffer_test",
4);
thread_pool.Schedule([&]() {
std::memcpy(buffer->data(), expected.data(), expected.size());
definition_event.SetStateConcrete();
});
TrackedTfrtCpuDeviceBuffer tracked_buffer(
false, true, {buffer}, definition_event,
nullptr);
BlockUntilReady(tracked_buffer.definition_event().GetAsyncValue());
auto result = tracked_buffer.Buffers()[0];
ASSERT_TRUE(result.IsAvailable());
EXPECT_EQ(
std::string(static_cast<const char*>(result->data()), result->size()),
expected);
}
TEST(TrackedTfrtCpuDeviceBufferTest, Tuple) {
std::string expected_0 = "tracked_tfrt_cpu_device_buffer_test";
std::string expected_1 = "tuple";
TF_ASSERT_OK_AND_ASSIGN(
auto buffer_0,
MaybeOwningCpuMemory::AllocateAvailableAvr(expected_0.size()));
TF_ASSERT_OK_AND_ASSIGN(
auto buffer_1,
MaybeOwningCpuMemory::AllocateAvailableAvr(expected_1.size()));
auto definition_event_0 = MakeConstructedAsyncValueRef<CpuEvent>();
auto definition_event_1 = MakeConstructedAsyncValueRef<CpuEvent>();
ThreadPool thread_pool(tsl::Env::Default(), "tracked_buffer_test",
4);
thread_pool.Schedule([&]() {
std::memcpy(buffer_0->data(), expected_0.data(), expected_0.size());
definition_event_0.SetStateConcrete();
});
thread_pool.Schedule([&]() {
std::memcpy(buffer_1->data(), expected_1.data(), expected_1.size());
definition_event_1.SetStateConcrete();
});
TrackedTfrtCpuDeviceBuffer tracked_buffer(
true, true, {buffer_0, buffer_1},
{definition_event_0, definition_event_1},
nullptr);
BlockUntilReady(tracked_buffer.definition_event().GetAsyncValue());
auto result_0 = tracked_buffer.Buffers()[0];
auto result_1 = tracked_buffer.Buffers()[1];
ASSERT_TRUE(result_0.IsAvailable());
ASSERT_TRUE(result_1.IsAvailable());
EXPECT_EQ(
std::string(static_cast<const char*>(result_0->data()), result_0->size()),
expected_0);
EXPECT_EQ(
std::string(static_cast<const char*>(result_1->data()), result_1->size()),
expected_1);
}
TEST(TrackedTfrtCpuDeviceBufferTest, BasicError) {
TF_ASSERT_OK_AND_ASSIGN(auto buffer,
MaybeOwningCpuMemory::AllocateAvailableAvr(64));
auto definition_event = MakeConstructedAsyncValueRef<CpuEvent>();
ThreadPool thread_pool(tsl::Env::Default(), "tracked_buffer_test",
4);
thread_pool.Schedule([&]() {
definition_event.SetError("tracked_tfrt_cpu_device_buffer_test error.");
});
TrackedTfrtCpuDeviceBuffer tracked_buffer(
false, true, {buffer}, definition_event,
nullptr);
BlockUntilReady(tracked_buffer.definition_event().GetAsyncValue());
ASSERT_TRUE(tracked_buffer.definition_event().IsError());
EXPECT_EQ(tracked_buffer.definition_event().GetError().message(),
"tracked_tfrt_cpu_device_buffer_test error.");
}
TEST(TrackedTfrtCpuDeviceBufferTest, TupleError) {
std::string expected = "tracked_tfrt_cpu_device_buffer_test";
TF_ASSERT_OK_AND_ASSIGN(
auto buffer_0,
MaybeOwningCpuMemory::AllocateAvailableAvr(expected.size()));
TF_ASSERT_OK_AND_ASSIGN(
auto buffer_1,
MaybeOwningCpuMemory::AllocateAvailableAvr(expected.size()));
auto definition_event_0 = MakeConstructedAsyncValueRef<CpuEvent>();
auto definition_event_1 = MakeConstructedAsyncValueRef<CpuEvent>();
ThreadPool thread_pool(tsl::Env::Default(), "tracked_buffer_test",
4);
thread_pool.Schedule([&]() {
std::memcpy(buffer_0->data(), expected.data(), expected.size());
definition_event_0.SetStateConcrete();
});
thread_pool.Schedule([&]() {
definition_event_1.SetError(
"tracked_tfrt_cpu_device_buffer_test tuple error.");
});
TrackedTfrtCpuDeviceBuffer tracked_buffer(
true, true, {buffer_0, buffer_1},
{definition_event_0, definition_event_1},
nullptr);
BlockUntilReady(tracked_buffer.definition_event().GetAsyncValue());
ASSERT_TRUE(tracked_buffer.definition_event().IsError());
EXPECT_EQ(tracked_buffer.definition_event().GetError().message(),
"tracked_tfrt_cpu_device_buffer_test tuple error.");
}
TEST(TrackedTfrtCpuDeviceBufferTest, DelayedAllocation) {
std::string expected = "tracked_tfrt_cpu_device_buffer_test";
auto buffer = MakeUnconstructedAsyncValueRef<MaybeOwningCpuMemory>();
auto malloc_event = MakeConstructedAsyncValueRef<CpuEvent>();
malloc_event.AndThen([buffer_copy = buffer.CopyRef(),
buffer_size = expected.size()] {
buffer_copy.emplace(MaybeOwningCpuMemory::Allocate(buffer_size).value());
});
auto definition_event = MakeConstructedAsyncValueRef<CpuEvent>();
TrackedTfrtCpuDeviceBuffer tracked_buffer(false,
true, {buffer},
{expected.size()}, definition_event,
nullptr);
auto result = tracked_buffer.Buffers()[0];
ASSERT_FALSE(result.IsAvailable());
ASSERT_EQ(tracked_buffer.BufferSizes()[0], expected.size());
ThreadPool thread_pool(tsl::Env::Default(), "tracked_buffer_test",
4);
thread_pool.Schedule([&]() {
malloc_event.SetStateConcrete();
std::memcpy(buffer->data(), expected.data(), expected.size());
definition_event.SetStateConcrete();
});
BlockUntilReady(tracked_buffer.definition_event().GetAsyncValue());
EXPECT_EQ(
std::string(static_cast<const char*>(result->data()), result->size()),
expected);
}
TEST(TrackedTfrtCpuDeviceBufferTest, DelayedAllocationTuple) {
std::string expected_0 = "tracked_tfrt_cpu_device_buffer_test";
std::string expected_1 = "tuple";
auto buffer_0 = MakeUnconstructedAsyncValueRef<MaybeOwningCpuMemory>();
auto malloc_event_0 = MakeConstructedAsyncValueRef<CpuEvent>();
malloc_event_0.AndThen(
[buffer_0_copy = buffer_0.CopyRef(), buffer_0_size = expected_0.size()] {
buffer_0_copy.emplace(
MaybeOwningCpuMemory::Allocate(buffer_0_size).value());
});
auto buffer_1 = MakeUnconstructedAsyncValueRef<MaybeOwningCpuMemory>();
auto malloc_event_1 = MakeConstructedAsyncValueRef<CpuEvent>();
malloc_event_1.AndThen(
[buffer_1_copy = buffer_1.CopyRef(), buffer_1_size = expected_1.size()] {
buffer_1_copy.emplace(
MaybeOwningCpuMemory::Allocate(buffer_1_size).value());
});
auto definition_event_0 = MakeConstructedAsyncValueRef<CpuEvent>();
auto definition_event_1 = MakeConstructedAsyncValueRef<CpuEvent>();
TrackedTfrtCpuDeviceBuffer tracked_buffer(
true,
true, {buffer_0, buffer_1},
{expected_0.size(), expected_1.size()},
{definition_event_0, definition_event_1},
nullptr);
auto result_0 = tracked_buffer.Buffers()[0];
auto result_1 = tracked_buffer.Buffers()[1];
ASSERT_FALSE(result_0.IsAvailable());
ASSERT_FALSE(result_1.IsAvailable());
ASSERT_EQ(tracked_buffer.BufferSizes()[0], expected_0.size());
ASSERT_EQ(tracked_buffer.BufferSizes()[1], expected_1.size());
ThreadPool thread_pool(tsl::Env::Default(), "tracked_buffer_test",
4);
thread_pool.Schedule([&]() {
malloc_event_0.SetStateConcrete();
std::memcpy(buffer_0->data(), expected_0.data(), expected_0.size());
definition_event_0.SetStateConcrete();
});
thread_pool.Schedule([&]() {
malloc_event_1.SetStateConcrete();
std::memcpy(buffer_1->data(), expected_1.data(), expected_1.size());
definition_event_1.SetStateConcrete();
});
BlockUntilReady(tracked_buffer.definition_event().GetAsyncValue());
EXPECT_EQ(
std::string(static_cast<const char*>(result_0->data()), result_0->size()),
expected_0);
EXPECT_EQ(
std::string(static_cast<const char*>(result_1->data()), result_1->size()),
expected_1);
}
}
} |
305 | #ifndef I18N_ADDRESSINPUT_RULE_RETRIEVER_H_
#define I18N_ADDRESSINPUT_RULE_RETRIEVER_H_
#include <libaddressinput/callback.h>
#include <memory>
#include <string>
namespace i18n {
namespace addressinput {
class Retriever;
class Rule;
class RuleRetriever {
public:
using Callback =
i18n::addressinput::Callback<const std::string&, const Rule&>;
RuleRetriever(const RuleRetriever&) = delete;
RuleRetriever& operator=(const RuleRetriever&) = delete;
explicit RuleRetriever(const Retriever* retriever);
~RuleRetriever();
void RetrieveRule(const std::string& key, const Callback& rule_ready) const;
private:
std::unique_ptr<const Retriever> data_retriever_;
};
}
}
#endif
#include "rule_retriever.h"
#include <libaddressinput/callback.h>
#include <cassert>
#include <cstddef>
#include <memory>
#include <string>
#include "retriever.h"
#include "rule.h"
namespace i18n {
namespace addressinput {
namespace {
class Helper {
public:
Helper(const Helper&) = delete;
Helper& operator=(const Helper&) = delete;
Helper(const std::string& key,
const RuleRetriever::Callback& rule_ready,
const Retriever& data_retriever)
: rule_ready_(rule_ready),
data_retrieved_(BuildCallback(this, &Helper::OnDataRetrieved)) {
data_retriever.Retrieve(key, *data_retrieved_);
}
private:
~Helper() = default;
void OnDataRetrieved(bool success,
const std::string& key,
const std::string& data) {
Rule rule;
if (!success) {
rule_ready_(false, key, rule);
} else {
success = rule.ParseSerializedRule(data);
rule_ready_(success, key, rule);
}
delete this;
}
const RuleRetriever::Callback& rule_ready_;
const std::unique_ptr<const Retriever::Callback> data_retrieved_;
};
}
RuleRetriever::RuleRetriever(const Retriever* retriever)
: data_retriever_(retriever) {
assert(data_retriever_ != nullptr);
}
RuleRetriever::~RuleRetriever() = default;
void RuleRetriever::RetrieveRule(const std::string& key,
const Callback& rule_ready) const {
new Helper(key, rule_ready, *data_retriever_);
}
}
} | #include "rule_retriever.h"
#include <libaddressinput/callback.h>
#include <libaddressinput/null_storage.h>
#include <memory>
#include <string>
#include <gtest/gtest.h>
#include "retriever.h"
#include "rule.h"
#include "testdata_source.h"
namespace {
using i18n::addressinput::BuildCallback;
using i18n::addressinput::NullStorage;
using i18n::addressinput::Retriever;
using i18n::addressinput::Rule;
using i18n::addressinput::RuleRetriever;
using i18n::addressinput::TestdataSource;
class RuleRetrieverTest : public testing::Test {
public:
RuleRetrieverTest(const RuleRetrieverTest&) = delete;
RuleRetrieverTest& operator=(const RuleRetrieverTest&) = delete;
protected:
RuleRetrieverTest()
: rule_retriever_(
new Retriever(new TestdataSource(false), new NullStorage)),
success_(false),
key_(),
rule_(),
rule_ready_(BuildCallback(this, &RuleRetrieverTest::OnRuleReady)) {}
RuleRetriever rule_retriever_;
bool success_;
std::string key_;
Rule rule_;
const std::unique_ptr<const RuleRetriever::Callback> rule_ready_;
private:
void OnRuleReady(bool success,
const std::string& key,
const Rule& rule) {
success_ = success;
key_ = key;
rule_.CopyFrom(rule);
}
};
TEST_F(RuleRetrieverTest, ExistingRule) {
static const char kExistingKey[] = "data/CA";
rule_retriever_.RetrieveRule(kExistingKey, *rule_ready_);
EXPECT_TRUE(success_);
EXPECT_EQ(kExistingKey, key_);
EXPECT_FALSE(rule_.GetFormat().empty());
}
TEST_F(RuleRetrieverTest, MissingRule) {
static const char kMissingKey[] = "junk";
rule_retriever_.RetrieveRule(kMissingKey, *rule_ready_);
EXPECT_TRUE(success_);
EXPECT_EQ(kMissingKey, key_);
EXPECT_TRUE(rule_.GetFormat().empty());
}
} |
306 | #ifndef XLA_HLO_IR_BACKEND_CONFIG_H_
#define XLA_HLO_IR_BACKEND_CONFIG_H_
#include <memory>
#include <string>
#include <utility>
#include "absl/base/thread_annotations.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/synchronization/mutex.h"
#include "tsl/platform/protobuf.h"
namespace xla {
absl::StatusOr<std::string> BackendConfigToRawString(
const tsl::protobuf::Message& proto);
std::unique_ptr<tsl::protobuf::Message> CloneBackendConfigProto(
const tsl::protobuf::Message* proto);
class BackendConfigWrapper {
public:
BackendConfigWrapper() = default;
explicit BackendConfigWrapper(std::string raw_string)
: raw_string_(std::move(raw_string)) {}
explicit BackendConfigWrapper(const tsl::protobuf::Message& proto)
: proto_(CloneBackendConfigProto(&proto)) {}
BackendConfigWrapper(const BackendConfigWrapper& other) {
absl::MutexLock other_lock{&other.mutex_};
proto_ = CloneBackendConfigProto(other.proto_.get());
raw_string_ = other.raw_string_;
}
BackendConfigWrapper& operator=(BackendConfigWrapper&& other);
bool operator==(const BackendConfigWrapper& other) const;
bool operator!=(const BackendConfigWrapper& other) const {
return !(*this == other);
}
const std::string& GetRawString() const {
absl::WriterMutexLock lock{&mutex_};
return GetRawStringWithoutMutex();
}
absl::Status GetProto(tsl::protobuf::Message* output_proto) const;
bool empty() const {
absl::MutexLock lock{&mutex_};
return proto_ == nullptr && raw_string_.empty();
}
private:
const std::string& GetRawStringWithoutMutex() const
ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
mutable absl::Mutex mutex_;
mutable std::unique_ptr<tsl::protobuf::Message> proto_
ABSL_GUARDED_BY(mutex_);
mutable std::string raw_string_ ABSL_GUARDED_BY(mutex_);
};
}
#endif
#include "xla/hlo/ir/backend_config.h"
#include <memory>
#include <string>
#include <utility>
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/synchronization/mutex.h"
#include "xla/util.h"
#include "tsl/platform/errors.h"
#include "tsl/platform/human_readable_json.h"
#include "tsl/platform/protobuf.h"
namespace xla {
std::unique_ptr<tsl::protobuf::Message> CloneBackendConfigProto(
const tsl::protobuf::Message* proto) {
if (proto == nullptr) {
return nullptr;
}
std::unique_ptr<tsl::protobuf::Message> result(proto->New());
result->CopyFrom(*proto);
return result;
}
absl::StatusOr<std::string> BackendConfigToRawString(
const tsl::protobuf::Message& proto) {
return tsl::ProtoToHumanReadableJson(proto, true);
}
const std::string& BackendConfigWrapper::GetRawStringWithoutMutex() const {
if (proto_ && raw_string_.empty()) {
raw_string_ = BackendConfigToRawString(*proto_).value();
}
static const std::string* kEmptyString = new std::string();
return raw_string_.empty() ? *kEmptyString : raw_string_;
}
absl::Status BackendConfigWrapper::GetProto(
tsl::protobuf::Message* output_proto) const {
output_proto->Clear();
absl::WriterMutexLock lock{&mutex_};
if (proto_ != nullptr) {
if (proto_->GetDescriptor() != output_proto->GetDescriptor()) {
return Internal("Mismatched backend config descriptors.");
}
output_proto->CopyFrom(*proto_);
return absl::OkStatus();
}
if (raw_string_.empty()) {
return absl::OkStatus();
}
TF_RETURN_IF_ERROR(tsl::HumanReadableJsonToProto(raw_string_, output_proto));
proto_ = CloneBackendConfigProto(output_proto);
return absl::OkStatus();
}
BackendConfigWrapper& BackendConfigWrapper::operator=(
BackendConfigWrapper&& other) {
std::unique_ptr<tsl::protobuf::Message> temp_proto;
std::string temp_string;
{
absl::MutexLock other_lock{&other.mutex_};
temp_proto = std::move(other.proto_);
temp_string = std::move(other.raw_string_);
}
absl::MutexLock this_lock{&mutex_};
proto_ = std::move(temp_proto);
raw_string_ = std::move(temp_string);
return *this;
}
bool BackendConfigWrapper::operator==(const BackendConfigWrapper& other) const {
tsl::protobuf::Message* this_proto = nullptr;
{
absl::MutexLock this_lock{&mutex_};
this_proto = proto_.get();
}
const std::string* other_raw_string = nullptr;
{
absl::MutexLock other_lock{&other.mutex_};
if (this_proto != nullptr && other.proto_ != nullptr) {
using ::tsl::protobuf::util::MessageDifferencer;
return MessageDifferencer::Equals(*this_proto, *other.proto_);
}
other_raw_string = &other.GetRawStringWithoutMutex();
}
return GetRawString() == *other_raw_string;
}
} | #include "xla/hlo/ir/backend_config.h"
#include <memory>
#include <string>
#include <thread>
#include <utility>
#include <vector>
#include "absl/strings/string_view.h"
#include "absl/synchronization/notification.h"
#include "xla/service/gpu/backend_configs.pb.h"
#include "tsl/lib/core/status_test_util.h"
#include "tsl/platform/test.h"
namespace xla {
namespace {
const int kNumThreads = 100;
const int kNumRepetitions = 100;
constexpr absl::string_view kRawString =
R"({"operation_queue_id":"0","wait_on_operation_queues":[],"fusion_backend_config":{"kind":"__triton_gemm","triton_gemm_config":{"block_m":"256","block_n":"256","block_k":"32","split_k":"1","num_stages":"1","num_warps":"16","num_ctas":"1"}},"force_earliest_schedule":false})";
template <typename Input, typename CheckFn>
void RunThreaded(Input input, CheckFn check_fn) {
for (int i = 0; i < kNumRepetitions; ++i) {
BackendConfigWrapper source(input);
absl::Notification all_threads_created;
std::vector<std::unique_ptr<std::thread>> threads;
for (int i = 0; i < kNumThreads; ++i) {
threads.emplace_back(std::make_unique<std::thread>([&] {
all_threads_created.WaitForNotification();
check_fn(source);
}));
}
all_threads_created.Notify();
for (int i = 0; i < kNumThreads; ++i) {
threads[i]->join();
}
}
}
TEST(BackendConfigWrapperTest, ConcurrentGetProto) {
RunThreaded(std::string{kRawString}, [](BackendConfigWrapper& source) {
gpu::GpuBackendConfig proto;
TF_EXPECT_OK(source.GetProto(&proto));
EXPECT_TRUE(proto.has_fusion_backend_config());
BackendConfigWrapper wrapped(proto);
EXPECT_TRUE(wrapped == source);
});
}
TEST(BackendConfigWrapperTest, ConcurrentGetRawString) {
BackendConfigWrapper source_json(std::string{kRawString});
gpu::GpuBackendConfig proto;
TF_EXPECT_OK(source_json.GetProto(&proto));
RunThreaded(proto, [](BackendConfigWrapper& source) {
std::string raw_string = source.GetRawString();
EXPECT_EQ(raw_string, kRawString);
BackendConfigWrapper wrapped(raw_string);
EXPECT_TRUE(wrapped == source);
});
}
TEST(BackendConfigWrapperTest, AssignmentToNonEmptyIsOK) {
BackendConfigWrapper a(std::string{kRawString});
BackendConfigWrapper b(std::string{kRawString});
a = std::move(b);
EXPECT_TRUE(a == BackendConfigWrapper(std::string{kRawString}));
}
TEST(BackendConfigWrapperTest, AssignmentDoesNotDeadlock) {
BackendConfigWrapper source;
BackendConfigWrapper& ref = source;
source = std::move(ref);
}
TEST(BackendConfigWrapperTest, SelfComparisonDoesNotDeadlock) {
BackendConfigWrapper source(std::string{kRawString});
EXPECT_TRUE(source == source);
}
TEST(BackendConfigWrapperTest, ComparisonDoesNotDeadlock) {
BackendConfigWrapper source_json(std::string{kRawString});
gpu::GpuBackendConfig proto;
TF_EXPECT_OK(source_json.GetProto(&proto));
RunThreaded(std::string{kRawString}, [&proto](BackendConfigWrapper& source) {
BackendConfigWrapper other_first(proto);
EXPECT_TRUE(other_first == source);
BackendConfigWrapper other_second(proto);
EXPECT_TRUE(source == other_second);
});
}
}
} |
307 | #ifndef THIRD_PARTY_CEL_CPP_BASE_KIND_H_
#define THIRD_PARTY_CEL_CPP_BASE_KIND_H_
#include "common/kind.h"
#include "common/type_kind.h"
#include "common/value_kind.h"
#endif
#include "common/kind.h"
#include "absl/strings/string_view.h"
namespace cel {
absl::string_view KindToString(Kind kind) {
switch (kind) {
case Kind::kNullType:
return "null_type";
case Kind::kDyn:
return "dyn";
case Kind::kAny:
return "any";
case Kind::kType:
return "type";
case Kind::kTypeParam:
return "type_param";
case Kind::kFunction:
return "function";
case Kind::kBool:
return "bool";
case Kind::kInt:
return "int";
case Kind::kUint:
return "uint";
case Kind::kDouble:
return "double";
case Kind::kString:
return "string";
case Kind::kBytes:
return "bytes";
case Kind::kDuration:
return "duration";
case Kind::kTimestamp:
return "timestamp";
case Kind::kList:
return "list";
case Kind::kMap:
return "map";
case Kind::kStruct:
return "struct";
case Kind::kUnknown:
return "*unknown*";
case Kind::kOpaque:
return "*opaque*";
case Kind::kBoolWrapper:
return "google.protobuf.BoolValue";
case Kind::kIntWrapper:
return "google.protobuf.Int64Value";
case Kind::kUintWrapper:
return "google.protobuf.UInt64Value";
case Kind::kDoubleWrapper:
return "google.protobuf.DoubleValue";
case Kind::kStringWrapper:
return "google.protobuf.StringValue";
case Kind::kBytesWrapper:
return "google.protobuf.BytesValue";
default:
return "*error*";
}
}
} | #include "common/kind.h"
#include <limits>
#include <type_traits>
#include "common/type_kind.h"
#include "common/value_kind.h"
#include "internal/testing.h"
namespace cel {
namespace {
static_assert(std::is_same_v<std::underlying_type_t<TypeKind>,
std::underlying_type_t<ValueKind>>,
"TypeKind and ValueKind must have the same underlying type");
TEST(Kind, ToString) {
EXPECT_EQ(KindToString(Kind::kError), "*error*");
EXPECT_EQ(KindToString(Kind::kNullType), "null_type");
EXPECT_EQ(KindToString(Kind::kDyn), "dyn");
EXPECT_EQ(KindToString(Kind::kAny), "any");
EXPECT_EQ(KindToString(Kind::kType), "type");
EXPECT_EQ(KindToString(Kind::kBool), "bool");
EXPECT_EQ(KindToString(Kind::kInt), "int");
EXPECT_EQ(KindToString(Kind::kUint), "uint");
EXPECT_EQ(KindToString(Kind::kDouble), "double");
EXPECT_EQ(KindToString(Kind::kString), "string");
EXPECT_EQ(KindToString(Kind::kBytes), "bytes");
EXPECT_EQ(KindToString(Kind::kDuration), "duration");
EXPECT_EQ(KindToString(Kind::kTimestamp), "timestamp");
EXPECT_EQ(KindToString(Kind::kList), "list");
EXPECT_EQ(KindToString(Kind::kMap), "map");
EXPECT_EQ(KindToString(Kind::kStruct), "struct");
EXPECT_EQ(KindToString(Kind::kUnknown), "*unknown*");
EXPECT_EQ(KindToString(Kind::kOpaque), "*opaque*");
EXPECT_EQ(KindToString(Kind::kBoolWrapper), "google.protobuf.BoolValue");
EXPECT_EQ(KindToString(Kind::kIntWrapper), "google.protobuf.Int64Value");
EXPECT_EQ(KindToString(Kind::kUintWrapper), "google.protobuf.UInt64Value");
EXPECT_EQ(KindToString(Kind::kDoubleWrapper), "google.protobuf.DoubleValue");
EXPECT_EQ(KindToString(Kind::kStringWrapper), "google.protobuf.StringValue");
EXPECT_EQ(KindToString(Kind::kBytesWrapper), "google.protobuf.BytesValue");
EXPECT_EQ(KindToString(static_cast<Kind>(std::numeric_limits<int>::max())),
"*error*");
}
TEST(Kind, TypeKindRoundtrip) {
EXPECT_EQ(TypeKindToKind(KindToTypeKind(Kind::kBool)), Kind::kBool);
}
TEST(Kind, ValueKindRoundtrip) {
EXPECT_EQ(ValueKindToKind(KindToValueKind(Kind::kBool)), Kind::kBool);
}
TEST(Kind, IsTypeKind) {
EXPECT_TRUE(KindIsTypeKind(Kind::kBool));
EXPECT_TRUE(KindIsTypeKind(Kind::kAny));
EXPECT_TRUE(KindIsTypeKind(Kind::kDyn));
}
TEST(Kind, IsValueKind) {
EXPECT_TRUE(KindIsValueKind(Kind::kBool));
EXPECT_FALSE(KindIsValueKind(Kind::kAny));
EXPECT_FALSE(KindIsValueKind(Kind::kDyn));
}
TEST(Kind, Equality) {
EXPECT_EQ(Kind::kBool, TypeKind::kBool);
EXPECT_EQ(TypeKind::kBool, Kind::kBool);
EXPECT_EQ(Kind::kBool, ValueKind::kBool);
EXPECT_EQ(ValueKind::kBool, Kind::kBool);
EXPECT_NE(Kind::kBool, TypeKind::kInt);
EXPECT_NE(TypeKind::kInt, Kind::kBool);
EXPECT_NE(Kind::kBool, ValueKind::kInt);
EXPECT_NE(ValueKind::kInt, Kind::kBool);
}
TEST(TypeKind, ToString) {
EXPECT_EQ(TypeKindToString(TypeKind::kBool), KindToString(Kind::kBool));
}
TEST(ValueKind, ToString) {
EXPECT_EQ(ValueKindToString(ValueKind::kBool), KindToString(Kind::kBool));
}
}
} |
308 | #ifndef TENSORFLOW_CORE_KERNELS_DATA_BATCH_DATASET_OP_H_
#define TENSORFLOW_CORE_KERNELS_DATA_BATCH_DATASET_OP_H_
#include "tensorflow/core/framework/dataset.h"
namespace tensorflow {
namespace data {
class BatchDatasetOp : public UnaryDatasetOpKernel {
public:
static constexpr const char* const kDatasetType = "Batch";
static constexpr const char* const kInputDataset = "input_dataset";
static constexpr const char* const kBatchSize = "batch_size";
static constexpr const char* const kDropRemainder = "drop_remainder";
static constexpr const char* const kParallelCopy = "parallel_copy";
static constexpr const char* const kOutputTypes = "output_types";
static constexpr const char* const kOutputShapes = "output_shapes";
explicit BatchDatasetOp(OpKernelConstruction* ctx);
protected:
void MakeDataset(OpKernelContext* ctx, DatasetBase* input,
DatasetBase** output) override;
private:
class Dataset;
const int op_version_;
bool parallel_copy_ = false;
};
}
}
#endif
#include "tensorflow/core/kernels/data/batch_dataset_op.h"
#include <algorithm>
#include <cstdlib>
#include <functional>
#include <optional>
#include <utility>
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/str_cat.h"
#include "tensorflow/core/data/dataset_utils.h"
#include "tensorflow/core/data/global_shuffle_utils.h"
#include "tensorflow/core/data/name_utils.h"
#include "tensorflow/core/framework/dataset.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/partial_tensor_shape.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/lib/gtl/cleanup.h"
#include "tensorflow/core/platform/macros.h"
#include "tensorflow/core/platform/stringprintf.h"
#include "tensorflow/core/util/batch_util.h"
#include "tsl/platform/mutex.h"
#include "tsl/platform/statusor.h"
namespace tensorflow {
namespace data {
constexpr const char* const BatchDatasetOp::kDatasetType;
constexpr const char* const BatchDatasetOp::kInputDataset;
constexpr const char* const BatchDatasetOp::kBatchSize;
constexpr const char* const BatchDatasetOp::kDropRemainder;
constexpr const char* const BatchDatasetOp::kParallelCopy;
constexpr const char* const BatchDatasetOp::kOutputTypes;
constexpr const char* const BatchDatasetOp::kOutputShapes;
constexpr char kInputImplEmpty[] = "input_impl_empty";
constexpr char kBatchDataset[] = "BatchDataset";
class BatchDatasetOp::Dataset : public DatasetBase {
public:
Dataset(OpKernelContext* ctx, int64_t batch_size, bool drop_remainder,
bool parallel_copy, const DatasetBase* input, int op_version)
: DatasetBase(DatasetContext(ctx)),
batch_size_(batch_size),
reserve_size_(drop_remainder ? batch_size
: std::min<int64_t>(batch_size, 1 << 16)),
drop_remainder_(drop_remainder),
parallel_copy_(parallel_copy),
input_(input),
op_version_(op_version),
traceme_metadata_(
{{"batch_size",
strings::Printf("%lld", static_cast<long long>(batch_size))},
{"drop_remainder", drop_remainder ? "true" : "false"},
{"parallel_copy", parallel_copy ? "true" : "false"}}) {
input_->Ref();
const auto& input_shapes = input_->output_shapes();
output_shapes_.reserve(input_shapes.size());
for (const auto& input_shape : input_shapes) {
if (drop_remainder_ || input_->Cardinality() == kInfiniteCardinality) {
output_shapes_.emplace_back(
PartialTensorShape({batch_size_}).Concatenate(input_shape));
} else {
output_shapes_.emplace_back(
PartialTensorShape({-1}).Concatenate(input_shape));
}
}
random_indexing_compatible_ = absl::OkStatus();
if (!drop_remainder_) {
random_indexing_compatible_ = absl::FailedPreconditionError(absl::StrCat(
type_string(),
" does not support global shuffling with `drop_remainder=False`."));
} else if (input_ != nullptr) {
random_indexing_compatible_ = input_->RandomIndexingCompatible();
}
}
~Dataset() override { input_->Unref(); }
std::unique_ptr<IteratorBase> MakeIteratorInternal(
const string& prefix) const override {
name_utils::IteratorPrefixParams params;
params.op_version = op_version_;
return std::make_unique<Iterator>(Iterator::Params{
this, name_utils::IteratorPrefix(kDatasetType, prefix, params)});
}
const DataTypeVector& output_dtypes() const override {
return input_->output_dtypes();
}
const std::vector<PartialTensorShape>& output_shapes() const override {
return output_shapes_;
}
string DebugString() const override {
name_utils::DatasetDebugStringParams params;
params.op_version = op_version_;
params.set_args(batch_size_);
return name_utils::DatasetDebugString(kDatasetType, params);
}
int64_t CardinalityInternal(CardinalityOptions options) const override {
int64_t n = input_->Cardinality(options);
if (n == kInfiniteCardinality || n == kUnknownCardinality) {
return n;
}
return n / batch_size_ + (n % batch_size_ == 0 || drop_remainder_ ? 0 : 1);
}
Status InputDatasets(std::vector<const DatasetBase*>* inputs) const override {
inputs->push_back(input_);
return absl::OkStatus();
}
Status CheckExternalState() const override {
return input_->CheckExternalState();
}
Status Get(OpKernelContext* ctx, int64 index,
std::vector<Tensor>* out_tensors) const override {
const int64 cardinality = Cardinality();
if (index < 0 || index >= cardinality) {
return errors::OutOfRange("Index out of range [0, ", cardinality,
"):", index);
}
int batch_start_index = batch_size_ * index;
std::vector<std::vector<Tensor>> batch_elements;
int input_cardinality = input_->Cardinality();
for (int i = batch_start_index;
i < batch_start_index + batch_size_ && i < input_cardinality; ++i) {
std::vector<Tensor> batch_element_tuple;
TF_RETURN_IF_ERROR(input_->Get(ctx, i, &batch_element_tuple));
batch_elements.emplace_back(std::move(batch_element_tuple));
}
TF_RETURN_IF_ERROR(CopyBatch(AnyContext(ctx), std::move(batch_elements),
parallel_copy_, out_tensors));
return absl::OkStatus();
}
absl::Status RandomIndexingCompatible() const override {
return random_indexing_compatible_;
}
protected:
Status AsGraphDefInternal(SerializationContext* ctx,
DatasetGraphDefBuilder* b,
Node** output) const override {
Node* input_graph_node = nullptr;
TF_RETURN_IF_ERROR(b->AddInputDataset(ctx, input_, &input_graph_node));
Node* batch_size = nullptr;
TF_RETURN_IF_ERROR(b->AddScalar(batch_size_, &batch_size));
Node* drop_remainder = nullptr;
TF_RETURN_IF_ERROR(b->AddScalar(drop_remainder_, &drop_remainder));
AttrValue parallel_copy;
b->BuildAttrValue(parallel_copy_, ¶llel_copy);
TF_RETURN_IF_ERROR(
b->AddDataset(this, {input_graph_node, batch_size, drop_remainder},
{{kParallelCopy, parallel_copy}}, output));
return absl::OkStatus();
}
private:
class Iterator : public DatasetIterator<Dataset> {
public:
explicit Iterator(const Params& params)
: DatasetIterator<Dataset>(params) {}
bool SymbolicCheckpointCompatible() const override { return true; }
Status Initialize(IteratorContext* ctx) override {
tsl::mutex_lock l(mu_);
return dataset()->input_->MakeIterator(ctx, this, prefix(), &input_impl_);
}
Status GetNextInternal(IteratorContext* ctx,
std::vector<Tensor>* out_tensors,
bool* end_of_sequence) override {
std::vector<std::vector<Tensor>> batch_elements;
{
mutex_lock l(mu_);
if (!input_impl_) {
*end_of_sequence = true;
return absl::OkStatus();
}
batch_elements.reserve(dataset()->reserve_size_);
*end_of_sequence = false;
IteratorContextWithIndexMapper ctx_with_index_mapper(ctx, this);
for (int i = 0; i < dataset()->batch_size_ && !*end_of_sequence; ++i) {
std::vector<Tensor> batch_element_tuple;
TF_RETURN_IF_ERROR(input_impl_->GetNext(ctx_with_index_mapper.Get(),
&batch_element_tuple,
end_of_sequence));
if (!*end_of_sequence) {
batch_elements.emplace_back(std::move(batch_element_tuple));
} else {
input_impl_.reset();
}
}
ctx_with_index_mapper.MergeCheckpoint();
}
if (batch_elements.empty()) {
DCHECK(*end_of_sequence);
return absl::OkStatus();
}
if (dataset()->drop_remainder_ &&
batch_elements.size() < dataset()->batch_size_) {
*end_of_sequence = true;
return absl::OkStatus();
}
TF_RETURN_IF_ERROR(CopyBatch(AnyContext(ctx), std::move(batch_elements),
dataset()->parallel_copy_, out_tensors));
*end_of_sequence = false;
return absl::OkStatus();
}
IndexMapperFn GetIndexMapper(
IndexMapperFn parent_index_mapper) const override {
int64_t batch_size = dataset()->batch_size_;
return [parent_index_mapper,
batch_size](size_t element_position) -> absl::StatusOr<size_t> {
size_t batch_element_position = element_position / batch_size;
size_t input_element_offset = element_position % batch_size;
TF_ASSIGN_OR_RETURN(size_t shuffled_element_position,
parent_index_mapper(batch_element_position));
return shuffled_element_position * batch_size + input_element_offset;
};
}
protected:
std::shared_ptr<model::Node> CreateNode(
IteratorContext* ctx, model::Node::Args args) const override {
return model::MakeKnownRatioNode(std::move(args), dataset()->batch_size_);
}
Status SaveInternal(SerializationContext* ctx,
IteratorStateWriter* writer) override {
mutex_lock l(mu_);
TF_RETURN_IF_ERROR(writer->WriteScalar(
prefix(), kInputImplEmpty, static_cast<int64_t>(!input_impl_)));
if (input_impl_) {
TF_RETURN_IF_ERROR(SaveInput(ctx, writer, input_impl_));
}
return absl::OkStatus();
}
Status RestoreInternal(IteratorContext* ctx,
IteratorStateReader* reader) override {
mutex_lock l(mu_);
if (ctx->restored_element_count().has_value()) {
IteratorContext::Params params(ctx);
params.restored_element_count =
*ctx->restored_element_count() * dataset()->batch_size_;
IteratorContext ctx_copy(params);
return RestoreInput(&ctx_copy, reader, input_impl_);
}
int64_t input_empty;
TF_RETURN_IF_ERROR(
reader->ReadScalar(prefix(), kInputImplEmpty, &input_empty));
if (!static_cast<bool>(input_empty)) {
TF_RETURN_IF_ERROR(RestoreInput(ctx, reader, input_impl_));
} else {
input_impl_.reset();
}
return absl::OkStatus();
}
TraceMeMetadata GetTraceMeMetadata() const override {
return dataset()->traceme_metadata_;
}
private:
mutex mu_;
std::unique_ptr<IteratorBase> input_impl_ TF_GUARDED_BY(mu_);
};
const int64_t batch_size_;
const int64_t reserve_size_;
const bool drop_remainder_;
const bool parallel_copy_;
const DatasetBase* const input_;
const int op_version_;
std::vector<PartialTensorShape> output_shapes_;
absl::Status random_indexing_compatible_;
const TraceMeMetadata traceme_metadata_;
};
BatchDatasetOp::BatchDatasetOp(OpKernelConstruction* ctx)
: UnaryDatasetOpKernel(ctx),
op_version_(ctx->def().op() == kBatchDataset ? 1 : 2) {
if (ctx->HasAttr(kParallelCopy)) {
OP_REQUIRES_OK(ctx, ctx->GetAttr(kParallelCopy, ¶llel_copy_));
}
}
void BatchDatasetOp::MakeDataset(OpKernelContext* ctx, DatasetBase* input,
DatasetBase** output) {
int64_t batch_size = 0;
OP_REQUIRES_OK(ctx,
ParseScalarArgument<int64_t>(ctx, kBatchSize, &batch_size));
OP_REQUIRES(ctx, batch_size > 0,
errors::InvalidArgument("Batch size must be greater than zero."));
bool drop_remainder = false;
if (op_version_ > 1) {
OP_REQUIRES_OK(
ctx, ParseScalarArgument<bool>(ctx, kDropRemainder, &drop_remainder));
}
*output = new Dataset(ctx, batch_size, drop_remainder, parallel_copy_, input,
op_version_);
}
namespace {
REGISTER_KERNEL_BUILDER(Name("BatchDataset").Device(DEVICE_CPU),
BatchDatasetOp);
REGISTER_KERNEL_BUILDER(Name("BatchDatasetV2").Device(DEVICE_CPU),
BatchDatasetOp);
}
}
} | #include "tensorflow/core/kernels/data/batch_dataset_op.h"
#include <string>
#include "tensorflow/core/common_runtime/type_inference.h"
#include "tensorflow/core/data/dataset_test_base.h"
#include "tensorflow/core/graph/node_builder.h"
#include "tensorflow/core/public/session_options.h"
namespace tensorflow {
namespace data {
namespace {
constexpr char kNodeName[] = "batch_dataset";
class BatchDatasetOpTest : public DatasetOpsTestBase {};
BatchDatasetParams BatchDatasetParams1() {
return BatchDatasetParams(RangeDatasetParams(0, 12, 1),
4,
false,
true,
{DT_INT64},
{PartialTensorShape({4})},
kNodeName);
}
BatchDatasetParams BatchDatasetParams2() {
return BatchDatasetParams(RangeDatasetParams(0, 12, 1),
4,
true,
false,
{DT_INT64},
{PartialTensorShape({4})},
kNodeName);
}
BatchDatasetParams BatchDatasetParams3() {
return BatchDatasetParams(RangeDatasetParams(0, 10, 1),
3,
false,
false,
{DT_INT64},
{PartialTensorShape({-1})},
kNodeName);
}
BatchDatasetParams BatchDatasetParams4() {
return BatchDatasetParams(RangeDatasetParams(0, 10, 1),
3,
true,
true,
{DT_INT64},
{PartialTensorShape({3})},
kNodeName);
}
BatchDatasetParams BatchDatasetParams5() {
return BatchDatasetParams(RangeDatasetParams(0, 10, 1),
12,
true,
true,
{DT_INT64},
{PartialTensorShape({12})},
kNodeName);
}
BatchDatasetParams BatchDatasetParams6() {
return BatchDatasetParams(RangeDatasetParams(0, 10, 1),
12,
false,
true,
{DT_INT64},
{PartialTensorShape({-1})},
kNodeName);
}
BatchDatasetParams BatchDatasetParams7() {
return BatchDatasetParams(RangeDatasetParams(0, 0, 1),
4,
false,
false,
{DT_INT64},
{PartialTensorShape({4})},
kNodeName);
}
BatchDatasetParams InvalidBatchSizeBatchDatasetParams() {
return BatchDatasetParams(RangeDatasetParams(0, 10, 1),
-1,
false,
false,
{DT_INT64},
{PartialTensorShape({3})},
kNodeName);
}
std::vector<GetNextTestCase<BatchDatasetParams>> GetNextTestCases() {
return {{BatchDatasetParams1(),
CreateTensors<int64_t>(
TensorShape({4}), {{0, 1, 2, 3}, {4, 5, 6, 7}, {8, 9, 10, 11}})},
{BatchDatasetParams2(),
CreateTensors<int64_t>(
TensorShape({4}), {{0, 1, 2, 3}, {4, 5, 6, 7}, {8, 9, 10, 11}})},
{BatchDatasetParams3(),
{CreateTensor<int64_t>(TensorShape({3}), {0, 1, 2}),
CreateTensor<int64_t>(TensorShape({3}), {3, 4, 5}),
CreateTensor<int64_t>(TensorShape({3}), {6, 7, 8}),
CreateTensor<int64_t>(TensorShape({1}), {9})}},
{BatchDatasetParams4(),
CreateTensors<int64_t>(TensorShape({3}),
{{0, 1, 2}, {3, 4, 5}, {6, 7, 8}})},
{BatchDatasetParams5(),
{}},
{BatchDatasetParams6(),
CreateTensors<int64_t>(TensorShape({10}),
{{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}})},
{BatchDatasetParams7(),
{}}};
}
ITERATOR_GET_NEXT_TEST_P(BatchDatasetOpTest, BatchDatasetParams,
GetNextTestCases())
TEST_F(BatchDatasetOpTest, DatasetNodeName) {
auto batch_dataset_params = BatchDatasetParams1();
TF_ASSERT_OK(Initialize(batch_dataset_params));
TF_ASSERT_OK(CheckDatasetNodeName(batch_dataset_params.node_name()));
}
TEST_F(BatchDatasetOpTest, DatasetTypeString) {
auto batch_dataset_params = BatchDatasetParams1();
TF_ASSERT_OK(Initialize(batch_dataset_params));
name_utils::OpNameParams params;
params.op_version = batch_dataset_params.op_version();
TF_ASSERT_OK(CheckDatasetTypeString(
name_utils::OpName(BatchDatasetOp::kDatasetType, params)));
}
TEST_F(BatchDatasetOpTest, DatasetOutputDtypes) {
auto batch_dataset_params = BatchDatasetParams1();
TF_ASSERT_OK(Initialize(batch_dataset_params));
TF_ASSERT_OK(CheckDatasetOutputDtypes({DT_INT64}));
}
std::vector<DatasetOutputShapesTestCase<BatchDatasetParams>>
DatasetOutputShapesTestCases() {
return {{BatchDatasetParams1(),
{PartialTensorShape({4})}},
{BatchDatasetParams2(),
{PartialTensorShape({4})}},
{BatchDatasetParams3(),
{PartialTensorShape({-1})}},
{BatchDatasetParams4(),
{PartialTensorShape({3})}},
{BatchDatasetParams5(),
{PartialTensorShape({12})}},
{BatchDatasetParams6(),
{PartialTensorShape({-1})}},
{BatchDatasetParams7(),
{PartialTensorShape({4})}}};
}
DATASET_OUTPUT_SHAPES_TEST_P(BatchDatasetOpTest, BatchDatasetParams,
DatasetOutputShapesTestCases())
std::vector<CardinalityTestCase<BatchDatasetParams>> CardinalityTestCases() {
return {
{BatchDatasetParams1(), 3},
{BatchDatasetParams2(), 3},
{BatchDatasetParams3(), 4},
{BatchDatasetParams4(), 3},
{BatchDatasetParams5(), 0},
{BatchDatasetParams6(), 1},
{BatchDatasetParams7(), 0}};
}
DATASET_CARDINALITY_TEST_P(BatchDatasetOpTest, BatchDatasetParams,
CardinalityTestCases())
TEST_F(BatchDatasetOpTest, IteratorOutputDtypes) {
auto batch_dataset_params = BatchDatasetParams1();
TF_ASSERT_OK(Initialize(batch_dataset_params));
TF_ASSERT_OK(CheckIteratorOutputDtypes({DT_INT64}));
}
std::vector<IteratorOutputShapesTestCase<BatchDatasetParams>>
IteratorOutputShapesTestCases() {
return {{BatchDatasetParams1(),
{PartialTensorShape({4})}},
{BatchDatasetParams2(),
{PartialTensorShape({4})}},
{BatchDatasetParams3(),
{PartialTensorShape({-1})}},
{BatchDatasetParams4(),
{PartialTensorShape({3})}},
{BatchDatasetParams5(),
{PartialTensorShape({12})}},
{BatchDatasetParams6(),
{PartialTensorShape({-1})}},
{BatchDatasetParams7(),
{PartialTensorShape({4})}}};
}
ITERATOR_OUTPUT_SHAPES_TEST_P(BatchDatasetOpTest, BatchDatasetParams,
IteratorOutputShapesTestCases())
TEST_F(BatchDatasetOpTest, IteratorOutputPrefix) {
auto batch_dataset_params = BatchDatasetParams1();
TF_ASSERT_OK(Initialize(batch_dataset_params));
name_utils::IteratorPrefixParams params;
params.op_version = batch_dataset_params.op_version();
TF_ASSERT_OK(CheckIteratorPrefix(name_utils::IteratorPrefix(
BatchDatasetOp::kDatasetType, batch_dataset_params.iterator_prefix(),
params)));
}
std::vector<IteratorSaveAndRestoreTestCase<BatchDatasetParams>>
IteratorSaveAndRestoreTestCases() {
return {{BatchDatasetParams1(),
{0, 1, 5},
CreateTensors<int64_t>(
TensorShape({4}), {{0, 1, 2, 3}, {4, 5, 6, 7}, {8, 9, 10, 11}})},
{BatchDatasetParams2(),
{0, 1, 5},
CreateTensors<int64_t>(
TensorShape({4}), {{0, 1, 2, 3}, {4, 5, 6, 7}, {8, 9, 10, 11}})},
{BatchDatasetParams3(),
{0, 1, 5},
{CreateTensor<int64_t>(TensorShape({3}), {0, 1, 2}),
CreateTensor<int64_t>(TensorShape({3}), {3, 4, 5}),
CreateTensor<int64_t>(TensorShape({3}), {6, 7, 8}),
CreateTensor<int64_t>(TensorShape({1}), {9})}},
{BatchDatasetParams4(),
{0, 1, 5},
{CreateTensor<int64_t>(TensorShape({3}), {0, 1, 2}),
CreateTensor<int64_t>(TensorShape({3}), {3, 4, 5}),
CreateTensor<int64_t>(TensorShape({3}), {6, 7, 8})}},
{BatchDatasetParams5(),
{0, 1, 5},
{}},
{BatchDatasetParams6(),
{0, 1, 5},
{CreateTensor<int64_t>(TensorShape({10}),
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9})}},
{BatchDatasetParams7(),
{0, 1, 5},
{}}};
}
ITERATOR_SAVE_AND_RESTORE_TEST_P(BatchDatasetOpTest, BatchDatasetParams,
IteratorSaveAndRestoreTestCases())
TEST_F(BatchDatasetOpTest, InvalidBatchSize) {
auto batch_dataset_params = InvalidBatchSizeBatchDatasetParams();
EXPECT_EQ(Initialize(batch_dataset_params).code(),
absl::StatusCode::kInvalidArgument);
}
REGISTER_OP("BatchDatasetOpTest>ConstTypeCtor")
.Output("output: dtype")
.Attr("value: tensor")
.Attr("dtype: type")
.SetTypeConstructor(full_type::Unary(TFT_TENSOR, "dtype"));
static void add_identity_nodes(Node* node, Graph& graph,
std::vector<Node*>& identity_nodes) {
for (int i = 0; i < node->num_outputs(); i++) {
Node* new_node;
std::string name = absl::StrCat("Identity", i);
TF_EXPECT_OK(NodeBuilder(name, "Identity")
.Attr("T", node->output_type(i))
.Input(node, i)
.Finalize(&graph, &new_node));
identity_nodes.push_back(new_node);
}
}
static Status type_inference(Graph& graph) {
GraphOptimizationPassOptions opt_options;
std::unique_ptr<Graph> graph_ptr(new Graph(OpRegistry::Global()));
graph_ptr->Copy(graph);
opt_options.graph = &graph_ptr;
opt_options.flib_def = graph.mutable_flib_def();
TypeInferencePass pass;
return pass.Run(opt_options);
}
TEST(BatchDatsetOpTest, TypeInference) {
Graph graph(OpRegistry::Global());
Node* input_dataset;
Node* batch_size;
Node* drop_remainder;
Node* batch_dataset_v2;
FullTypeDef input_dataset_t;
protobuf::TextFormat::Parser parser;
CHECK(parser.ParseFromString(
R"pb(type_id: TFT_PRODUCT
args {
type_id: TFT_DATASET
args {
type_id: TFT_PRODUCT
args {
type_id: TFT_RAGGED
args { type_id: TFT_STRING }
}
}
})pb",
&input_dataset_t));
TensorProto tensor_proto;
TF_EXPECT_OK(NodeBuilder("input_dataset", "Const")
.Attr("value", tensor_proto)
.Attr("dtype", DT_VARIANT)
.Finalize(&graph, &input_dataset));
(*input_dataset->mutable_def()->mutable_experimental_type()) =
input_dataset_t;
TF_EXPECT_OK(NodeBuilder("batch_size", "BatchDatasetOpTest>ConstTypeCtor")
.Attr("value", tensor_proto)
.Attr("dtype", DT_INT64)
.Finalize(&graph, &batch_size));
TF_EXPECT_OK(NodeBuilder("drop_remainder", "BatchDatasetOpTest>ConstTypeCtor")
.Attr("value", tensor_proto)
.Attr("dtype", DT_BOOL)
.Finalize(&graph, &drop_remainder));
TF_EXPECT_OK(NodeBuilder("BatchDatasetV2", "BatchDatasetV2")
.Attr("output_types", {DT_VARIANT})
.Attr("output_shapes", {TensorShape({1})})
.Input(input_dataset)
.Input(batch_size)
.Input(drop_remainder)
.Finalize(&graph, &batch_dataset_v2));
std::vector<Node*> identity_nodes;
add_identity_nodes(batch_dataset_v2, graph, identity_nodes);
TF_EXPECT_OK(type_inference(graph));
EXPECT_TRUE(full_type::IsEqual(identity_nodes[0]->def().experimental_type(),
input_dataset_t))
<< "fulltype is\n"
<< identity_nodes[0]->def().experimental_type().DebugString()
<< "\nexpected\n"
<< input_dataset_t.DebugString();
}
}
}
} |
309 | #ifndef TENSORFLOW_CORE_DATA_SERVICE_SNAPSHOT_SNAPSHOT_CHUNK_PROVIDER_H_
#define TENSORFLOW_CORE_DATA_SERVICE_SNAPSHOT_SNAPSHOT_CHUNK_PROVIDER_H_
#include <cstdint>
#include <functional>
#include <optional>
#include <string>
#include <utility>
#include <vector>
#include "absl/base/thread_annotations.h"
#include "absl/container/btree_set.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/string_view.h"
#include "absl/synchronization/mutex.h"
#include "tensorflow/core/framework/dataset.h"
#include "tensorflow/core/framework/tensor.h"
#include "tsl/platform/env.h"
namespace tensorflow {
namespace data {
class SnapshotChunkProvider : public SplitProvider {
public:
SnapshotChunkProvider(absl::string_view snapshot_path, tsl::Env* env);
~SnapshotChunkProvider() override = default;
SnapshotChunkProvider(const SnapshotChunkProvider&) = delete;
SnapshotChunkProvider& operator=(const SnapshotChunkProvider&) = delete;
absl::Status GetNext(Tensor* split, bool* end_of_splits) override;
absl::Status Reset() override;
absl::Status Save(std::function<std::string(std::string)> full_name,
IteratorStateWriter* writer) override;
absl::Status Restore(std::function<std::string(std::string)> full_name,
IteratorStateReader* reader) override;
int64_t Cardinality() const override;
void Cancel() override;
private:
struct SnapshotState {
SnapshotState() = default;
explicit SnapshotState(bool snapshot_is_done)
: snapshot_is_done(snapshot_is_done) {}
explicit SnapshotState(absl::Status status) : status(std::move(status)) {}
bool snapshot_is_done = false;
absl::Status status = absl::OkStatus();
};
struct ChunkOrder {
bool operator()(const std::string& chunk1, const std::string& chunk2) const;
};
using OrderedChunkSet = absl::btree_set<std::string, ChunkOrder>;
static std::string SetToString(const OrderedChunkSet& s);
static OrderedChunkSet SetFromString(absl::string_view s);
absl::Status UpdateSnapshot();
absl::StatusOr<SnapshotState> GetSnapshotState();
absl::StatusOr<std::vector<std::string>> GetAvailableChunks();
const std::string snapshot_path_;
tsl::Env* const env_;
mutable absl::Mutex mu_;
OrderedChunkSet chunks_read_ ABSL_GUARDED_BY(mu_);
OrderedChunkSet chunks_unread_ ABSL_GUARDED_BY(mu_);
SnapshotState snapshot_state_ ABSL_GUARDED_BY(mu_);
};
}
}
#endif
#include "tensorflow/core/data/service/snapshot/snapshot_chunk_provider.h"
#include <cstdint>
#include <functional>
#include <optional>
#include <string>
#include <tuple>
#include <utility>
#include <vector>
#include "absl/base/thread_annotations.h"
#include "absl/container/btree_set.h"
#include "absl/log/log.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_join.h"
#include "absl/strings/str_split.h"
#include "absl/strings/string_view.h"
#include "absl/synchronization/mutex.h"
#include "absl/time/time.h"
#include "tensorflow/core/data/service/snapshot/file_utils.h"
#include "tensorflow/core/data/service/snapshot/path_utils.h"
#include "tensorflow/core/framework/dataset.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/framework/types.pb.h"
#include "tsl/platform/env.h"
#include "tsl/platform/errors.h"
#include "tsl/platform/path.h"
#include "tsl/platform/retrying_utils.h"
#include "tsl/platform/status_to_from_proto.h"
#include "tsl/platform/statusor.h"
#include "tsl/platform/tstring.h"
#include "tsl/protobuf/status.pb.h"
namespace tensorflow {
namespace data {
namespace {
constexpr char kChunksRead[] = "chunks_read";
constexpr absl::string_view kSetElementDelimiter = ",";
Tensor ConvertToTensor(absl::string_view s) {
Tensor tensor(DT_STRING, TensorShape({}));
tensor.scalar<tsl::tstring>()() = tsl::tstring(s);
return tensor;
}
std::string AbsPath(absl::string_view snapshot_path, absl::string_view chunk) {
return tsl::io::JoinPath(CommittedChunksDirectory(snapshot_path), chunk);
}
void Backoff(int num_retries, tsl::Env* env) {
if (num_retries >= 1) {
absl::Duration retry_backoff = tsl::ComputeRetryBackoff(num_retries - 1);
env->SleepForMicroseconds(absl::ToInt64Microseconds(retry_backoff));
}
}
}
SnapshotChunkProvider::SnapshotChunkProvider(absl::string_view snapshot_path,
tsl::Env* env)
: snapshot_path_(snapshot_path), env_(env) {}
absl::Status SnapshotChunkProvider::GetNext(Tensor* split, bool* end_of_splits)
ABSL_LOCKS_EXCLUDED(mu_) {
for (int num_retries = 0;; ++num_retries) {
Backoff(num_retries, env_);
absl::MutexLock l(&mu_);
TF_RETURN_IF_ERROR(snapshot_state_.status);
if (!chunks_unread_.empty()) {
std::string next_chunk = *chunks_unread_.begin();
chunks_read_.insert(next_chunk);
chunks_unread_.erase(next_chunk);
*split = ConvertToTensor(AbsPath(snapshot_path_, next_chunk));
*end_of_splits = false;
return absl::OkStatus();
}
if (snapshot_state_.snapshot_is_done) {
*end_of_splits = true;
return absl::OkStatus();
}
TF_RETURN_IF_ERROR(UpdateSnapshot());
}
}
absl::Status SnapshotChunkProvider::UpdateSnapshot()
ABSL_EXCLUSIVE_LOCKS_REQUIRED(mu_) {
TF_ASSIGN_OR_RETURN(snapshot_state_, GetSnapshotState());
TF_RETURN_IF_ERROR(snapshot_state_.status);
TF_ASSIGN_OR_RETURN(std::vector<std::string> chunks, GetAvailableChunks());
for (const std::string& chunk : chunks) {
if (!chunks_read_.contains(chunk)) {
chunks_unread_.insert(std::string(chunk));
}
}
return absl::OkStatus();
}
absl::StatusOr<SnapshotChunkProvider::SnapshotState>
SnapshotChunkProvider::GetSnapshotState() {
std::string error_file_path = SnapshotErrorFilePath(snapshot_path_);
if (env_->FileExists(error_file_path).ok()) {
StatusProto status_proto;
TF_RETURN_IF_ERROR(ReadTextProto(env_, error_file_path, &status_proto));
absl::Status status = tsl::StatusFromProto(status_proto);
if (status.ok()) {
return absl::InternalError(absl::StrCat(
"Unexpected snapshot ERROR file contains an OK status at ",
error_file_path, "."));
}
return SnapshotState(status);
}
return SnapshotState(
env_->FileExists(SnapshotDoneFilePath(snapshot_path_)).ok());
}
absl::StatusOr<std::vector<std::string>>
SnapshotChunkProvider::GetAvailableChunks() {
absl::StatusOr<std::vector<std::string>> status_or_chunks =
GetChildren(CommittedChunksDirectory(snapshot_path_), env_);
if (status_or_chunks.ok()) {
return *std::move(status_or_chunks);
} else if (absl::IsNotFound(status_or_chunks.status())) {
return std::vector<std::string>{};
}
return status_or_chunks.status();
}
absl::Status SnapshotChunkProvider::Reset() {
absl::MutexLock l(&mu_);
chunks_read_.clear();
chunks_unread_.clear();
return UpdateSnapshot();
}
absl::Status SnapshotChunkProvider::Save(
std::function<std::string(std::string)> full_name,
IteratorStateWriter* writer) {
absl::MutexLock l(&mu_);
TF_RETURN_IF_ERROR(
writer->WriteScalar(full_name(kChunksRead), SetToString(chunks_read_)));
return absl::OkStatus();
}
absl::Status SnapshotChunkProvider::Restore(
std::function<std::string(std::string)> full_name,
IteratorStateReader* reader) {
absl::MutexLock l(&mu_);
tsl::tstring chunks_read;
TF_RETURN_IF_ERROR(reader->ReadScalar(full_name(kChunksRead), &chunks_read));
chunks_read_ = SetFromString(chunks_read);
return UpdateSnapshot();
}
int64_t SnapshotChunkProvider::Cardinality() const {
return SnapshotChunksCardinality(snapshot_path_, env_);
}
void SnapshotChunkProvider::Cancel() {
absl::MutexLock l(&mu_);
if (snapshot_state_.snapshot_is_done || !snapshot_state_.status.ok()) {
return;
}
snapshot_state_.status = absl::CancelledError(
absl::StrCat("Cancelled loading tf.data snapshot at ", snapshot_path_));
VLOG(2) << snapshot_state_.status;
}
std::string SnapshotChunkProvider::SetToString(
const SnapshotChunkProvider::OrderedChunkSet& s) {
return absl::StrJoin(s, kSetElementDelimiter);
}
SnapshotChunkProvider::OrderedChunkSet SnapshotChunkProvider::SetFromString(
absl::string_view s) {
if (s.empty()) {
return {};
}
std::vector<std::string> split = absl::StrSplit(s, kSetElementDelimiter);
return OrderedChunkSet(split.begin(), split.end());
}
bool SnapshotChunkProvider::ChunkOrder::operator()(
const std::string& chunk1, const std::string& chunk2) const {
absl::StatusOr<std::tuple<int64_t, int64_t, int64_t>> tokens1 =
ParseChunkFilename(chunk1);
absl::StatusOr<std::tuple<int64_t, int64_t, int64_t>> tokens2 =
ParseChunkFilename(chunk2);
if (!tokens1.status().ok()) {
LOG_EVERY_N_SEC(ERROR, 60) << "Failed to parse tf.data snapshot chunk file "
<< chunk1 << ": " << tokens1.status();
return chunk1 < chunk2;
}
if (!tokens2.status().ok()) {
LOG_EVERY_N_SEC(ERROR, 60) << "Failed to parse tf.data snapshot chunk file "
<< chunk2 << ": " << tokens2.status();
return chunk1 < chunk2;
}
auto [stream_index1, chunk_index1, num_records1] = *tokens1;
auto [stream_index2, chunk_index2, num_records2] = *tokens2;
if (chunk_index1 != chunk_index2) {
return chunk_index1 < chunk_index2;
}
return stream_index1 < stream_index2;
}
}
} | #include "tensorflow/core/data/service/snapshot/snapshot_chunk_provider.h"
#include <memory>
#include <optional>
#include <string>
#include <utility>
#include <vector>
#include "absl/algorithm/container.h"
#include "absl/memory/memory.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/str_cat.h"
#include "absl/synchronization/mutex.h"
#include "tensorflow/core/data/serialization_utils.h"
#include "tensorflow/core/data/service/snapshot/file_utils.h"
#include "tensorflow/core/data/service/snapshot/path_utils.h"
#include "tensorflow/core/framework/dataset.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/variant_tensor_data.h"
#include "tsl/lib/core/status_test_util.h"
#include "tsl/platform/env.h"
#include "tsl/platform/errors.h"
#include "tsl/platform/path.h"
#include "tsl/platform/status_matchers.h"
#include "tsl/platform/status_to_from_proto.h"
#include "tsl/platform/statusor.h"
#include "tsl/platform/test.h"
#include "tsl/platform/tstring.h"
#include "tsl/protobuf/status.pb.h"
namespace tensorflow {
namespace data {
namespace {
using ::testing::ElementsAreArray;
using ::testing::HasSubstr;
using ::testing::IsEmpty;
using ::testing::UnorderedElementsAreArray;
using ::tsl::testing::IsOkAndHolds;
using ::tsl::testing::StatusIs;
absl::StatusOr<std::string> CreateSnapshotDirectory() {
std::string snapshot_path;
if (!tsl::Env::Default()->LocalTempFilename(&snapshot_path)) {
return absl::FailedPreconditionError(
"Failed to create local temp file for snapshot.");
}
TF_RETURN_IF_ERROR(tsl::Env::Default()->RecursivelyCreateDir(
CommittedChunksDirectory(snapshot_path)));
return snapshot_path;
}
absl::Status WriteChunk(absl::string_view snapshot_path,
absl::string_view chunk_file) {
return AtomicallyWriteStringToFile(
tsl::io::JoinPath(CommittedChunksDirectory(snapshot_path), chunk_file),
"", tsl::Env::Default());
}
absl::Status SetDone(absl::string_view snapshot_path) {
return AtomicallyWriteStringToFile(SnapshotDoneFilePath(snapshot_path), "",
tsl::Env::Default());
}
absl::Status SetStatus(absl::string_view snapshot_path,
const absl::Status& status) {
return AtomicallyWriteTextProto(SnapshotErrorFilePath(snapshot_path),
tsl::StatusToProto(status),
tsl::Env::Default());
}
absl::StatusOr<std::string> GetChunk(
SnapshotChunkProvider& snapshot_chunk_provider) {
Tensor split;
bool end_of_splits = false;
TF_RETURN_IF_ERROR(snapshot_chunk_provider.GetNext(&split, &end_of_splits));
if (end_of_splits) {
return absl::OutOfRangeError("No more available chunks.");
}
return split.unaligned_flat<tsl::tstring>().data()[0];
}
absl::StatusOr<std::vector<std::string>> GetAllChunks(
SnapshotChunkProvider& snapshot_chunk_provider) {
std::vector<std::string> chunks;
while (true) {
Tensor split;
bool end_of_splits = false;
TF_RETURN_IF_ERROR(snapshot_chunk_provider.GetNext(&split, &end_of_splits));
if (end_of_splits) {
return chunks;
}
chunks.push_back(split.unaligned_flat<tsl::tstring>().data()[0]);
}
return chunks;
}
std::vector<std::string> JoinPaths(absl::string_view snapshot_path,
const std::vector<std::string> chunks) {
std::vector<std::string> joined_chunks;
for (absl::string_view chunk : chunks) {
joined_chunks.push_back(
tsl::io::JoinPath(CommittedChunksDirectory(snapshot_path), chunk));
}
return joined_chunks;
}
std::string full_name(const std::string& name) {
return FullName("test", name);
}
absl::Status SaveAndRestore(SplitProvider& split_provider) {
VariantTensorDataWriter writer;
TF_RETURN_IF_ERROR(split_provider.Save(full_name, &writer));
std::vector<const VariantTensorData*> variants;
writer.GetData(&variants);
VariantTensorDataReader reader(variants);
TF_RETURN_IF_ERROR(split_provider.Restore(full_name, &reader));
return absl::OkStatus();
}
TEST(SnapshotChunkProviderTest, EmptySnapshot) {
TF_ASSERT_OK_AND_ASSIGN(std::string snapshot_path, CreateSnapshotDirectory());
TF_ASSERT_OK(SetDone(snapshot_path));
SnapshotChunkProvider snapshot_chunk_provider(snapshot_path,
tsl::Env::Default());
EXPECT_THAT(GetAllChunks(snapshot_chunk_provider), IsOkAndHolds(IsEmpty()));
EXPECT_THAT(GetAllChunks(snapshot_chunk_provider), IsOkAndHolds(IsEmpty()));
}
TEST(SnapshotChunkProviderTest, SingleReader) {
TF_ASSERT_OK_AND_ASSIGN(std::string snapshot_path, CreateSnapshotDirectory());
std::vector<std::string> chunks = {"chunk_4_4_4", "chunk_3_3_3",
"chunk_2_2_2", "chunk_1_1_1",
"chunk_0_0_0"};
for (absl::string_view chunk : chunks) {
TF_ASSERT_OK(WriteChunk(snapshot_path, chunk));
}
TF_ASSERT_OK(SetDone(snapshot_path));
SnapshotChunkProvider snapshot_chunk_provider(snapshot_path,
tsl::Env::Default());
absl::c_reverse(chunks);
EXPECT_THAT(GetAllChunks(snapshot_chunk_provider),
IsOkAndHolds(ElementsAreArray(JoinPaths(snapshot_path, chunks))));
}
TEST(SnapshotChunkProviderTest, Cardinality) {
TF_ASSERT_OK_AND_ASSIGN(std::string snapshot_path, CreateSnapshotDirectory());
TF_ASSERT_OK(WriteChunk(snapshot_path, "chunk_0_0_0"));
SnapshotChunkProvider snapshot_chunk_provider(snapshot_path,
tsl::Env::Default());
EXPECT_EQ(snapshot_chunk_provider.Cardinality(), kUnknownCardinality);
std::vector<std::string> chunks = {"chunk_1_1_1", "chunk_2_2_2",
"chunk_3_3_3", "chunk_4_4_4"};
for (absl::string_view chunk : chunks) {
TF_ASSERT_OK(WriteChunk(snapshot_path, chunk));
}
EXPECT_EQ(snapshot_chunk_provider.Cardinality(), kUnknownCardinality);
TF_ASSERT_OK(SetDone(snapshot_path));
EXPECT_EQ(snapshot_chunk_provider.Cardinality(), 5);
}
TEST(SnapshotChunkProviderTest, WaitForSnapshot) {
std::string snapshot_path;
ASSERT_TRUE(tsl::Env::Default()->LocalTempFilename(&snapshot_path));
absl::Mutex mu;
std::vector<std::string> result;
std::unique_ptr<tsl::Thread> reader_thread =
absl::WrapUnique(tsl::Env::Default()->StartThread(
{}, "Reader",
[&snapshot_path, &mu, &result]() {
SnapshotChunkProvider snapshot_chunk_provider(snapshot_path,
tsl::Env::Default());
TF_ASSERT_OK_AND_ASSIGN(std::vector<std::string> chunks,
GetAllChunks(snapshot_chunk_provider));
absl::MutexLock l(&mu);
result = std::move(chunks);
}));
{
absl::MutexLock l(&mu);
EXPECT_TRUE(result.empty());
}
TF_ASSERT_OK(tsl::Env::Default()->RecursivelyCreateDir(
CommittedChunksDirectory(snapshot_path)));
TF_ASSERT_OK(WriteChunk(snapshot_path, "chunk_0_0_0"));
TF_ASSERT_OK(SetDone(snapshot_path));
reader_thread.reset();
absl::MutexLock l(&mu);
EXPECT_THAT(result,
ElementsAreArray(JoinPaths(snapshot_path, {"chunk_0_0_0"})));
}
TEST(SnapshotChunkProviderTest, ConcurrentReadWrite) {
TF_ASSERT_OK_AND_ASSIGN(std::string snapshot_path, CreateSnapshotDirectory());
const int num_readers = 10;
absl::Mutex mu;
SnapshotChunkProvider snapshot_chunk_provider(snapshot_path,
tsl::Env::Default());
std::vector<std::string> result;
std::vector<std::unique_ptr<tsl::Thread>> reader_threads;
for (int i = 0; i < num_readers; ++i) {
reader_threads.push_back(absl::WrapUnique(tsl::Env::Default()->StartThread(
{}, absl::StrCat("Reader_", i),
[&snapshot_chunk_provider, &mu, &result]() {
while (true) {
tsl::Env::Default()->SleepForMicroseconds(25);
Tensor split;
bool end_of_splits = false;
TF_ASSERT_OK(
snapshot_chunk_provider.GetNext(&split, &end_of_splits));
if (end_of_splits) {
break;
}
absl::MutexLock l(&mu);
result.push_back(split.unaligned_flat<tsl::tstring>().data()[0]);
}
})));
}
int num_streams = 10, num_chunks_per_stream = 50;
std::vector<std::unique_ptr<tsl::Thread>> stream_threads;
for (int i = 0; i < num_streams; ++i) {
stream_threads.push_back(absl::WrapUnique(tsl::Env::Default()->StartThread(
{}, absl::StrCat("Writer_", i),
[&snapshot_path, num_chunks_per_stream, i]() {
for (int j = 0; j < num_chunks_per_stream; ++j) {
std::string filename = absl::StrCat("chunk_", i, "_", j, "_1");
TF_ASSERT_OK(WriteChunk(snapshot_path, filename));
tsl::Env::Default()->SleepForMicroseconds(35);
}
})));
}
stream_threads.clear();
TF_ASSERT_OK(SetDone(snapshot_path));
reader_threads.clear();
std::vector<std::string> expected;
for (int i = 0; i < num_streams; ++i) {
for (int j = 0; j < num_chunks_per_stream; ++j) {
expected.push_back(absl::StrCat("chunk_", i, "_", j, "_1"));
}
}
EXPECT_THAT(result,
UnorderedElementsAreArray(JoinPaths(snapshot_path, expected)));
}
TEST(SnapshotChunkProviderTest, SaveRestore) {
TF_ASSERT_OK_AND_ASSIGN(std::string snapshot_path, CreateSnapshotDirectory());
std::vector<std::string> chunks = {"chunk_4_4_4", "chunk_3_3_3",
"chunk_2_2_2", "chunk_1_1_1",
"chunk_0_0_0"};
for (absl::string_view chunk : chunks) {
TF_ASSERT_OK(WriteChunk(snapshot_path, chunk));
}
TF_ASSERT_OK(SetDone(snapshot_path));
SnapshotChunkProvider snapshot_chunk_provider(snapshot_path,
tsl::Env::Default());
EXPECT_THAT(GetChunk(snapshot_chunk_provider),
IsOkAndHolds(tsl::io::JoinPath(
CommittedChunksDirectory(snapshot_path), "chunk_0_0_0")));
TF_ASSERT_OK(SaveAndRestore(snapshot_chunk_provider));
EXPECT_THAT(GetAllChunks(snapshot_chunk_provider),
IsOkAndHolds(ElementsAreArray(
JoinPaths(snapshot_path, {"chunk_1_1_1", "chunk_2_2_2",
"chunk_3_3_3", "chunk_4_4_4"}))));
}
TEST(SnapshotChunkProviderTest, SnapshotError) {
TF_ASSERT_OK_AND_ASSIGN(std::string snapshot_path, CreateSnapshotDirectory());
std::unique_ptr<tsl::Thread> reader_thread =
absl::WrapUnique(tsl::Env::Default()->StartThread(
{}, "Reader", [&snapshot_path]() {
SnapshotChunkProvider snapshot_chunk_provider(snapshot_path,
tsl::Env::Default());
EXPECT_THAT(
GetAllChunks(snapshot_chunk_provider),
StatusIs(absl::StatusCode::kFailedPrecondition, "Test error."));
}));
TF_ASSERT_OK(WriteChunk(snapshot_path, "chunk_0_0_0"));
TF_ASSERT_OK(WriteChunk(snapshot_path, "chunk_1_0_0"));
TF_ASSERT_OK(WriteChunk(snapshot_path, "chunk_2_0_0"));
TF_ASSERT_OK(
SetStatus(snapshot_path, absl::FailedPreconditionError("Test error.")));
reader_thread.reset();
}
TEST(SnapshotChunkProviderTest, Cancel) {
TF_ASSERT_OK_AND_ASSIGN(std::string snapshot_path, CreateSnapshotDirectory());
SnapshotChunkProvider snapshot_chunk_provider(snapshot_path,
tsl::Env::Default());
std::unique_ptr<tsl::Thread> reader_thread =
absl::WrapUnique(tsl::Env::Default()->StartThread(
{}, "Reader",
[&snapshot_chunk_provider]() {
EXPECT_THAT(
GetAllChunks(snapshot_chunk_provider),
StatusIs(absl::StatusCode::kCancelled,
HasSubstr("Cancelled loading tf.data snapshot at")));
}));
TF_ASSERT_OK(WriteChunk(snapshot_path, "chunk_0_0_0"));
TF_ASSERT_OK(WriteChunk(snapshot_path, "chunk_1_0_0"));
TF_ASSERT_OK(WriteChunk(snapshot_path, "chunk_2_0_0"));
snapshot_chunk_provider.Cancel();
reader_thread.reset();
}
}
}
} |
310 | #ifndef STORAGE_LEVELDB_INCLUDE_WRITE_BATCH_H_
#define STORAGE_LEVELDB_INCLUDE_WRITE_BATCH_H_
#include <string>
#include "leveldb/export.h"
#include "leveldb/status.h"
namespace leveldb {
class Slice;
class LEVELDB_EXPORT WriteBatch {
public:
class LEVELDB_EXPORT Handler {
public:
virtual ~Handler();
virtual void Put(const Slice& key, const Slice& value) = 0;
virtual void Delete(const Slice& key) = 0;
};
WriteBatch();
WriteBatch(const WriteBatch&) = default;
WriteBatch& operator=(const WriteBatch&) = default;
~WriteBatch();
void Put(const Slice& key, const Slice& value);
void Delete(const Slice& key);
void Clear();
size_t ApproximateSize() const;
void Append(const WriteBatch& source);
Status Iterate(Handler* handler) const;
private:
friend class WriteBatchInternal;
std::string rep_;
};
}
#endif
#include "leveldb/write_batch.h"
#include "db/dbformat.h"
#include "db/memtable.h"
#include "db/write_batch_internal.h"
#include "leveldb/db.h"
#include "util/coding.h"
namespace leveldb {
static const size_t kHeader = 12;
WriteBatch::WriteBatch() { Clear(); }
WriteBatch::~WriteBatch() = default;
WriteBatch::Handler::~Handler() = default;
void WriteBatch::Clear() {
rep_.clear();
rep_.resize(kHeader);
}
size_t WriteBatch::ApproximateSize() const { return rep_.size(); }
Status WriteBatch::Iterate(Handler* handler) const {
Slice input(rep_);
if (input.size() < kHeader) {
return Status::Corruption("malformed WriteBatch (too small)");
}
input.remove_prefix(kHeader);
Slice key, value;
int found = 0;
while (!input.empty()) {
found++;
char tag = input[0];
input.remove_prefix(1);
switch (tag) {
case kTypeValue:
if (GetLengthPrefixedSlice(&input, &key) &&
GetLengthPrefixedSlice(&input, &value)) {
handler->Put(key, value);
} else {
return Status::Corruption("bad WriteBatch Put");
}
break;
case kTypeDeletion:
if (GetLengthPrefixedSlice(&input, &key)) {
handler->Delete(key);
} else {
return Status::Corruption("bad WriteBatch Delete");
}
break;
default:
return Status::Corruption("unknown WriteBatch tag");
}
}
if (found != WriteBatchInternal::Count(this)) {
return Status::Corruption("WriteBatch has wrong count");
} else {
return Status::OK();
}
}
int WriteBatchInternal::Count(const WriteBatch* b) {
return DecodeFixed32(b->rep_.data() + 8);
}
void WriteBatchInternal::SetCount(WriteBatch* b, int n) {
EncodeFixed32(&b->rep_[8], n);
}
SequenceNumber WriteBatchInternal::Sequence(const WriteBatch* b) {
return SequenceNumber(DecodeFixed64(b->rep_.data()));
}
void WriteBatchInternal::SetSequence(WriteBatch* b, SequenceNumber seq) {
EncodeFixed64(&b->rep_[0], seq);
}
void WriteBatch::Put(const Slice& key, const Slice& value) {
WriteBatchInternal::SetCount(this, WriteBatchInternal::Count(this) + 1);
rep_.push_back(static_cast<char>(kTypeValue));
PutLengthPrefixedSlice(&rep_, key);
PutLengthPrefixedSlice(&rep_, value);
}
void WriteBatch::Delete(const Slice& key) {
WriteBatchInternal::SetCount(this, WriteBatchInternal::Count(this) + 1);
rep_.push_back(static_cast<char>(kTypeDeletion));
PutLengthPrefixedSlice(&rep_, key);
}
void WriteBatch::Append(const WriteBatch& source) {
WriteBatchInternal::Append(this, &source);
}
namespace {
class MemTableInserter : public WriteBatch::Handler {
public:
SequenceNumber sequence_;
MemTable* mem_;
void Put(const Slice& key, const Slice& value) override {
mem_->Add(sequence_, kTypeValue, key, value);
sequence_++;
}
void Delete(const Slice& key) override {
mem_->Add(sequence_, kTypeDeletion, key, Slice());
sequence_++;
}
};
}
Status WriteBatchInternal::InsertInto(const WriteBatch* b, MemTable* memtable) {
MemTableInserter inserter;
inserter.sequence_ = WriteBatchInternal::Sequence(b);
inserter.mem_ = memtable;
return b->Iterate(&inserter);
}
void WriteBatchInternal::SetContents(WriteBatch* b, const Slice& contents) {
assert(contents.size() >= kHeader);
b->rep_.assign(contents.data(), contents.size());
}
void WriteBatchInternal::Append(WriteBatch* dst, const WriteBatch* src) {
SetCount(dst, Count(dst) + Count(src));
assert(src->rep_.size() >= kHeader);
dst->rep_.append(src->rep_.data() + kHeader, src->rep_.size() - kHeader);
}
} | #include "gtest/gtest.h"
#include "db/memtable.h"
#include "db/write_batch_internal.h"
#include "leveldb/db.h"
#include "leveldb/env.h"
#include "util/logging.h"
namespace leveldb {
static std::string PrintContents(WriteBatch* b) {
InternalKeyComparator cmp(BytewiseComparator());
MemTable* mem = new MemTable(cmp);
mem->Ref();
std::string state;
Status s = WriteBatchInternal::InsertInto(b, mem);
int count = 0;
Iterator* iter = mem->NewIterator();
for (iter->SeekToFirst(); iter->Valid(); iter->Next()) {
ParsedInternalKey ikey;
EXPECT_TRUE(ParseInternalKey(iter->key(), &ikey));
switch (ikey.type) {
case kTypeValue:
state.append("Put(");
state.append(ikey.user_key.ToString());
state.append(", ");
state.append(iter->value().ToString());
state.append(")");
count++;
break;
case kTypeDeletion:
state.append("Delete(");
state.append(ikey.user_key.ToString());
state.append(")");
count++;
break;
}
state.append("@");
state.append(NumberToString(ikey.sequence));
}
delete iter;
if (!s.ok()) {
state.append("ParseError()");
} else if (count != WriteBatchInternal::Count(b)) {
state.append("CountMismatch()");
}
mem->Unref();
return state;
}
TEST(WriteBatchTest, Empty) {
WriteBatch batch;
ASSERT_EQ("", PrintContents(&batch));
ASSERT_EQ(0, WriteBatchInternal::Count(&batch));
}
TEST(WriteBatchTest, Multiple) {
WriteBatch batch;
batch.Put(Slice("foo"), Slice("bar"));
batch.Delete(Slice("box"));
batch.Put(Slice("baz"), Slice("boo"));
WriteBatchInternal::SetSequence(&batch, 100);
ASSERT_EQ(100, WriteBatchInternal::Sequence(&batch));
ASSERT_EQ(3, WriteBatchInternal::Count(&batch));
ASSERT_EQ(
"Put(baz, boo)@102"
"Delete(box)@101"
"Put(foo, bar)@100",
PrintContents(&batch));
}
TEST(WriteBatchTest, Corruption) {
WriteBatch batch;
batch.Put(Slice("foo"), Slice("bar"));
batch.Delete(Slice("box"));
WriteBatchInternal::SetSequence(&batch, 200);
Slice contents = WriteBatchInternal::Contents(&batch);
WriteBatchInternal::SetContents(&batch,
Slice(contents.data(), contents.size() - 1));
ASSERT_EQ(
"Put(foo, bar)@200"
"ParseError()",
PrintContents(&batch));
}
TEST(WriteBatchTest, Append) {
WriteBatch b1, b2;
WriteBatchInternal::SetSequence(&b1, 200);
WriteBatchInternal::SetSequence(&b2, 300);
b1.Append(b2);
ASSERT_EQ("", PrintContents(&b1));
b2.Put("a", "va");
b1.Append(b2);
ASSERT_EQ("Put(a, va)@200", PrintContents(&b1));
b2.Clear();
b2.Put("b", "vb");
b1.Append(b2);
ASSERT_EQ(
"Put(a, va)@200"
"Put(b, vb)@201",
PrintContents(&b1));
b2.Delete("foo");
b1.Append(b2);
ASSERT_EQ(
"Put(a, va)@200"
"Put(b, vb)@202"
"Put(b, vb)@201"
"Delete(foo)@203",
PrintContents(&b1));
}
TEST(WriteBatchTest, ApproximateSize) {
WriteBatch batch;
size_t empty_size = batch.ApproximateSize();
batch.Put(Slice("foo"), Slice("bar"));
size_t one_key_size = batch.ApproximateSize();
ASSERT_LT(empty_size, one_key_size);
batch.Put(Slice("baz"), Slice("boo"));
size_t two_keys_size = batch.ApproximateSize();
ASSERT_LT(one_key_size, two_keys_size);
batch.Delete(Slice("box"));
size_t post_delete_size = batch.ApproximateSize();
ASSERT_LT(two_keys_size, post_delete_size);
}
} |
311 | #ifndef TENSORFLOW_LITE_TOCO_TFLITE_IMPORT_H_
#define TENSORFLOW_LITE_TOCO_TFLITE_IMPORT_H_
#include <string>
#include "tensorflow/lite/schema/schema_generated.h"
#include "tensorflow/lite/toco/model.h"
#include "tensorflow/lite/toco/model_flags.pb.h"
namespace toco {
namespace tflite {
std::unique_ptr<Model> Import(const ModelFlags &model_flags,
const std::string &input_file_contents);
namespace details {
using TensorsTable = std::vector<std::string>;
using OperatorsTable = std::vector<std::string>;
void LoadTensorsTable(const ::tflite::Model &input_model,
TensorsTable *tensors_table);
void LoadOperatorsTable(const ::tflite::Model &input_model,
OperatorsTable *operators_table);
}
}
}
#endif
#include "tensorflow/lite/toco/tflite/import.h"
#include <memory>
#include <string>
#include "absl/log/check.h"
#include "absl/log/log.h"
#include "flatbuffers/verifier.h"
#include "tensorflow/lite/core/tools/verifier.h"
#include "tensorflow/lite/schema/schema_generated.h"
#include "tensorflow/lite/schema/schema_utils.h"
#include "tensorflow/lite/stderr_reporter.h"
#include "tensorflow/lite/toco/model.h"
#include "tensorflow/lite/toco/model_flags.pb.h"
#include "tensorflow/lite/toco/tflite/operator.h"
#include "tensorflow/lite/toco/tflite/types.h"
#include "tensorflow/lite/toco/tooling_util.h"
namespace toco {
namespace tflite {
namespace details {
void LoadTensorsTable(const ::tflite::Model& input_model,
TensorsTable* tensors_table) {
auto tensors = (*input_model.subgraphs())[0]->tensors();
if (!tensors) return;
for (const auto* tensor : *tensors) {
tensors_table->push_back(tensor->name()->c_str());
}
}
void LoadOperatorsTable(const ::tflite::Model& input_model,
OperatorsTable* operators_table) {
auto opcodes = input_model.operator_codes();
if (!opcodes) return;
for (const auto* opcode : *opcodes) {
auto builtin_code = GetBuiltinCode(opcode);
if (builtin_code != ::tflite::BuiltinOperator_CUSTOM) {
operators_table->push_back(EnumNameBuiltinOperator(builtin_code));
} else {
operators_table->push_back(opcode->custom_code()->c_str());
}
}
}
}
void ImportTensors(const ::tflite::Model& input_model, Model* model) {
auto tensors = (*input_model.subgraphs())[0]->tensors();
auto* buffers = input_model.buffers();
if (!tensors) return;
for (const auto* input_tensor : *tensors) {
Array& array = model->GetOrCreateArray(input_tensor->name()->c_str());
array.data_type = DataType::Deserialize(input_tensor->type());
int buffer_index = input_tensor->buffer();
auto* buffer = buffers->Get(buffer_index);
DataBuffer::Deserialize(*input_tensor, *buffer, &array);
auto shape = input_tensor->shape();
if (shape) {
array.mutable_shape()->mutable_dims()->clear();
for (uint32_t i = 0; i < shape->Length(); ++i) {
auto d = shape->Get(i);
array.mutable_shape()->mutable_dims()->push_back(d);
}
}
auto quantization = input_tensor->quantization();
if (quantization) {
if (quantization->min() && quantization->max()) {
CHECK_EQ(1, quantization->min()->Length());
CHECK_EQ(1, quantization->max()->Length());
MinMax& minmax = array.GetOrCreateMinMax();
minmax.min = quantization->min()->Get(0);
minmax.max = quantization->max()->Get(0);
}
if (quantization->scale() && quantization->zero_point()) {
CHECK_EQ(1, quantization->scale()->Length());
CHECK_EQ(1, quantization->zero_point()->Length());
QuantizationParams& q = array.GetOrCreateQuantizationParams();
q.scale = quantization->scale()->Get(0);
q.zero_point = quantization->zero_point()->Get(0);
}
}
}
}
void ImportOperators(
const ::tflite::Model& input_model,
const std::map<std::string, std::unique_ptr<BaseOperator>>& ops_by_name,
const details::TensorsTable& tensors_table,
const details::OperatorsTable& operators_table, Model* model) {
auto ops = (*input_model.subgraphs())[0]->operators();
if (!ops) return;
for (const auto* input_op : *ops) {
uint32_t index = input_op->opcode_index();
if (index > operators_table.size()) {
LOG(FATAL) << "Index " << index << " must be between zero and "
<< operators_table.size();
}
std::string opname = operators_table.at(index);
std::unique_ptr<Operator> new_op = nullptr;
if (ops_by_name.count(opname) == 0) {
std::string effective_opname = "TENSORFLOW_UNSUPPORTED";
if (ops_by_name.count(effective_opname) == 0) {
LOG(FATAL) << "Internal logic error: TENSORFLOW_UNSUPPORTED not found.";
}
new_op = ops_by_name.at(effective_opname)
->Deserialize(input_op->builtin_options(),
input_op->custom_options());
if (new_op->type == OperatorType::kUnsupported) {
auto* unsupported_op =
static_cast<TensorFlowUnsupportedOperator*>(new_op.get());
unsupported_op->tensorflow_op = opname;
unsupported_op->quantized = true;
} else {
LOG(FATAL) << "Expected a TensorFlowUnsupportedOperator";
}
} else {
new_op = ops_by_name.at(opname)->Deserialize(input_op->builtin_options(),
input_op->custom_options());
}
model->operators.emplace_back(new_op.release());
auto* op = model->operators.back().get();
auto inputs = input_op->inputs();
for (uint32_t i = 0; i < inputs->Length(); i++) {
auto input_index = inputs->Get(i);
if (input_index != -1) {
const std::string& input_name = tensors_table.at(input_index);
op->inputs.push_back(input_name);
} else {
const std::string& tensor_name =
toco::AvailableArrayName(*model, "OptionalTensor");
model->CreateOptionalArray(tensor_name);
op->inputs.push_back(tensor_name);
}
}
auto outputs = input_op->outputs();
for (int i = 0, end = outputs->Length(); i < end; i++) {
auto output_index = outputs->Get(i);
const std::string& output_name = tensors_table.at(output_index);
op->outputs.push_back(output_name);
}
}
}
void ImportIOTensors(const ModelFlags& model_flags,
const ::tflite::Model& input_model,
const details::TensorsTable& tensors_table, Model* model) {
if (model_flags.input_arrays().empty()) {
auto inputs = (*input_model.subgraphs())[0]->inputs();
if (inputs) {
for (int input : *inputs) {
const std::string& input_name = tensors_table.at(input);
model->flags.add_input_arrays()->set_name(input_name);
}
}
}
if (model_flags.output_arrays().empty()) {
auto outputs = (*input_model.subgraphs())[0]->outputs();
if (outputs) {
for (int output : *outputs) {
const std::string& output_name = tensors_table.at(output);
model->flags.add_output_arrays(output_name);
}
}
}
}
namespace {
bool Verify(const void* buf, size_t len) {
::flatbuffers::Verifier verifier(static_cast<const uint8_t*>(buf), len);
return ::tflite::VerifyModelBuffer(verifier);
}
}
std::unique_ptr<Model> Import(const ModelFlags& model_flags,
const std::string& input_file_contents) {
::tflite::AlwaysTrueResolver r;
if (!::tflite::Verify(input_file_contents.data(), input_file_contents.size(),
r, ::tflite::DefaultErrorReporter())) {
LOG(FATAL) << "Invalid flatbuffer.";
}
const ::tflite::Model* input_model =
::tflite::GetModel(input_file_contents.data());
const auto ops_by_name = BuildOperatorByNameMap();
if (!input_model->subgraphs() || input_model->subgraphs()->size() != 1) {
LOG(FATAL) << "Number of subgraphs in tflite should be exactly 1.";
}
std::unique_ptr<Model> model;
model = std::make_unique<Model>();
details::TensorsTable tensors_table;
details::LoadTensorsTable(*input_model, &tensors_table);
details::OperatorsTable operators_table;
details::LoadOperatorsTable(*input_model, &operators_table);
ImportTensors(*input_model, model.get());
ImportOperators(*input_model, ops_by_name, tensors_table, operators_table,
model.get());
ImportIOTensors(model_flags, *input_model, tensors_table, model.get());
UndoWeightsShuffling(model.get());
return model;
}
}
} | #include "tensorflow/lite/toco/tflite/import.h"
#include <initializer_list>
#include <string>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "flatbuffers/flatbuffer_builder.h"
#include "tensorflow/lite/schema/schema_conversion_utils.h"
#include "tensorflow/lite/schema/schema_generated.h"
#include "tensorflow/lite/toco/model.h"
#include "tensorflow/lite/toco/model_flags.pb.h"
#include "tensorflow/lite/toco/toco_types.h"
#include "tensorflow/lite/version.h"
namespace toco {
namespace tflite {
namespace {
using ::testing::ElementsAre;
using flatbuffers::Offset;
using flatbuffers::Vector;
class ImportTest : public ::testing::Test {
protected:
template <typename T>
Offset<Vector<unsigned char>> CreateDataVector(const std::vector<T>& data) {
return builder_.CreateVector(reinterpret_cast<const uint8_t*>(data.data()),
sizeof(T) * data.size());
}
Offset<Vector<Offset<::tflite::Buffer>>> BuildBuffers() {
auto buf0 = ::tflite::CreateBuffer(builder_, CreateDataVector<float>({}));
auto buf1 = ::tflite::CreateBuffer(
builder_, CreateDataVector<float>({1.0f, 2.0f, 3.0f, 4.0f}));
auto buf2 =
::tflite::CreateBuffer(builder_, CreateDataVector<float>({3.0f, 4.0f}));
return builder_.CreateVector(
std::vector<Offset<::tflite::Buffer>>({buf0, buf1, buf2}));
}
Offset<Vector<Offset<::tflite::Tensor>>> BuildTensors() {
auto q = ::tflite::CreateQuantizationParameters(
builder_,
builder_.CreateVector<float>({0.1f}),
builder_.CreateVector<float>({0.2f}),
builder_.CreateVector<float>({0.3f}),
builder_.CreateVector<int64_t>({100LL}));
auto t1 =
::tflite::CreateTensor(builder_, builder_.CreateVector<int>({1, 2, 2}),
::tflite::TensorType_FLOAT32, 1,
builder_.CreateString("tensor_one"), q);
auto t2 =
::tflite::CreateTensor(builder_, builder_.CreateVector<int>({2, 1}),
::tflite::TensorType_FLOAT32, 0,
builder_.CreateString("tensor_two"), q);
return builder_.CreateVector(
std::vector<Offset<::tflite::Tensor>>({t1, t2}));
}
Offset<Vector<Offset<::tflite::OperatorCode>>> BuildOpCodes(
std::initializer_list<::tflite::BuiltinOperator> op_codes) {
std::vector<Offset<::tflite::OperatorCode>> op_codes_vector;
for (auto op : op_codes) {
op_codes_vector.push_back(::tflite::CreateOperatorCode(builder_, op, 0));
}
return builder_.CreateVector(op_codes_vector);
}
Offset<Vector<Offset<::tflite::OperatorCode>>> BuildOpCodes() {
return BuildOpCodes({::tflite::BuiltinOperator_MAX_POOL_2D,
::tflite::BuiltinOperator_CONV_2D});
}
Offset<Vector<Offset<::tflite::Operator>>> BuildOperators(
std::initializer_list<int> inputs, std::initializer_list<int> outputs) {
auto is = builder_.CreateVector<int>(inputs);
if (inputs.size() == 0) is = 0;
auto os = builder_.CreateVector<int>(outputs);
if (outputs.size() == 0) os = 0;
auto op = ::tflite::CreateOperator(
builder_, 0, is, os, ::tflite::BuiltinOptions_Conv2DOptions,
::tflite::CreateConv2DOptions(builder_, ::tflite::Padding_VALID, 1, 1,
::tflite::ActivationFunctionType_NONE)
.Union(),
0, ::tflite::CustomOptionsFormat_FLEXBUFFERS);
return builder_.CreateVector(std::vector<Offset<::tflite::Operator>>({op}));
}
Offset<Vector<Offset<::tflite::Operator>>> BuildOperators() {
return BuildOperators({0}, {1});
}
Offset<Vector<Offset<::tflite::SubGraph>>> BuildSubGraphs(
Offset<Vector<Offset<::tflite::Tensor>>> tensors,
Offset<Vector<Offset<::tflite::Operator>>> operators,
int num_sub_graphs = 1) {
std::vector<int32_t> inputs = {0};
std::vector<int32_t> outputs = {1};
std::vector<Offset<::tflite::SubGraph>> v;
for (int i = 0; i < num_sub_graphs; ++i) {
v.push_back(::tflite::CreateSubGraph(
builder_, tensors, builder_.CreateVector(inputs),
builder_.CreateVector(outputs), operators,
builder_.CreateString("subgraph")));
}
return builder_.CreateVector(v);
}
void BuildTestModel() {
auto buffers = BuildBuffers();
auto tensors = BuildTensors();
auto opcodes = BuildOpCodes();
auto operators = BuildOperators();
auto subgraphs = BuildSubGraphs(tensors, operators);
auto s = builder_.CreateString("");
::tflite::FinishModelBuffer(
builder_, ::tflite::CreateModel(builder_, TFLITE_SCHEMA_VERSION,
opcodes, subgraphs, s, buffers));
input_model_ = ::tflite::GetModel(builder_.GetBufferPointer());
}
std::string InputModelAsString() {
return std::string(reinterpret_cast<char*>(builder_.GetBufferPointer()),
builder_.GetSize());
}
flatbuffers::FlatBufferBuilder builder_;
const ::tflite::Model* input_model_ = nullptr;
};
TEST_F(ImportTest, LoadTensorsTable) {
BuildTestModel();
details::TensorsTable tensors;
details::LoadTensorsTable(*input_model_, &tensors);
EXPECT_THAT(tensors, ElementsAre("tensor_one", "tensor_two"));
}
TEST_F(ImportTest, LoadOperatorsTable) {
BuildTestModel();
details::OperatorsTable operators;
details::LoadOperatorsTable(*input_model_, &operators);
EXPECT_THAT(operators, ElementsAre("MAX_POOL_2D", "CONV_2D"));
}
TEST_F(ImportTest, Tensors) {
BuildTestModel();
auto model = Import(ModelFlags(), InputModelAsString());
ASSERT_GT(model->HasArray("tensor_one"), 0);
Array& a1 = model->GetArray("tensor_one");
EXPECT_EQ(ArrayDataType::kFloat, a1.data_type);
EXPECT_THAT(a1.GetBuffer<ArrayDataType::kFloat>().data,
ElementsAre(1.0f, 2.0f, 3.0f, 4.0f));
ASSERT_TRUE(a1.has_shape());
EXPECT_THAT(a1.shape().dims(), ElementsAre(1, 2, 2));
const auto& mm = a1.minmax;
ASSERT_TRUE(mm.get());
EXPECT_FLOAT_EQ(0.1, mm->min);
EXPECT_FLOAT_EQ(0.2, mm->max);
const auto& q = a1.quantization_params;
ASSERT_TRUE(q.get());
EXPECT_FLOAT_EQ(0.3, q->scale);
EXPECT_EQ(100, q->zero_point);
}
TEST_F(ImportTest, NoBuffers) {
auto buffers = 0;
auto tensors = BuildTensors();
auto opcodes = BuildOpCodes();
auto operators = BuildOperators();
auto subgraphs = BuildSubGraphs(tensors, operators);
auto comment = builder_.CreateString("");
::tflite::FinishModelBuffer(
builder_, ::tflite::CreateModel(builder_, TFLITE_SCHEMA_VERSION, opcodes,
subgraphs, comment, buffers));
EXPECT_DEATH(Import(ModelFlags(), InputModelAsString()),
"Missing 'buffers' section.");
}
TEST_F(ImportTest, NoInputs) {
auto buffers = BuildBuffers();
auto tensors = BuildTensors();
auto opcodes = BuildOpCodes();
auto operators = BuildOperators({}, {1});
auto subgraphs = BuildSubGraphs(tensors, operators);
auto comment = builder_.CreateString("");
::tflite::FinishModelBuffer(
builder_, ::tflite::CreateModel(builder_, TFLITE_SCHEMA_VERSION, opcodes,
subgraphs, comment, buffers));
EXPECT_DEATH(Import(ModelFlags(), InputModelAsString()),
"Missing 'inputs' for operator.");
}
TEST_F(ImportTest, NoOutputs) {
auto buffers = BuildBuffers();
auto tensors = BuildTensors();
auto opcodes = BuildOpCodes();
auto operators = BuildOperators({0}, {});
auto subgraphs = BuildSubGraphs(tensors, operators);
auto comment = builder_.CreateString("");
::tflite::FinishModelBuffer(
builder_, ::tflite::CreateModel(builder_, TFLITE_SCHEMA_VERSION, opcodes,
subgraphs, comment, buffers));
EXPECT_DEATH(Import(ModelFlags(), InputModelAsString()),
"Missing 'outputs' for operator.");
}
TEST_F(ImportTest, InvalidOpCode) {
auto buffers = BuildBuffers();
auto tensors = BuildTensors();
auto opcodes = BuildOpCodes({static_cast<::tflite::BuiltinOperator>(-1),
::tflite::BuiltinOperator_CONV_2D});
auto operators = BuildOperators();
auto subgraphs = BuildSubGraphs(tensors, operators);
auto comment = builder_.CreateString("");
::tflite::FinishModelBuffer(
builder_, ::tflite::CreateModel(builder_, TFLITE_SCHEMA_VERSION, opcodes,
subgraphs, comment, buffers));
EXPECT_DEATH(Import(ModelFlags(), InputModelAsString()),
"Operator id '-1' is out of range.");
}
TEST_F(ImportTest, MultipleSubGraphs) {
auto buffers = BuildBuffers();
auto tensors = BuildTensors();
auto opcodes = BuildOpCodes();
auto operators = BuildOperators();
auto subgraphs = BuildSubGraphs(tensors, operators, 2);
auto comment = builder_.CreateString("");
::tflite::FinishModelBuffer(
builder_, ::tflite::CreateModel(builder_, TFLITE_SCHEMA_VERSION, opcodes,
subgraphs, comment, buffers));
input_model_ = ::tflite::GetModel(builder_.GetBufferPointer());
EXPECT_DEATH(Import(ModelFlags(), InputModelAsString()),
"Number of subgraphs in tflite should be exactly 1.");
}
}
}
} |
312 | #ifndef XLA_SERVICE_GPU_EXECUTION_STREAM_ASSIGNMENT_H_
#define XLA_SERVICE_GPU_EXECUTION_STREAM_ASSIGNMENT_H_
#include "absl/container/flat_hash_map.h"
#include "absl/log/check.h"
#include "absl/status/statusor.h"
#include "xla/hlo/ir/hlo_instruction.h"
#include "xla/hlo/ir/hlo_instructions.h"
#include "xla/hlo/ir/hlo_module.h"
#include "xla/service/gpu/runtime/thunk.h"
namespace xla::gpu {
class ExecutionStreamAssignment {
public:
explicit ExecutionStreamAssignment(const HloModule* module);
absl::StatusOr<ExecutionStreamId> GetSyncExecutionStreamId(
const HloInstruction* instruction) const;
struct AsyncExecutionStreamIds {
ExecutionStreamId source_stream_id;
ExecutionStreamId destination_stream_id;
};
absl::StatusOr<AsyncExecutionStreamIds> GetAsyncExecutionStreamIds(
const HloAsyncInstruction* instruction) const;
private:
absl::flat_hash_map<HloInstruction*, ExecutionStreamId> sync_instructions_;
absl::flat_hash_map<HloInstruction*, AsyncExecutionStreamIds>
async_instructions_;
};
inline bool operator==(
const ExecutionStreamAssignment::AsyncExecutionStreamIds& first,
const ExecutionStreamAssignment::AsyncExecutionStreamIds& second) {
return first.source_stream_id == second.source_stream_id &&
first.destination_stream_id == second.destination_stream_id;
}
}
#endif
#include "xla/service/gpu/execution_stream_assignment.h"
#include <deque>
#include <memory>
#include <utility>
#include "absl/container/flat_hash_map.h"
#include "absl/log/check.h"
#include "absl/status/status.h"
#include "absl/strings/str_cat.h"
#include "xla/hlo/ir/hlo_casting_utils.h"
#include "xla/hlo/ir/hlo_computation.h"
#include "xla/hlo/ir/hlo_instruction.h"
#include "xla/hlo/ir/hlo_instructions.h"
#include "xla/hlo/ir/hlo_module.h"
#include "xla/hlo/ir/hlo_opcode.h"
#include "xla/service/call_graph.h"
#include "xla/service/gpu/runtime/thunk.h"
namespace xla::gpu {
ExecutionStreamAssignment::ExecutionStreamAssignment(const HloModule* module) {
std::unique_ptr<CallGraph> call_graph = CallGraph::Build(module);
ExecutionStreamId next_stream_id = ExecutionStreamId(1);
struct Pending {
Pending(HloComputation* node, ExecutionStreamId stream_id)
: node(node), stream_id(stream_id) {}
HloComputation* node;
ExecutionStreamId stream_id;
};
std::deque<Pending> queue;
queue.emplace_back(module->entry_computation(), ExecutionStreamId(0));
auto enqueue_called_computations = [&](const CallSite& callsite,
ExecutionStreamId stream) {
if (GetInstructionCallContext(callsite.instruction()->opcode()) ==
CallContext::kEmbedded) {
return;
}
for (HloComputation* computation : callsite.called_computations()) {
queue.emplace_back(computation, stream);
}
};
while (!queue.empty()) {
Pending pending = queue.front();
queue.pop_front();
for (HloInstruction* instruction : pending.node->instructions()) {
if (instruction->IsAsynchronous()) continue;
CHECK(sync_instructions_.try_emplace(instruction, pending.stream_id)
.second);
}
for (const CallSite& callsite :
call_graph->GetNode(pending.node).callsites()) {
if (callsite.instruction()->IsAsynchronous()) {
CHECK_EQ(callsite.instruction()->opcode(), HloOpcode::kAsyncStart);
const ExecutionStreamId async_stream_id = next_stream_id++;
enqueue_called_computations(callsite, async_stream_id);
AsyncExecutionStreamIds streams;
streams.source_stream_id = pending.stream_id;
streams.destination_stream_id = async_stream_id;
CHECK(async_instructions_.try_emplace(callsite.instruction(), streams)
.second);
} else {
enqueue_called_computations(callsite, pending.stream_id);
}
}
for (HloInstruction* instruction : pending.node->instructions()) {
if (!instruction->IsAsynchronous()) continue;
if (instruction->opcode() == HloOpcode::kAsyncStart) {
CHECK(async_instructions_.find(instruction) !=
async_instructions_.end());
} else {
HloInstruction* async_start =
Cast<HloAsyncInstruction>(instruction)->async_chain_start();
AsyncExecutionStreamIds async_start_streams =
async_instructions_.at(async_start);
CHECK(async_instructions_.try_emplace(instruction, async_start_streams)
.second);
}
}
}
}
namespace {
absl::Status StreamNotFoundError(const HloInstruction* instruction) {
return absl::NotFoundError(absl::StrCat(
"No ExecutionStreamId found for ", instruction->ToString(),
"; this may happen if the Computation is not reachable from the module's "
"entrypoint, or if it's only reachable through a embedded calls."));
}
}
absl::StatusOr<ExecutionStreamId>
ExecutionStreamAssignment::GetSyncExecutionStreamId(
const HloInstruction* instruction) const {
CHECK(!instruction->IsAsynchronous());
auto stream = sync_instructions_.find(instruction);
if (stream == sync_instructions_.end()) {
return StreamNotFoundError(instruction);
}
return stream->second;
}
absl::StatusOr<ExecutionStreamAssignment::AsyncExecutionStreamIds>
ExecutionStreamAssignment::GetAsyncExecutionStreamIds(
const HloAsyncInstruction* instruction) const {
auto streams = async_instructions_.find(instruction);
if (streams == async_instructions_.end()) {
return StreamNotFoundError(instruction);
}
return streams->second;
}
} | #include "xla/service/gpu/execution_stream_assignment.h"
#include <memory>
#include <string_view>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "absl/status/status.h"
#include "absl/strings/string_view.h"
#include "xla/hlo/ir/hlo_casting_utils.h"
#include "xla/hlo/ir/hlo_computation.h"
#include "xla/hlo/ir/hlo_instruction.h"
#include "xla/hlo/ir/hlo_instructions.h"
#include "xla/hlo/ir/hlo_module.h"
#include "xla/service/gpu/runtime/thunk.h"
#include "xla/tests/hlo_test_base.h"
#include "tsl/platform/status_matchers.h"
#include "tsl/platform/statusor.h"
using ::tsl::testing::IsOkAndHolds;
using ::tsl::testing::StatusIs;
using AsyncExecutionStreamIds =
::xla::gpu::ExecutionStreamAssignment::AsyncExecutionStreamIds;
namespace xla::gpu {
namespace {
class ExecutionStreamAssignmentTest : public HloTestBase {
protected:
void ExpectExecutionStreamForSyncInstructions(
const ExecutionStreamAssignment& assignment, HloComputation* computation,
ExecutionStreamId stream) const {
for (const HloInstruction* instruction : computation->instructions()) {
if (instruction->IsAsynchronous()) continue;
EXPECT_THAT(assignment.GetSyncExecutionStreamId(instruction),
IsOkAndHolds(stream));
}
}
};
TEST_F(ExecutionStreamAssignmentTest, AsyncFusion) {
const char* kModuleStr = R"(
HloModule m
leaf1 {
p0 = f32[2,2] parameter(0)
ROOT add = f32[2,2] add(p0, p0)
}
leaf2 {
p0 = f32[2,2] parameter(0)
ROOT add = f32[2,2] add(p0, p0)
}
ENTRY entry {
p0 = f32[2,2] parameter(0)
start1 = ((f32[2,2]), f32[2,2], s32[]) fusion-start(p0),
kind=kLoop, calls=leaf1
start2 = ((f32[2,2]), f32[2,2], s32[]) fusion-start(p0),
kind=kLoop, calls=leaf2
update1 = ((f32[2,2]), f32[2,2], s32[]) fusion-update(start1)
update2 = ((f32[2,2]), f32[2,2], s32[]) fusion-update(start2)
done1 = f32[2,2] fusion-done(update1)
done2 = f32[2,2] fusion-done(update2)
ROOT done = f32[2,2] add(done1, done2)
}
)";
TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> module,
ParseAndReturnVerifiedModule(kModuleStr));
ExecutionStreamAssignment assignment(module.get());
ExpectExecutionStreamForSyncInstructions(
assignment, FindComputation(module.get(), "entry"), ExecutionStreamId(0));
for (std::string_view instruction : {"start1", "update1", "done1"}) {
EXPECT_THAT(assignment.GetAsyncExecutionStreamIds(Cast<HloAsyncInstruction>(
FindInstruction(module.get(), instruction))),
IsOkAndHolds(AsyncExecutionStreamIds(
ExecutionStreamId(0),
ExecutionStreamId(1))));
}
for (std::string_view instruction : {"start2", "update2", "done2"}) {
EXPECT_THAT(assignment.GetAsyncExecutionStreamIds(Cast<HloAsyncInstruction>(
FindInstruction(module.get(), instruction))),
IsOkAndHolds(AsyncExecutionStreamIds(
ExecutionStreamId(0),
ExecutionStreamId(2))));
}
ExpectExecutionStreamForSyncInstructions(
assignment,
Cast<HloAsyncInstruction>(FindInstruction(module.get(), "start1"))
->async_wrapped_computation(),
ExecutionStreamId(1));
ExpectExecutionStreamForSyncInstructions(
assignment,
Cast<HloAsyncInstruction>(FindInstruction(module.get(), "start2"))
->async_wrapped_computation(),
ExecutionStreamId(2));
}
TEST_F(ExecutionStreamAssignmentTest, FusionComputations) {
const char* kModuleStr = R"(
HloModule m
reduce {
p0 = f32[] parameter(0)
p1 = f32[] parameter(1)
ROOT add = f32[] add(p0, p1)
}
fusion {
p0 = f32[4] parameter(0)
c0 = f32[] constant(0)
ROOT reduce = f32[] reduce(p0, c0), dimensions={0}, to_apply=reduce
}
ENTRY entry {
p0 = f32[4] parameter(0)
ROOT done = f32[] fusion(p0), kind=kLoop, calls=fusion
}
)";
TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> module,
ParseAndReturnVerifiedModule(kModuleStr));
ExecutionStreamAssignment assignment(module.get());
ExpectExecutionStreamForSyncInstructions(
assignment, FindComputation(module.get(), "entry"), ExecutionStreamId(0));
for (std::string_view computation : {"reduce", "fusion"}) {
for (const HloInstruction* instruction :
FindComputation(module.get(), computation)->instructions()) {
EXPECT_THAT(assignment.GetSyncExecutionStreamId(instruction),
StatusIs(absl::StatusCode::kNotFound));
}
}
}
TEST_F(ExecutionStreamAssignmentTest, UnreachableComputation) {
const char* kModuleStr = R"(
HloModule m
unreachable {
p0 = f32[2,2] parameter(0)
ROOT add = f32[2,2] add(p0, p0)
}
ENTRY entry {
p0 = f32[2,2] parameter(0)
ROOT add = f32[2,2] add(p0, p0)
}
)";
TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> module,
ParseAndReturnVerifiedModule(kModuleStr));
ExecutionStreamAssignment assignment(module.get());
ExpectExecutionStreamForSyncInstructions(
assignment, FindComputation(module.get(), "entry"), ExecutionStreamId(0));
for (const HloInstruction* instruction :
FindComputation(module.get(), "unreachable")->instructions()) {
EXPECT_THAT(assignment.GetSyncExecutionStreamId(instruction),
StatusIs(absl::StatusCode::kNotFound));
}
}
}
} |
313 | #ifndef THIRD_PARTY_CEL_CPP_COMMON_INTERNAL_REFERENCE_COUNT_H_
#define THIRD_PARTY_CEL_CPP_COMMON_INTERNAL_REFERENCE_COUNT_H_
#include <atomic>
#include <cstdint>
#include <new>
#include <type_traits>
#include <utility>
#include "absl/base/attributes.h"
#include "absl/base/nullability.h"
#include "absl/base/optimization.h"
#include "absl/log/absl_check.h"
#include "common/arena.h"
#include "common/data.h"
#include "google/protobuf/arena.h"
#include "google/protobuf/message_lite.h"
namespace cel::common_internal {
struct AdoptRef final {
explicit AdoptRef() = default;
};
inline constexpr AdoptRef kAdoptRef{};
class ReferenceCount;
struct ReferenceCountFromThis;
void SetReferenceCountForThat(ReferenceCountFromThis& that,
absl::Nullable<ReferenceCount*> refcount);
ABSL_ATTRIBUTE_PURE_FUNCTION
absl::Nullable<ReferenceCount*> GetReferenceCountForThat(
const ReferenceCountFromThis& that);
struct ReferenceCountFromThis {
private:
friend void SetReferenceCountForThat(
ReferenceCountFromThis& that, absl::Nullable<ReferenceCount*> refcount);
friend absl::Nullable<ReferenceCount*> GetReferenceCountForThat(
const ReferenceCountFromThis& that);
static constexpr uintptr_t kNullPtr = uintptr_t{0};
static constexpr uintptr_t kSentinelPtr = ~kNullPtr;
absl::Nullable<void*> refcount = reinterpret_cast<void*>(kSentinelPtr);
};
inline void SetReferenceCountForThat(ReferenceCountFromThis& that,
absl::Nullable<ReferenceCount*> refcount) {
ABSL_DCHECK_EQ(that.refcount,
reinterpret_cast<void*>(ReferenceCountFromThis::kSentinelPtr));
that.refcount = static_cast<void*>(refcount);
}
inline absl::Nullable<ReferenceCount*> GetReferenceCountForThat(
const ReferenceCountFromThis& that) {
ABSL_DCHECK_NE(that.refcount,
reinterpret_cast<void*>(ReferenceCountFromThis::kSentinelPtr));
return static_cast<ReferenceCount*>(that.refcount);
}
void StrongRef(const ReferenceCount& refcount) noexcept;
void StrongRef(absl::Nullable<const ReferenceCount*> refcount) noexcept;
void StrongUnref(const ReferenceCount& refcount) noexcept;
void StrongUnref(absl::Nullable<const ReferenceCount*> refcount) noexcept;
ABSL_MUST_USE_RESULT
bool StrengthenRef(const ReferenceCount& refcount) noexcept;
ABSL_MUST_USE_RESULT
bool StrengthenRef(absl::Nullable<const ReferenceCount*> refcount) noexcept;
void WeakRef(const ReferenceCount& refcount) noexcept;
void WeakRef(absl::Nullable<const ReferenceCount*> refcount) noexcept;
void WeakUnref(const ReferenceCount& refcount) noexcept;
void WeakUnref(absl::Nullable<const ReferenceCount*> refcount) noexcept;
ABSL_MUST_USE_RESULT
bool IsUniqueRef(const ReferenceCount& refcount) noexcept;
ABSL_MUST_USE_RESULT
bool IsUniqueRef(absl::Nullable<const ReferenceCount*> refcount) noexcept;
ABSL_MUST_USE_RESULT
bool IsExpiredRef(const ReferenceCount& refcount) noexcept;
ABSL_MUST_USE_RESULT
bool IsExpiredRef(absl::Nullable<const ReferenceCount*> refcount) noexcept;
class alignas(8) ReferenceCount {
public:
ReferenceCount() = default;
ReferenceCount(const ReferenceCount&) = delete;
ReferenceCount(ReferenceCount&&) = delete;
ReferenceCount& operator=(const ReferenceCount&) = delete;
ReferenceCount& operator=(ReferenceCount&&) = delete;
virtual ~ReferenceCount() = default;
private:
friend void StrongRef(const ReferenceCount& refcount) noexcept;
friend void StrongUnref(const ReferenceCount& refcount) noexcept;
friend bool StrengthenRef(const ReferenceCount& refcount) noexcept;
friend void WeakRef(const ReferenceCount& refcount) noexcept;
friend void WeakUnref(const ReferenceCount& refcount) noexcept;
friend bool IsUniqueRef(const ReferenceCount& refcount) noexcept;
friend bool IsExpiredRef(const ReferenceCount& refcount) noexcept;
virtual void Finalize() noexcept = 0;
virtual void Delete() noexcept = 0;
mutable std::atomic<int32_t> strong_refcount_ = 1;
mutable std::atomic<int32_t> weak_refcount_ = 1;
};
static_assert(alignof(ReferenceCount) >= alignof(google::protobuf::Arena));
class ReferenceCounted : public ReferenceCount {
private:
void Finalize() noexcept override {}
void Delete() noexcept override { delete this; }
};
template <typename T>
class EmplacedReferenceCount final : public ReferenceCounted {
public:
static_assert(std::is_destructible_v<T>, "T must be destructible");
static_assert(!std::is_reference_v<T>, "T must not be a reference");
static_assert(!std::is_volatile_v<T>, "T must not be volatile qualified");
static_assert(!std::is_const_v<T>, "T must not be const qualified");
template <typename... Args>
explicit EmplacedReferenceCount(T*& value, Args&&... args) noexcept(
std::is_nothrow_constructible_v<T, Args...>) {
value =
::new (static_cast<void*>(&value_[0])) T(std::forward<Args>(args)...);
}
private:
void Finalize() noexcept override {
std::launder(reinterpret_cast<T*>(&value_[0]))->~T();
}
alignas(T) char value_[sizeof(T)];
};
template <typename T>
class DeletingReferenceCount final : public ReferenceCounted {
public:
explicit DeletingReferenceCount(absl::Nonnull<const T*> to_delete) noexcept
: to_delete_(to_delete) {}
private:
void Finalize() noexcept override {
delete std::exchange(to_delete_, nullptr);
}
const T* to_delete_;
};
extern template class DeletingReferenceCount<google::protobuf::MessageLite>;
extern template class DeletingReferenceCount<Data>;
template <typename T>
absl::Nonnull<const ReferenceCount*> MakeDeletingReferenceCount(
absl::Nonnull<const T*> to_delete) {
if constexpr (IsArenaConstructible<T>::value) {
ABSL_DCHECK_EQ(to_delete->GetArena(), nullptr);
}
if constexpr (std::is_base_of_v<google::protobuf::MessageLite, T>) {
return new DeletingReferenceCount<google::protobuf::MessageLite>(to_delete);
} else if constexpr (std::is_base_of_v<Data, T>) {
auto* refcount = new DeletingReferenceCount<Data>(to_delete);
common_internal::SetDataReferenceCount(to_delete, refcount);
return refcount;
} else {
return new DeletingReferenceCount<T>(to_delete);
}
}
template <typename T, typename... Args>
std::pair<absl::Nonnull<T*>, absl::Nonnull<const ReferenceCount*>>
MakeEmplacedReferenceCount(Args&&... args) {
using U = std::remove_const_t<T>;
U* pointer;
auto* const refcount =
new EmplacedReferenceCount<U>(pointer, std::forward<Args>(args)...);
if constexpr (IsArenaConstructible<U>::value) {
ABSL_DCHECK_EQ(pointer->GetArena(), nullptr);
}
if constexpr (std::is_base_of_v<Data, T>) {
common_internal::SetDataReferenceCount(pointer, refcount);
}
return std::pair{static_cast<absl::Nonnull<T*>>(pointer),
static_cast<absl::Nonnull<const ReferenceCount*>>(refcount)};
}
template <typename T>
class InlinedReferenceCount final : public ReferenceCounted {
public:
template <typename... Args>
explicit InlinedReferenceCount(std::in_place_t, Args&&... args)
: ReferenceCounted() {
::new (static_cast<void*>(value())) T(std::forward<Args>(args)...);
}
ABSL_ATTRIBUTE_ALWAYS_INLINE absl::Nonnull<T*> value() {
return reinterpret_cast<T*>(&value_[0]);
}
ABSL_ATTRIBUTE_ALWAYS_INLINE absl::Nonnull<const T*> value() const {
return reinterpret_cast<const T*>(&value_[0]);
}
private:
void Finalize() noexcept override { value()->~T(); }
alignas(T) char value_[sizeof(T)];
};
template <typename T, typename... Args>
std::pair<absl::Nonnull<T*>, absl::Nonnull<ReferenceCount*>> MakeReferenceCount(
Args&&... args) {
using U = std::remove_const_t<T>;
auto* const refcount =
new InlinedReferenceCount<U>(std::in_place, std::forward<Args>(args)...);
auto* const pointer = refcount->value();
if constexpr (std::is_base_of_v<ReferenceCountFromThis, U>) {
SetReferenceCountForThat(*pointer, refcount);
}
return std::make_pair(static_cast<T*>(pointer),
static_cast<ReferenceCount*>(refcount));
}
inline void StrongRef(const ReferenceCount& refcount) noexcept {
const auto count =
refcount.strong_refcount_.fetch_add(1, std::memory_order_relaxed);
ABSL_DCHECK_GT(count, 0);
}
inline void StrongRef(absl::Nullable<const ReferenceCount*> refcount) noexcept {
if (refcount != nullptr) {
StrongRef(*refcount);
}
}
inline void StrongUnref(const ReferenceCount& refcount) noexcept {
const auto count =
refcount.strong_refcount_.fetch_sub(1, std::memory_order_acq_rel);
ABSL_DCHECK_GT(count, 0);
ABSL_ASSUME(count > 0);
if (ABSL_PREDICT_FALSE(count == 1)) {
const_cast<ReferenceCount&>(refcount).Finalize();
WeakUnref(refcount);
}
}
inline void StrongUnref(
absl::Nullable<const ReferenceCount*> refcount) noexcept {
if (refcount != nullptr) {
StrongUnref(*refcount);
}
}
ABSL_MUST_USE_RESULT
inline bool StrengthenRef(const ReferenceCount& refcount) noexcept {
auto count = refcount.strong_refcount_.load(std::memory_order_relaxed);
while (true) {
ABSL_DCHECK_GE(count, 0);
ABSL_ASSUME(count >= 0);
if (count == 0) {
return false;
}
if (refcount.strong_refcount_.compare_exchange_weak(
count, count + 1, std::memory_order_release,
std::memory_order_relaxed)) {
return true;
}
}
}
ABSL_MUST_USE_RESULT
inline bool StrengthenRef(
absl::Nullable<const ReferenceCount*> refcount) noexcept {
return refcount != nullptr ? StrengthenRef(*refcount) : false;
}
inline void WeakRef(const ReferenceCount& refcount) noexcept {
const auto count =
refcount.weak_refcount_.fetch_add(1, std::memory_order_relaxed);
ABSL_DCHECK_GT(count, 0);
}
inline void WeakRef(absl::Nullable<const ReferenceCount*> refcount) noexcept {
if (refcount != nullptr) {
WeakRef(*refcount);
}
}
inline void WeakUnref(const ReferenceCount& refcount) noexcept {
const auto count =
refcount.weak_refcount_.fetch_sub(1, std::memory_order_acq_rel);
ABSL_DCHECK_GT(count, 0);
ABSL_ASSUME(count > 0);
if (ABSL_PREDICT_FALSE(count == 1)) {
const_cast<ReferenceCount&>(refcount).Delete();
}
}
inline void WeakUnref(absl::Nullable<const ReferenceCount*> refcount) noexcept {
if (refcount != nullptr) {
WeakUnref(*refcount);
}
}
ABSL_MUST_USE_RESULT
inline bool IsUniqueRef(const ReferenceCount& refcount) noexcept {
const auto count = refcount.strong_refcount_.load(std::memory_order_acquire);
ABSL_DCHECK_GT(count, 0);
ABSL_ASSUME(count > 0);
return count == 1;
}
ABSL_MUST_USE_RESULT
inline bool IsUniqueRef(
absl::Nullable<const ReferenceCount*> refcount) noexcept {
return refcount != nullptr ? IsUniqueRef(*refcount) : false;
}
ABSL_MUST_USE_RESULT
inline bool IsExpiredRef(const ReferenceCount& refcount) noexcept {
const auto count = refcount.strong_refcount_.load(std::memory_order_acquire);
ABSL_DCHECK_GE(count, 0);
ABSL_ASSUME(count >= 0);
return count == 0;
}
ABSL_MUST_USE_RESULT
inline bool IsExpiredRef(
absl::Nullable<const ReferenceCount*> refcount) noexcept {
return refcount != nullptr ? IsExpiredRef(*refcount) : false;
}
}
#endif
#include "common/internal/reference_count.h"
#include "common/data.h"
#include "google/protobuf/message_lite.h"
namespace cel::common_internal {
template class DeletingReferenceCount<google::protobuf::MessageLite>;
template class DeletingReferenceCount<Data>;
} | #include "common/internal/reference_count.h"
#include <tuple>
#include "google/protobuf/struct.pb.h"
#include "absl/base/nullability.h"
#include "common/data.h"
#include "internal/testing.h"
#include "google/protobuf/arena.h"
#include "google/protobuf/message_lite.h"
namespace cel::common_internal {
namespace {
using testing::NotNull;
using testing::WhenDynamicCastTo;
class Object : public virtual ReferenceCountFromThis {
public:
explicit Object(bool& destructed) : destructed_(destructed) {}
~Object() { destructed_ = true; }
private:
bool& destructed_;
};
class Subobject : public Object, public virtual ReferenceCountFromThis {
public:
using Object::Object;
};
TEST(ReferenceCount, Strong) {
bool destructed = false;
Object* object;
ReferenceCount* refcount;
std::tie(object, refcount) = MakeReferenceCount<Subobject>(destructed);
EXPECT_EQ(GetReferenceCountForThat(*object), refcount);
EXPECT_EQ(GetReferenceCountForThat(*static_cast<Subobject*>(object)),
refcount);
StrongRef(refcount);
StrongUnref(refcount);
EXPECT_TRUE(IsUniqueRef(refcount));
EXPECT_FALSE(IsExpiredRef(refcount));
EXPECT_FALSE(destructed);
StrongUnref(refcount);
EXPECT_TRUE(destructed);
}
TEST(ReferenceCount, Weak) {
bool destructed = false;
Object* object;
ReferenceCount* refcount;
std::tie(object, refcount) = MakeReferenceCount<Subobject>(destructed);
EXPECT_EQ(GetReferenceCountForThat(*object), refcount);
EXPECT_EQ(GetReferenceCountForThat(*static_cast<Subobject*>(object)),
refcount);
WeakRef(refcount);
ASSERT_TRUE(StrengthenRef(refcount));
StrongUnref(refcount);
EXPECT_TRUE(IsUniqueRef(refcount));
EXPECT_FALSE(IsExpiredRef(refcount));
EXPECT_FALSE(destructed);
StrongUnref(refcount);
EXPECT_TRUE(destructed);
EXPECT_TRUE(IsExpiredRef(refcount));
ASSERT_FALSE(StrengthenRef(refcount));
WeakUnref(refcount);
}
class DataObject final : public Data {
public:
DataObject() noexcept : Data() {}
explicit DataObject(absl::Nullable<google::protobuf::Arena*> arena) noexcept
: Data(arena) {}
char member_[17];
};
struct OtherObject final {
char data[17];
};
TEST(DeletingReferenceCount, Data) {
auto* data = new DataObject();
const auto* refcount = MakeDeletingReferenceCount(data);
EXPECT_THAT(refcount, WhenDynamicCastTo<const DeletingReferenceCount<Data>*>(
NotNull()));
EXPECT_EQ(common_internal::GetDataReferenceCount(data), refcount);
StrongUnref(refcount);
}
TEST(DeletingReferenceCount, MessageLite) {
auto* message_lite = new google::protobuf::Value();
const auto* refcount = MakeDeletingReferenceCount(message_lite);
EXPECT_THAT(
refcount,
WhenDynamicCastTo<const DeletingReferenceCount<google::protobuf::MessageLite>*>(
NotNull()));
StrongUnref(refcount);
}
TEST(DeletingReferenceCount, Other) {
auto* other = new OtherObject();
const auto* refcount = MakeDeletingReferenceCount(other);
EXPECT_THAT(
refcount,
WhenDynamicCastTo<const DeletingReferenceCount<OtherObject>*>(NotNull()));
StrongUnref(refcount);
}
TEST(EmplacedReferenceCount, Data) {
Data* data;
const ReferenceCount* refcount;
std::tie(data, refcount) = MakeEmplacedReferenceCount<DataObject>();
EXPECT_THAT(
refcount,
WhenDynamicCastTo<const EmplacedReferenceCount<DataObject>*>(NotNull()));
EXPECT_EQ(common_internal::GetDataReferenceCount(data), refcount);
StrongUnref(refcount);
}
TEST(EmplacedReferenceCount, MessageLite) {
google::protobuf::Value* message_lite;
const ReferenceCount* refcount;
std::tie(message_lite, refcount) =
MakeEmplacedReferenceCount<google::protobuf::Value>();
EXPECT_THAT(
refcount,
WhenDynamicCastTo<const EmplacedReferenceCount<google::protobuf::Value>*>(
NotNull()));
StrongUnref(refcount);
}
TEST(EmplacedReferenceCount, Other) {
OtherObject* other;
const ReferenceCount* refcount;
std::tie(other, refcount) = MakeEmplacedReferenceCount<OtherObject>();
EXPECT_THAT(
refcount,
WhenDynamicCastTo<const EmplacedReferenceCount<OtherObject>*>(NotNull()));
StrongUnref(refcount);
}
}
} |
314 | #ifndef XLA_SERVICE_CONVOLUTION_4D_EXPANDER_H_
#define XLA_SERVICE_CONVOLUTION_4D_EXPANDER_H_
#include "absl/status/statusor.h"
#include "absl/strings/string_view.h"
#include "xla/hlo/ir/hlo_instruction.h"
#include "xla/service/op_expander_pass.h"
namespace xla {
class Convolution4DExpander : public OpExpanderPass {
public:
absl::string_view name() const override { return "convolution_4d_expander"; }
protected:
bool InstructionMatchesPattern(HloInstruction* instruction) override;
absl::StatusOr<HloInstruction*> ExpandInstruction(
HloInstruction* instruction) override;
};
}
#endif
#include "xla/service/convolution_4d_expander.h"
#include <algorithm>
#include <functional>
#include <vector>
#include "absl/algorithm/container.h"
#include "absl/status/statusor.h"
#include "xla/hlo/ir/hlo_instruction.h"
#include "xla/shape_util.h"
#include "xla/status_macros.h"
#include "xla/xla_data.pb.h"
namespace xla {
bool Convolution4DExpander::InstructionMatchesPattern(
HloInstruction* instruction) {
if (instruction->opcode() != HloOpcode::kConvolution) {
return false;
}
const ConvolutionDimensionNumbers& dim_nums =
instruction->convolution_dimension_numbers();
if (dim_nums.input_spatial_dimensions().size() != 4) {
return false;
}
Shape input = instruction->operand(0)->shape();
for (int64_t i = 0; i < dim_nums.input_spatial_dimensions().size(); ++i) {
int64_t spatial_dim = dim_nums.input_spatial_dimensions(i);
if (input.dimensions(spatial_dim) == 1 &&
instruction->window().dimensions(i).padding_low() == 0 &&
instruction->window().dimensions(i).padding_high() == 0) {
return true;
}
}
return false;
}
absl::StatusOr<HloInstruction*> Convolution4DExpander::ExpandInstruction(
HloInstruction* instruction) {
HloComputation* computation = instruction->parent();
ConvolutionDimensionNumbers dim_nums =
instruction->convolution_dimension_numbers();
ConvolutionDimensionNumbers new_dim_nums = dim_nums;
std::vector<int64_t> removed_input_dimensions;
std::vector<int64_t> removed_kernel_dimensions;
std::vector<int64_t> removed_output_dimensions;
new_dim_nums.clear_input_spatial_dimensions();
new_dim_nums.clear_output_spatial_dimensions();
new_dim_nums.clear_kernel_spatial_dimensions();
Window new_window;
HloInstruction* input = instruction->mutable_operand(0);
for (int64_t i = 0; i < dim_nums.input_spatial_dimensions().size(); ++i) {
int64_t input_spatial_dim = dim_nums.input_spatial_dimensions(i);
int64_t output_spatial_dim = dim_nums.output_spatial_dimensions(i);
int64_t kernel_spatial_dim = dim_nums.kernel_spatial_dimensions(i);
if (input->shape().dimensions(input_spatial_dim) == 1 &&
instruction->window().dimensions(i).padding_low() == 0 &&
instruction->window().dimensions(i).padding_high() == 0) {
removed_input_dimensions.push_back(input_spatial_dim);
removed_output_dimensions.push_back(output_spatial_dim);
removed_kernel_dimensions.push_back(kernel_spatial_dim);
} else {
*new_window.add_dimensions() = instruction->window().dimensions(i);
new_dim_nums.add_input_spatial_dimensions(input_spatial_dim);
new_dim_nums.add_output_spatial_dimensions(output_spatial_dim);
new_dim_nums.add_kernel_spatial_dimensions(kernel_spatial_dim);
}
}
std::sort(removed_input_dimensions.begin(), removed_input_dimensions.end(),
std::greater<>());
std::sort(removed_output_dimensions.begin(), removed_output_dimensions.end(),
std::greater<>());
std::sort(removed_kernel_dimensions.begin(), removed_kernel_dimensions.end(),
std::greater<>());
Shape new_input_shape = input->shape();
for (int64_t dim : removed_input_dimensions) {
new_input_shape.DeleteDimension(dim);
}
HloInstruction* kernel = instruction->mutable_operand(1);
Shape new_kernel_shape = kernel->shape();
for (int64_t dim : removed_kernel_dimensions) {
new_kernel_shape.DeleteDimension(dim);
}
Shape new_output_shape = instruction->shape();
for (int64_t dim : removed_output_dimensions) {
new_output_shape.DeleteDimension(dim);
}
auto compute_new_dimension =
[](const std::vector<int64_t>& removed_dimensions,
int64_t old_dimension) {
int64_t num_smaller = absl::c_count_if(
removed_dimensions, [old_dimension](int64_t removed_dimension) {
return removed_dimension < old_dimension;
});
return old_dimension - num_smaller;
};
new_dim_nums.set_input_batch_dimension(compute_new_dimension(
removed_input_dimensions, new_dim_nums.input_batch_dimension()));
new_dim_nums.set_input_feature_dimension(compute_new_dimension(
removed_input_dimensions, new_dim_nums.input_feature_dimension()));
for (int64_t i = 0; i < new_dim_nums.input_spatial_dimensions().size(); ++i) {
new_dim_nums.set_input_spatial_dimensions(
i, compute_new_dimension(removed_input_dimensions,
new_dim_nums.input_spatial_dimensions(i)));
}
new_dim_nums.set_output_batch_dimension(compute_new_dimension(
removed_output_dimensions, new_dim_nums.output_batch_dimension()));
new_dim_nums.set_output_feature_dimension(compute_new_dimension(
removed_output_dimensions, new_dim_nums.output_feature_dimension()));
for (int64_t i = 0; i < new_dim_nums.output_spatial_dimensions().size();
++i) {
new_dim_nums.set_output_spatial_dimensions(
i, compute_new_dimension(removed_output_dimensions,
new_dim_nums.output_spatial_dimensions(i)));
}
new_dim_nums.set_kernel_input_feature_dimension(
compute_new_dimension(removed_kernel_dimensions,
new_dim_nums.kernel_input_feature_dimension()));
new_dim_nums.set_kernel_output_feature_dimension(
compute_new_dimension(removed_kernel_dimensions,
new_dim_nums.kernel_output_feature_dimension()));
for (int64_t i = 0; i < new_dim_nums.kernel_spatial_dimensions().size();
++i) {
new_dim_nums.set_kernel_spatial_dimensions(
i, compute_new_dimension(removed_kernel_dimensions,
new_dim_nums.kernel_spatial_dimensions(i)));
}
HloInstruction* reshaped_input = computation->AddInstruction(
HloInstruction::CreateReshape(new_input_shape, input));
HloInstruction* reshaped_kernel = computation->AddInstruction(
HloInstruction::CreateReshape(new_kernel_shape, kernel));
instruction->set_convolution_dimension_numbers(new_dim_nums);
instruction->set_window(new_window);
HloInstruction* new_convolution =
computation->AddInstruction(instruction->CloneWithNewOperands(
new_output_shape, {reshaped_input, reshaped_kernel}));
return computation->AddInstruction(
HloInstruction::CreateReshape(instruction->shape(), new_convolution));
}
} | #include "xla/service/convolution_4d_expander.h"
#include <memory>
#include <string>
#include "xla/hlo/ir/hlo_computation.h"
#include "xla/hlo/ir/hlo_instruction.h"
#include "xla/hlo/ir/hlo_opcode.h"
#include "xla/test.h"
#include "xla/tests/hlo_test_base.h"
#include "xla/types.h"
namespace xla {
namespace {
using Convolution4DExpanderTest = HloTestBase;
TEST_F(Convolution4DExpanderTest, ConvertTo2DConvolution) {
std::string hlo_string = R"(HloModule convolution_4d_fp32
ENTRY convolution_computation {
input = f32[1,10,1,10,5,20]{5,4,3,2,1,0} parameter(0)
kernel = f32[20,1,2,1,4,15]{5,4,3,2,1,0} parameter(1)
ROOT conv = f32[15,1,9,1,7,5]{5,4,3,2,1,0} convolution(input, kernel), dim_labels=0123bf_i0123o->f0123b, window={size=1x2x1x4}
})";
TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> module,
ParseAndReturnVerifiedModule(hlo_string));
auto computation = module->entry_computation();
HloInstruction* root = computation->root_instruction();
EXPECT_EQ(root->opcode(), HloOpcode::kConvolution);
EXPECT_EQ(root->window().dimensions_size(), 4);
Convolution4DExpander expander_pass;
ASSERT_TRUE(expander_pass.Run(module.get()).value());
root = computation->root_instruction();
EXPECT_EQ(root->opcode(), HloOpcode::kReshape);
const HloInstruction* new_convolution = root->operand(0);
EXPECT_EQ(new_convolution->opcode(), HloOpcode::kConvolution);
EXPECT_EQ(new_convolution->window().dimensions_size(), 2);
}
TEST_F(Convolution4DExpanderTest, ConvertTo3DConvolution) {
std::string hlo_string = R"(HloModule convolution_4d_fp32
ENTRY convolution_computation {
input = f32[1,10,1,10,5,20]{5,4,3,2,1,0} parameter(0)
kernel = f32[20,1,2,1,4,15]{5,4,3,2,1,0} parameter(1)
ROOT conv = f32[15,1,9,2,7,5]{5,4,3,2,1,0} convolution(input, kernel), dim_labels=0123bf_i0123o->f0123b, window={size=1x2x1x4 pad=0_0x0_0x1_0x0_0}
})";
TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> module,
ParseAndReturnVerifiedModule(hlo_string));
auto computation = module->entry_computation();
HloInstruction* root = computation->root_instruction();
EXPECT_EQ(root->opcode(), HloOpcode::kConvolution);
EXPECT_EQ(root->window().dimensions_size(), 4);
Convolution4DExpander expander_pass;
ASSERT_TRUE(expander_pass.Run(module.get()).value());
root = computation->root_instruction();
EXPECT_EQ(root->opcode(), HloOpcode::kReshape);
const HloInstruction* new_convolution = root->operand(0);
EXPECT_EQ(new_convolution->opcode(), HloOpcode::kConvolution);
EXPECT_EQ(new_convolution->window().dimensions_size(), 3);
}
TEST_F(Convolution4DExpanderTest, ConvertTo0DConvolution) {
std::string hlo_string = R"(HloModule convolution_4d_fp32
ENTRY convolution_computation {
input = f32[1,1,1,1,5,20]{5,4,3,2,1,0} parameter(0)
kernel = f32[20,1,1,1,1,15]{5,4,3,2,1,0} parameter(1)
ROOT conv = f32[15,1,1,1,1,5]{5,4,3,2,1,0} convolution(input, kernel), dim_labels=0123bf_i0123o->f0123b, window={size=1x1x1x1}
})";
TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> module,
ParseAndReturnVerifiedModule(hlo_string));
auto computation = module->entry_computation();
HloInstruction* root = computation->root_instruction();
EXPECT_EQ(root->opcode(), HloOpcode::kConvolution);
EXPECT_EQ(root->window().dimensions_size(), 4);
Convolution4DExpander expander_pass;
ASSERT_TRUE(expander_pass.Run(module.get()).value());
root = computation->root_instruction();
EXPECT_EQ(root->opcode(), HloOpcode::kReshape);
const HloInstruction* new_convolution = root->operand(0);
EXPECT_EQ(new_convolution->opcode(), HloOpcode::kConvolution);
EXPECT_EQ(new_convolution->window().dimensions_size(), 0);
}
TEST_F(Convolution4DExpanderTest, DontConvert3DConvolution) {
std::string hlo_string = R"(HloModule convolution_4d_fp32
ENTRY convolution_computation {
input = f32[1,1,1,5,20]{4,3,2,1,0} parameter(0)
kernel = f32[20,1,1,1,15]{4,3,2,1,0} parameter(1)
ROOT conv = f32[15,1,1,1,5]{4,3,2,1,0} convolution(input, kernel), dim_labels=012bf_i012o->f012b, window={size=1x1x1}
})";
TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> module,
ParseAndReturnVerifiedModule(hlo_string));
auto computation = module->entry_computation();
HloInstruction* root = computation->root_instruction();
EXPECT_EQ(root->opcode(), HloOpcode::kConvolution);
EXPECT_EQ(root->window().dimensions_size(), 3);
Convolution4DExpander expander_pass;
ASSERT_FALSE(expander_pass.Run(module.get()).value());
}
TEST_F(Convolution4DExpanderTest, DontConvertIfNoTrivialDimensionAvailable) {
std::string hlo_string = R"(HloModule convolution_4d_fp32
ENTRY convolution_computation {
input = f32[2,10,2,10,5,20]{5,4,3,2,1,0} parameter(0)
kernel = f32[20,2,2,2,4,15]{5,4,3,2,1,0} parameter(1)
ROOT conv = f32[15,1,9,1,7,5]{5,4,3,2,1,0} convolution(input, kernel), dim_labels=0123bf_i0123o->f0123b, window={size=2x2x2x4}
})";
TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> module,
ParseAndReturnVerifiedModule(hlo_string));
auto computation = module->entry_computation();
HloInstruction* root = computation->root_instruction();
EXPECT_EQ(root->opcode(), HloOpcode::kConvolution);
EXPECT_EQ(root->window().dimensions_size(), 4);
Convolution4DExpander expander_pass;
ASSERT_FALSE(expander_pass.Run(module.get()).value());
}
TEST_F(Convolution4DExpanderTest, DontConvertIfPaddingIsNonzero) {
std::string hlo_string = R"(HloModule convolution_4d_fp32
ENTRY convolution_computation {
input = f32[1,10,1,10,5,20]{5,4,3,2,1,0} parameter(0)
kernel = f32[20,1,2,1,4,15]{5,4,3,2,1,0} parameter(1)
ROOT conv = f32[15,1,9,1,7,5]{5,4,3,2,1,0} convolution(input, kernel), dim_labels=0123bf_i0123o->f0123b, window={size=1x2x1x4 stride=2x1x2x1 pad=1_0x0_0x0_1x0_0}
})";
TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> module,
ParseAndReturnVerifiedModule(hlo_string));
auto computation = module->entry_computation();
HloInstruction* root = computation->root_instruction();
EXPECT_EQ(root->opcode(), HloOpcode::kConvolution);
EXPECT_EQ(root->window().dimensions_size(), 4);
Convolution4DExpander expander_pass;
ASSERT_FALSE(expander_pass.Run(module.get()).value());
}
}
} |
315 | #ifndef QUICHE_OBLIVIOUS_HTTP_BUFFERS_OBLIVIOUS_HTTP_RESPONSE_H_
#define QUICHE_OBLIVIOUS_HTTP_BUFFERS_OBLIVIOUS_HTTP_RESPONSE_H_
#include <stddef.h>
#include <string>
#include "absl/status/statusor.h"
#include "absl/strings/string_view.h"
#include "quiche/common/quiche_random.h"
#include "quiche/oblivious_http/buffers/oblivious_http_request.h"
#include "quiche/oblivious_http/common/oblivious_http_header_key_config.h"
namespace quiche {
class QUICHE_EXPORT ObliviousHttpResponse {
public:
static absl::StatusOr<ObliviousHttpResponse> CreateClientObliviousResponse(
std::string encrypted_data,
ObliviousHttpRequest::Context& oblivious_http_request_context,
absl::string_view resp_label =
ObliviousHttpHeaderKeyConfig::kOhttpResponseLabel);
static absl::StatusOr<ObliviousHttpResponse> CreateServerObliviousResponse(
std::string plaintext_payload,
ObliviousHttpRequest::Context& oblivious_http_request_context,
absl::string_view resp_label =
ObliviousHttpHeaderKeyConfig::kOhttpResponseLabel,
QuicheRandom* quiche_random = nullptr);
ObliviousHttpResponse(const ObliviousHttpResponse& other) = default;
ObliviousHttpResponse& operator=(const ObliviousHttpResponse& other) =
default;
ObliviousHttpResponse(ObliviousHttpResponse&& other) = default;
ObliviousHttpResponse& operator=(ObliviousHttpResponse&& other) = default;
~ObliviousHttpResponse() = default;
const std::string& EncapsulateAndSerialize() const;
const std::string& GetPlaintextData() const;
std::string ConsumePlaintextData() && {
return std::move(response_plaintext_);
}
private:
struct CommonAeadParamsResult {
const EVP_AEAD* evp_hpke_aead;
const size_t aead_key_len;
const size_t aead_nonce_len;
const size_t secret_len;
};
struct CommonOperationsResult {
bssl::UniquePtr<EVP_AEAD_CTX> aead_ctx;
const std::string aead_nonce;
};
explicit ObliviousHttpResponse(std::string encrypted_data,
std::string resp_plaintext);
static absl::StatusOr<CommonAeadParamsResult> GetCommonAeadParams(
ObliviousHttpRequest::Context& oblivious_http_request_context);
static absl::StatusOr<CommonOperationsResult> CommonOperationsToEncapDecap(
absl::string_view response_nonce,
ObliviousHttpRequest::Context& oblivious_http_request_context,
absl::string_view resp_label, const size_t aead_key_len,
const size_t aead_nonce_len, const size_t secret_len);
std::string encrypted_data_;
std::string response_plaintext_;
};
}
#endif
#include "quiche/oblivious_http/buffers/oblivious_http_response.h"
#include <stddef.h>
#include <stdint.h>
#include <algorithm>
#include <memory>
#include <string>
#include <utility>
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/string_view.h"
#include "openssl/aead.h"
#include "openssl/hkdf.h"
#include "openssl/hpke.h"
#include "quiche/common/platform/api/quiche_bug_tracker.h"
#include "quiche/common/quiche_crypto_logging.h"
#include "quiche/common/quiche_random.h"
#include "quiche/oblivious_http/common/oblivious_http_header_key_config.h"
namespace quiche {
namespace {
void random(QuicheRandom* quiche_random, char* dest, size_t len) {
if (quiche_random == nullptr) {
quiche_random = QuicheRandom::GetInstance();
}
quiche_random->RandBytes(dest, len);
}
}
ObliviousHttpResponse::ObliviousHttpResponse(std::string encrypted_data,
std::string resp_plaintext)
: encrypted_data_(std::move(encrypted_data)),
response_plaintext_(std::move(resp_plaintext)) {}
absl::StatusOr<ObliviousHttpResponse>
ObliviousHttpResponse::CreateClientObliviousResponse(
std::string encrypted_data,
ObliviousHttpRequest::Context& oblivious_http_request_context,
absl::string_view resp_label) {
if (oblivious_http_request_context.hpke_context_ == nullptr) {
return absl::FailedPreconditionError(
"HPKE context wasn't initialized before proceeding with this Response "
"Decapsulation on Client-side.");
}
size_t expected_key_len = EVP_HPKE_KEM_enc_len(
EVP_HPKE_CTX_kem(oblivious_http_request_context.hpke_context_.get()));
if (oblivious_http_request_context.encapsulated_key_.size() !=
expected_key_len) {
return absl::InvalidArgumentError(absl::StrCat(
"Invalid len for encapsulated_key arg. Expected:", expected_key_len,
" Actual:", oblivious_http_request_context.encapsulated_key_.size()));
}
if (encrypted_data.empty()) {
return absl::InvalidArgumentError("Empty encrypted_data input param.");
}
absl::StatusOr<CommonAeadParamsResult> aead_params_st =
GetCommonAeadParams(oblivious_http_request_context);
if (!aead_params_st.ok()) {
return aead_params_st.status();
}
size_t secret_len = aead_params_st.value().secret_len;
if (encrypted_data.size() < secret_len) {
return absl::InvalidArgumentError(
absl::StrCat("Invalid input response. Failed to parse required minimum "
"expected_len=",
secret_len, " bytes."));
}
absl::string_view response_nonce =
absl::string_view(encrypted_data).substr(0, secret_len);
absl::string_view encrypted_response =
absl::string_view(encrypted_data).substr(secret_len);
auto common_ops_st = CommonOperationsToEncapDecap(
response_nonce, oblivious_http_request_context, resp_label,
aead_params_st.value().aead_key_len,
aead_params_st.value().aead_nonce_len, aead_params_st.value().secret_len);
if (!common_ops_st.ok()) {
return common_ops_st.status();
}
std::string decrypted(encrypted_response.size(), '\0');
size_t decrypted_len;
if (!EVP_AEAD_CTX_open(
common_ops_st.value().aead_ctx.get(),
reinterpret_cast<uint8_t*>(decrypted.data()), &decrypted_len,
decrypted.size(),
reinterpret_cast<const uint8_t*>(
common_ops_st.value().aead_nonce.data()),
aead_params_st.value().aead_nonce_len,
reinterpret_cast<const uint8_t*>(encrypted_response.data()),
encrypted_response.size(), nullptr, 0)) {
return SslErrorAsStatus(
"Failed to decrypt the response with derived AEAD key and nonce.");
}
decrypted.resize(decrypted_len);
ObliviousHttpResponse oblivious_response(std::move(encrypted_data),
std::move(decrypted));
return oblivious_response;
}
absl::StatusOr<ObliviousHttpResponse>
ObliviousHttpResponse::CreateServerObliviousResponse(
std::string plaintext_payload,
ObliviousHttpRequest::Context& oblivious_http_request_context,
absl::string_view response_label, QuicheRandom* quiche_random) {
if (oblivious_http_request_context.hpke_context_ == nullptr) {
return absl::FailedPreconditionError(
"HPKE context wasn't initialized before proceeding with this Response "
"Encapsulation on Server-side.");
}
size_t expected_key_len = EVP_HPKE_KEM_enc_len(
EVP_HPKE_CTX_kem(oblivious_http_request_context.hpke_context_.get()));
if (oblivious_http_request_context.encapsulated_key_.size() !=
expected_key_len) {
return absl::InvalidArgumentError(absl::StrCat(
"Invalid len for encapsulated_key arg. Expected:", expected_key_len,
" Actual:", oblivious_http_request_context.encapsulated_key_.size()));
}
if (plaintext_payload.empty()) {
return absl::InvalidArgumentError("Empty plaintext_payload input param.");
}
absl::StatusOr<CommonAeadParamsResult> aead_params_st =
GetCommonAeadParams(oblivious_http_request_context);
if (!aead_params_st.ok()) {
return aead_params_st.status();
}
const size_t nonce_size = aead_params_st->secret_len;
const size_t max_encrypted_data_size =
nonce_size + plaintext_payload.size() +
EVP_AEAD_max_overhead(EVP_HPKE_AEAD_aead(EVP_HPKE_CTX_aead(
oblivious_http_request_context.hpke_context_.get())));
std::string encrypted_data(max_encrypted_data_size, '\0');
random(quiche_random, encrypted_data.data(), nonce_size);
absl::string_view response_nonce =
absl::string_view(encrypted_data).substr(0, nonce_size);
auto common_ops_st = CommonOperationsToEncapDecap(
response_nonce, oblivious_http_request_context, response_label,
aead_params_st.value().aead_key_len,
aead_params_st.value().aead_nonce_len, aead_params_st.value().secret_len);
if (!common_ops_st.ok()) {
return common_ops_st.status();
}
size_t ciphertext_len;
if (!EVP_AEAD_CTX_seal(
common_ops_st.value().aead_ctx.get(),
reinterpret_cast<uint8_t*>(encrypted_data.data() + nonce_size),
&ciphertext_len, encrypted_data.size() - nonce_size,
reinterpret_cast<const uint8_t*>(
common_ops_st.value().aead_nonce.data()),
aead_params_st.value().aead_nonce_len,
reinterpret_cast<const uint8_t*>(plaintext_payload.data()),
plaintext_payload.size(), nullptr, 0)) {
return SslErrorAsStatus(
"Failed to encrypt the payload with derived AEAD key.");
}
encrypted_data.resize(nonce_size + ciphertext_len);
if (nonce_size == 0 || ciphertext_len == 0) {
return absl::InternalError(absl::StrCat(
"ObliviousHttpResponse Object wasn't initialized with required fields.",
(nonce_size == 0 ? "Generated nonce is empty." : ""),
(ciphertext_len == 0 ? "Generated Encrypted payload is empty." : "")));
}
ObliviousHttpResponse oblivious_response(std::move(encrypted_data),
std::move(plaintext_payload));
return oblivious_response;
}
const std::string& ObliviousHttpResponse::EncapsulateAndSerialize() const {
return encrypted_data_;
}
const std::string& ObliviousHttpResponse::GetPlaintextData() const {
return response_plaintext_;
}
absl::StatusOr<ObliviousHttpResponse::CommonAeadParamsResult>
ObliviousHttpResponse::GetCommonAeadParams(
ObliviousHttpRequest::Context& oblivious_http_request_context) {
const EVP_AEAD* evp_hpke_aead = EVP_HPKE_AEAD_aead(
EVP_HPKE_CTX_aead(oblivious_http_request_context.hpke_context_.get()));
if (evp_hpke_aead == nullptr) {
return absl::FailedPreconditionError(
"Key Configuration not supported by HPKE AEADs. Check your key "
"config.");
}
const size_t aead_key_len = EVP_AEAD_key_length(evp_hpke_aead);
const size_t aead_nonce_len = EVP_AEAD_nonce_length(evp_hpke_aead);
const size_t secret_len = std::max(aead_key_len, aead_nonce_len);
CommonAeadParamsResult result{evp_hpke_aead, aead_key_len, aead_nonce_len,
secret_len};
return result;
}
absl::StatusOr<ObliviousHttpResponse::CommonOperationsResult>
ObliviousHttpResponse::CommonOperationsToEncapDecap(
absl::string_view response_nonce,
ObliviousHttpRequest::Context& oblivious_http_request_context,
absl::string_view resp_label, const size_t aead_key_len,
const size_t aead_nonce_len, const size_t secret_len) {
if (response_nonce.empty()) {
return absl::InvalidArgumentError("Invalid input params.");
}
std::string secret(secret_len, '\0');
if (!EVP_HPKE_CTX_export(oblivious_http_request_context.hpke_context_.get(),
reinterpret_cast<uint8_t*>(secret.data()),
secret.size(),
reinterpret_cast<const uint8_t*>(resp_label.data()),
resp_label.size())) {
return SslErrorAsStatus("Failed to export secret.");
}
std::string salt = absl::StrCat(
oblivious_http_request_context.encapsulated_key_, response_nonce);
std::string pseudorandom_key(EVP_MAX_MD_SIZE, '\0');
size_t prk_len;
auto evp_md = EVP_HPKE_KDF_hkdf_md(
EVP_HPKE_CTX_kdf(oblivious_http_request_context.hpke_context_.get()));
if (evp_md == nullptr) {
QUICHE_BUG(Invalid Key Configuration
: Unsupported BoringSSL HPKE KDFs)
<< "Update KeyConfig to support only BoringSSL HKDFs.";
return absl::FailedPreconditionError(
"Key Configuration not supported by BoringSSL HPKE KDFs. Check your "
"Key "
"Config.");
}
if (!HKDF_extract(
reinterpret_cast<uint8_t*>(pseudorandom_key.data()), &prk_len, evp_md,
reinterpret_cast<const uint8_t*>(secret.data()), secret_len,
reinterpret_cast<const uint8_t*>(salt.data()), salt.size())) {
return SslErrorAsStatus(
"Failed to derive pesudorandom key from salt and secret.");
}
pseudorandom_key.resize(prk_len);
std::string aead_key(aead_key_len, '\0');
absl::string_view hkdf_info = ObliviousHttpHeaderKeyConfig::kKeyHkdfInfo;
if (!HKDF_expand(reinterpret_cast<uint8_t*>(aead_key.data()), aead_key_len,
evp_md,
reinterpret_cast<const uint8_t*>(pseudorandom_key.data()),
prk_len, reinterpret_cast<const uint8_t*>(hkdf_info.data()),
hkdf_info.size())) {
return SslErrorAsStatus(
"Failed to expand AEAD key using pseudorandom key(prk).");
}
std::string aead_nonce(aead_nonce_len, '\0');
hkdf_info = ObliviousHttpHeaderKeyConfig::kNonceHkdfInfo;
if (!HKDF_expand(reinterpret_cast<uint8_t*>(aead_nonce.data()),
aead_nonce_len, evp_md,
reinterpret_cast<const uint8_t*>(pseudorandom_key.data()),
prk_len, reinterpret_cast<const uint8_t*>(hkdf_info.data()),
hkdf_info.size())) {
return SslErrorAsStatus(
"Failed to expand AEAD nonce using pseudorandom key(prk).");
}
const EVP_AEAD* evp_hpke_aead = EVP_HPKE_AEAD_aead(
EVP_HPKE_CTX_aead(oblivious_http_request_context.hpke_context_.get()));
if (evp_hpke_aead == nullptr) {
return absl::FailedPreconditionError(
"Key Configuration not supported by HPKE AEADs. Check your key "
"config.");
}
bssl::UniquePtr<EVP_AEAD_CTX> aead_ctx(EVP_AEAD_CTX_new(
evp_hpke_aead, reinterpret_cast<const uint8_t*>(aead_key.data()),
aead_key.size(), 0));
if (aead_ctx == nullptr) {
return SslErrorAsStatus("Failed to initialize AEAD context.");
}
if (!EVP_AEAD_CTX_init(aead_ctx.get(), evp_hpke_aead,
reinterpret_cast<const uint8_t*>(aead_key.data()),
aead_key.size(), 0, nullptr)) {
return SslErrorAsStatus(
"Failed to initialize AEAD context with derived key.");
}
CommonOperationsResult result{std::move(aead_ctx), std::move(aead_nonce)};
return result;
}
} | #include "quiche/oblivious_http/buffers/oblivious_http_response.h"
#include <stddef.h>
#include <stdint.h>
#include <string.h>
#include <algorithm>
#include <memory>
#include <string>
#include <utility>
#include "absl/status/statusor.h"
#include "absl/strings/escaping.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/string_view.h"
#include "openssl/hpke.h"
#include "quiche/common/platform/api/quiche_test.h"
#include "quiche/oblivious_http/buffers/oblivious_http_request.h"
#include "quiche/oblivious_http/common/oblivious_http_header_key_config.h"
namespace quiche {
namespace {
std::string GetHpkePrivateKey() {
absl::string_view hpke_key_hex =
"b77431ecfa8f4cfc30d6e467aafa06944dffe28cb9dd1409e33a3045f5adc8a1";
std::string hpke_key_bytes;
EXPECT_TRUE(absl::HexStringToBytes(hpke_key_hex, &hpke_key_bytes));
return hpke_key_bytes;
}
std::string GetHpkePublicKey() {
absl::string_view public_key =
"6d21cfe09fbea5122f9ebc2eb2a69fcc4f06408cd54aac934f012e76fcdcef62";
std::string public_key_bytes;
EXPECT_TRUE(absl::HexStringToBytes(public_key, &public_key_bytes));
return public_key_bytes;
}
std::string GetSeed() {
absl::string_view seed =
"52c4a758a802cd8b936eceea314432798d5baf2d7e9235dc084ab1b9cfa2f736";
std::string seed_bytes;
EXPECT_TRUE(absl::HexStringToBytes(seed, &seed_bytes));
return seed_bytes;
}
std::string GetSeededEncapsulatedKey() {
absl::string_view encapsulated_key =
"37fda3567bdbd628e88668c3c8d7e97d1d1253b6d4ea6d44c150f741f1bf4431";
std::string encapsulated_key_bytes;
EXPECT_TRUE(
absl::HexStringToBytes(encapsulated_key, &encapsulated_key_bytes));
return encapsulated_key_bytes;
}
const ObliviousHttpHeaderKeyConfig GetOhttpKeyConfig(uint8_t key_id,
uint16_t kem_id,
uint16_t kdf_id,
uint16_t aead_id) {
auto ohttp_key_config =
ObliviousHttpHeaderKeyConfig::Create(key_id, kem_id, kdf_id, aead_id);
EXPECT_TRUE(ohttp_key_config.ok());
return ohttp_key_config.value();
}
bssl::UniquePtr<EVP_HPKE_CTX> GetSeededClientContext(uint8_t key_id,
uint16_t kem_id,
uint16_t kdf_id,
uint16_t aead_id) {
bssl::UniquePtr<EVP_HPKE_CTX> client_ctx(EVP_HPKE_CTX_new());
std::string encapsulated_key(EVP_HPKE_MAX_ENC_LENGTH, '\0');
size_t enc_len;
std::string info = GetOhttpKeyConfig(key_id, kem_id, kdf_id, aead_id)
.SerializeRecipientContextInfo();
EXPECT_TRUE(EVP_HPKE_CTX_setup_sender_with_seed_for_testing(
client_ctx.get(), reinterpret_cast<uint8_t *>(encapsulated_key.data()),
&enc_len, encapsulated_key.size(), EVP_hpke_x25519_hkdf_sha256(),
EVP_hpke_hkdf_sha256(), EVP_hpke_aes_256_gcm(),
reinterpret_cast<const uint8_t *>(GetHpkePublicKey().data()),
GetHpkePublicKey().size(), reinterpret_cast<const uint8_t *>(info.data()),
info.size(), reinterpret_cast<const uint8_t *>(GetSeed().data()),
GetSeed().size()));
encapsulated_key.resize(enc_len);
EXPECT_EQ(encapsulated_key, GetSeededEncapsulatedKey());
return client_ctx;
}
bssl::UniquePtr<EVP_HPKE_KEY> ConstructHpkeKey(
absl::string_view hpke_key,
const ObliviousHttpHeaderKeyConfig &ohttp_key_config) {
bssl::UniquePtr<EVP_HPKE_KEY> bssl_hpke_key(EVP_HPKE_KEY_new());
EXPECT_NE(bssl_hpke_key, nullptr);
EXPECT_TRUE(EVP_HPKE_KEY_init(
bssl_hpke_key.get(), ohttp_key_config.GetHpkeKem(),
reinterpret_cast<const uint8_t *>(hpke_key.data()), hpke_key.size()));
return bssl_hpke_key;
}
ObliviousHttpRequest SetUpObliviousHttpContext(uint8_t key_id, uint16_t kem_id,
uint16_t kdf_id,
uint16_t aead_id,
std::string plaintext) {
auto ohttp_key_config = GetOhttpKeyConfig(key_id, kem_id, kdf_id, aead_id);
auto client_request_encapsulate =
ObliviousHttpRequest::CreateClientWithSeedForTesting(
std::move(plaintext), GetHpkePublicKey(), ohttp_key_config,
GetSeed());
EXPECT_TRUE(client_request_encapsulate.ok());
auto oblivious_request =
client_request_encapsulate->EncapsulateAndSerialize();
auto server_request_decapsulate =
ObliviousHttpRequest::CreateServerObliviousRequest(
oblivious_request,
*(ConstructHpkeKey(GetHpkePrivateKey(), ohttp_key_config)),
ohttp_key_config);
EXPECT_TRUE(server_request_decapsulate.ok());
return std::move(server_request_decapsulate.value());
}
class TestQuicheRandom : public QuicheRandom {
public:
TestQuicheRandom(char seed) : seed_(seed) {}
~TestQuicheRandom() override {}
void RandBytes(void *data, size_t len) override { memset(data, seed_, len); }
uint64_t RandUint64() override {
uint64_t random_int;
memset(&random_int, seed_, sizeof(random_int));
return random_int;
}
void InsecureRandBytes(void *data, size_t len) override {
return RandBytes(data, len);
}
uint64_t InsecureRandUint64() override { return RandUint64(); }
private:
char seed_;
};
size_t GetResponseNonceLength(const EVP_HPKE_CTX &hpke_context) {
EXPECT_NE(&hpke_context, nullptr);
const EVP_AEAD *evp_hpke_aead =
EVP_HPKE_AEAD_aead(EVP_HPKE_CTX_aead(&hpke_context));
EXPECT_NE(evp_hpke_aead, nullptr);
const size_t aead_key_len = EVP_AEAD_key_length(evp_hpke_aead);
const size_t aead_nonce_len = EVP_AEAD_nonce_length(evp_hpke_aead);
const size_t secret_len = std::max(aead_key_len, aead_nonce_len);
return secret_len;
}
TEST(ObliviousHttpResponse, TestDecapsulateReceivedResponse) {
absl::string_view encrypted_response =
"39d5b03c02c97e216df444e4681007105974d4df1585aae05e7b53f3ccdb55d51f711d48"
"eeefbc1a555d6d928e35df33fd23c23846fa7b083e30692f7b";
std::string encrypted_response_bytes;
ASSERT_TRUE(
absl::HexStringToBytes(encrypted_response, &encrypted_response_bytes));
auto oblivious_context =
SetUpObliviousHttpContext(4, EVP_HPKE_DHKEM_X25519_HKDF_SHA256,
EVP_HPKE_HKDF_SHA256, EVP_HPKE_AES_256_GCM,
"test")
.ReleaseContext();
auto decapsulated = ObliviousHttpResponse::CreateClientObliviousResponse(
std::move(encrypted_response_bytes), oblivious_context);
EXPECT_TRUE(decapsulated.ok());
auto decrypted = decapsulated->GetPlaintextData();
EXPECT_EQ(decrypted, "test response");
}
}
TEST(ObliviousHttpResponse, EndToEndTestForResponse) {
auto oblivious_ctx = ObliviousHttpRequest::Context(
GetSeededClientContext(5, EVP_HPKE_DHKEM_X25519_HKDF_SHA256,
EVP_HPKE_HKDF_SHA256, EVP_HPKE_AES_256_GCM),
GetSeededEncapsulatedKey());
auto server_response_encapsulate =
ObliviousHttpResponse::CreateServerObliviousResponse("test response",
oblivious_ctx);
EXPECT_TRUE(server_response_encapsulate.ok());
auto oblivious_response =
server_response_encapsulate->EncapsulateAndSerialize();
auto client_response_encapsulate =
ObliviousHttpResponse::CreateClientObliviousResponse(oblivious_response,
oblivious_ctx);
auto decrypted = client_response_encapsulate->GetPlaintextData();
EXPECT_EQ(decrypted, "test response");
}
TEST(ObliviousHttpResponse, TestEncapsulateWithQuicheRandom) {
auto random = TestQuicheRandom('z');
auto server_seeded_request = SetUpObliviousHttpContext(
6, EVP_HPKE_DHKEM_X25519_HKDF_SHA256, EVP_HPKE_HKDF_SHA256,
EVP_HPKE_AES_256_GCM, "test");
auto server_request_context =
std::move(server_seeded_request).ReleaseContext();
auto server_response_encapsulate =
ObliviousHttpResponse::CreateServerObliviousResponse(
"test response", server_request_context,
ObliviousHttpHeaderKeyConfig::kOhttpResponseLabel, &random);
EXPECT_TRUE(server_response_encapsulate.ok());
std::string response_nonce =
server_response_encapsulate->EncapsulateAndSerialize().substr(
0, GetResponseNonceLength(*(server_request_context.hpke_context_)));
EXPECT_EQ(response_nonce,
std::string(
GetResponseNonceLength(*(server_request_context.hpke_context_)),
'z'));
absl::string_view expected_encrypted_response =
"2a3271ac4e6a501f51d0264d3dd7d0bc8a06973b58e89c26d6dac06144";
std::string expected_encrypted_response_bytes;
ASSERT_TRUE(absl::HexStringToBytes(expected_encrypted_response,
&expected_encrypted_response_bytes));
EXPECT_EQ(
server_response_encapsulate->EncapsulateAndSerialize().substr(
GetResponseNonceLength(*(server_request_context.hpke_context_))),
expected_encrypted_response_bytes);
}
} |
316 | #ifndef QUICHE_QUIC_CORE_QPACK_QPACK_RECEIVE_STREAM_H_
#define QUICHE_QUIC_CORE_QPACK_QPACK_RECEIVE_STREAM_H_
#include "quiche/quic/core/qpack/qpack_stream_receiver.h"
#include "quiche/quic/core/quic_stream.h"
#include "quiche/quic/platform/api/quic_export.h"
namespace quic {
class QuicSession;
class QUICHE_EXPORT QpackReceiveStream : public QuicStream {
public:
QpackReceiveStream(PendingStream* pending, QuicSession* session,
QpackStreamReceiver* receiver);
QpackReceiveStream(const QpackReceiveStream&) = delete;
QpackReceiveStream& operator=(const QpackReceiveStream&) = delete;
~QpackReceiveStream() override = default;
void OnStreamReset(const QuicRstStreamFrame& frame) override;
void OnDataAvailable() override;
QuicStreamOffset NumBytesConsumed() const {
return sequencer()->NumBytesConsumed();
}
private:
QpackStreamReceiver* receiver_;
};
}
#endif
#include "quiche/quic/core/qpack/qpack_receive_stream.h"
#include "absl/strings/string_view.h"
#include "quiche/quic/core/quic_session.h"
namespace quic {
QpackReceiveStream::QpackReceiveStream(PendingStream* pending,
QuicSession* session,
QpackStreamReceiver* receiver)
: QuicStream(pending, session, true), receiver_(receiver) {}
void QpackReceiveStream::OnStreamReset(const QuicRstStreamFrame& ) {
stream_delegate()->OnStreamError(
QUIC_HTTP_CLOSED_CRITICAL_STREAM,
"RESET_STREAM received for QPACK receive stream");
}
void QpackReceiveStream::OnDataAvailable() {
iovec iov;
while (!reading_stopped() && sequencer()->GetReadableRegion(&iov)) {
QUICHE_DCHECK(!sequencer()->IsClosed());
receiver_->Decode(absl::string_view(
reinterpret_cast<const char*>(iov.iov_base), iov.iov_len));
sequencer()->MarkConsumed(iov.iov_len);
}
}
} | #include "quiche/quic/core/qpack/qpack_receive_stream.h"
#include <vector>
#include "absl/strings/string_view.h"
#include "quiche/quic/core/quic_utils.h"
#include "quiche/quic/platform/api/quic_test.h"
#include "quiche/quic/test_tools/quic_spdy_session_peer.h"
#include "quiche/quic/test_tools/quic_test_utils.h"
namespace quic {
namespace test {
namespace {
using ::testing::_;
using ::testing::AnyNumber;
using ::testing::StrictMock;
struct TestParams {
TestParams(const ParsedQuicVersion& version, Perspective perspective)
: version(version), perspective(perspective) {
QUIC_LOG(INFO) << "TestParams: version: "
<< ParsedQuicVersionToString(version)
<< ", perspective: " << perspective;
}
TestParams(const TestParams& other)
: version(other.version), perspective(other.perspective) {}
ParsedQuicVersion version;
Perspective perspective;
};
std::vector<TestParams> GetTestParams() {
std::vector<TestParams> params;
ParsedQuicVersionVector all_supported_versions = AllSupportedVersions();
for (const auto& version : AllSupportedVersions()) {
if (!VersionUsesHttp3(version.transport_version)) {
continue;
}
for (Perspective p : {Perspective::IS_SERVER, Perspective::IS_CLIENT}) {
params.emplace_back(version, p);
}
}
return params;
}
class QpackReceiveStreamTest : public QuicTestWithParam<TestParams> {
public:
QpackReceiveStreamTest()
: connection_(new StrictMock<MockQuicConnection>(
&helper_, &alarm_factory_, perspective(),
SupportedVersions(GetParam().version))),
session_(connection_) {
EXPECT_CALL(session_, OnCongestionWindowChange(_)).Times(AnyNumber());
session_.Initialize();
EXPECT_CALL(
static_cast<const MockQuicCryptoStream&>(*session_.GetCryptoStream()),
encryption_established())
.WillRepeatedly(testing::Return(true));
QuicStreamId id = perspective() == Perspective::IS_SERVER
? GetNthClientInitiatedUnidirectionalStreamId(
session_.transport_version(), 3)
: GetNthServerInitiatedUnidirectionalStreamId(
session_.transport_version(), 3);
char type[] = {0x03};
QuicStreamFrame data1(id, false, 0, absl::string_view(type, 1));
session_.OnStreamFrame(data1);
qpack_receive_stream_ =
QuicSpdySessionPeer::GetQpackDecoderReceiveStream(&session_);
}
Perspective perspective() const { return GetParam().perspective; }
MockQuicConnectionHelper helper_;
MockAlarmFactory alarm_factory_;
StrictMock<MockQuicConnection>* connection_;
StrictMock<MockQuicSpdySession> session_;
QpackReceiveStream* qpack_receive_stream_;
};
INSTANTIATE_TEST_SUITE_P(Tests, QpackReceiveStreamTest,
::testing::ValuesIn(GetTestParams()));
TEST_P(QpackReceiveStreamTest, ResetQpackReceiveStream) {
EXPECT_TRUE(qpack_receive_stream_->is_static());
QuicRstStreamFrame rst_frame(kInvalidControlFrameId,
qpack_receive_stream_->id(),
QUIC_STREAM_CANCELLED, 1234);
EXPECT_CALL(*connection_,
CloseConnection(QUIC_HTTP_CLOSED_CRITICAL_STREAM, _, _));
qpack_receive_stream_->OnStreamReset(rst_frame);
}
}
}
} |
317 | #ifndef ABSL_BASE_INTERNAL_POISON_H_
#define ABSL_BASE_INTERNAL_POISON_H_
#include <atomic>
#include "absl/base/config.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace base_internal {
extern std::atomic<void*> poison_data;
inline void* get_poisoned_pointer() {
return poison_data.load(std::memory_order_relaxed);
}
}
ABSL_NAMESPACE_END
}
#endif
#include "absl/base/internal/poison.h"
#include <atomic>
#include <cstdint>
#include <cstdlib>
#include "absl/base/attributes.h"
#include "absl/base/config.h"
#if defined(ABSL_HAVE_ADDRESS_SANITIZER)
#include <sanitizer/asan_interface.h>
#elif defined(ABSL_HAVE_MEMORY_SANITIZER)
#include <sanitizer/msan_interface.h>
#elif defined(ABSL_HAVE_MMAP) && !defined(SGX_SIM)
#include <sys/mman.h>
#elif defined(_MSC_VER)
#include <windows.h>
#endif
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace base_internal {
namespace {
constexpr size_t kPageSize = 1 << 12;
alignas(kPageSize) static char poison_page[kPageSize];
}
std::atomic<void*> poison_data = {&poison_page};
namespace {
#if defined(ABSL_HAVE_ADDRESS_SANITIZER)
void PoisonBlock(void* data) { ASAN_POISON_MEMORY_REGION(data, kPageSize); }
#elif defined(ABSL_HAVE_MEMORY_SANITIZER)
void PoisonBlock(void* data) { __msan_poison(data, kPageSize); }
#elif defined(ABSL_HAVE_MMAP)
void PoisonBlock(void* data) { mprotect(data, kPageSize, PROT_NONE); }
#elif defined(_MSC_VER)
void PoisonBlock(void* data) {
DWORD old_mode = 0;
VirtualProtect(data, kPageSize, PAGE_NOACCESS, &old_mode);
}
#else
void PoisonBlock(void* data) {
constexpr uint64_t kBadPtr = 0xBAD0BAD0BAD0BAD0;
poison_data = reinterpret_cast<void*>(static_cast<uintptr_t>(kBadPtr));
}
#endif
void* InitializePoisonedPointer() {
PoisonBlock(&poison_page);
return &poison_page;
}
}
ABSL_ATTRIBUTE_UNUSED void* force_initialize = InitializePoisonedPointer();
}
ABSL_NAMESPACE_END
} | #include "absl/base/internal/poison.h"
#include <iostream>
#include "gtest/gtest.h"
#include "absl/base/config.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace base_internal {
namespace {
TEST(PoisonTest, CrashesOnDereference) {
#ifdef __ANDROID__
GTEST_SKIP() << "On Android, poisoned pointer dereference times out instead "
"of crashing.";
#endif
void* poisoned_ptr = get_poisoned_pointer();
EXPECT_DEATH_IF_SUPPORTED(std::cout << *static_cast<int*>(poisoned_ptr), "");
}
}
}
ABSL_NAMESPACE_END
} |
318 | #ifndef I18N_ADDRESSINPUT_UTIL_MD5_H_
#define I18N_ADDRESSINPUT_UTIL_MD5_H_
#include <cstddef>
#include <cstdint>
#include <string>
namespace i18n {
namespace addressinput {
struct MD5Digest {
uint8_t a[16];
};
typedef char MD5Context[88];
void MD5Init(MD5Context* context);
void MD5Update(MD5Context* context, const std::string& data);
void MD5Final(MD5Digest* digest, MD5Context* context);
void MD5IntermediateFinal(MD5Digest* digest, const MD5Context* context);
std::string MD5DigestToBase16(const MD5Digest& digest);
void MD5Sum(const void* data, size_t length, MD5Digest* digest);
std::string MD5String(const std::string& str);
}
}
#endif
#include "md5.h"
#include <cstddef>
#include <string>
#include <string.h>
namespace {
struct Context {
uint32_t buf[4];
uint32_t bits[2];
uint8_t in[64];
};
void byteReverse(uint8_t* buf, unsigned longs) {
do {
uint32_t temp = static_cast<uint32_t>(
static_cast<unsigned>(buf[3]) << 8 |
buf[2]) << 16 |
(static_cast<unsigned>(buf[1]) << 8 | buf[0]);
*reinterpret_cast<uint32_t*>(buf) = temp;
buf += 4;
} while (--longs);
}
#define F1(x, y, z) (z ^ (x & (y ^ z)))
#define F2(x, y, z) F1(z, x, y)
#define F3(x, y, z) (x ^ y ^ z)
#define F4(x, y, z) (y ^ (x | ~z))
#define MD5STEP(f, w, x, y, z, data, s) \
(w += f(x, y, z) + data, w = w << s | w >> (32 - s), w += x)
void MD5Transform(uint32_t buf[4], const uint32_t in[16]) {
uint32_t a, b, c, d;
a = buf[0];
b = buf[1];
c = buf[2];
d = buf[3];
MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
buf[0] += a;
buf[1] += b;
buf[2] += c;
buf[3] += d;
}
}
namespace i18n {
namespace addressinput {
void MD5Init(MD5Context* context) {
struct Context* ctx = reinterpret_cast<struct Context*>(context);
ctx->buf[0] = 0x67452301;
ctx->buf[1] = 0xefcdab89;
ctx->buf[2] = 0x98badcfe;
ctx->buf[3] = 0x10325476;
ctx->bits[0] = 0;
ctx->bits[1] = 0;
}
void MD5Update(MD5Context* context, const std::string& data) {
struct Context* ctx = reinterpret_cast<struct Context*>(context);
const uint8_t* buf = reinterpret_cast<const uint8_t*>(data.data());
size_t len = data.size();
uint32_t t = ctx->bits[0];
if ((ctx->bits[0] = t + (static_cast<uint32_t>(len) << 3)) < t)
ctx->bits[1]++;
ctx->bits[1] += static_cast<uint32_t>(len >> 29);
t = (t >> 3) & 0x3f;
if (t) {
uint8_t* p = static_cast<uint8_t*>(ctx->in + t);
t = 64 - t;
if (len < t) {
memcpy(p, buf, len);
return;
}
memcpy(p, buf, t);
byteReverse(ctx->in, 16);
MD5Transform(ctx->buf, reinterpret_cast<uint32_t*>(ctx->in));
buf += t;
len -= t;
}
while (len >= 64) {
memcpy(ctx->in, buf, 64);
byteReverse(ctx->in, 16);
MD5Transform(ctx->buf, reinterpret_cast<uint32_t*>(ctx->in));
buf += 64;
len -= 64;
}
memcpy(ctx->in, buf, len);
}
void MD5Final(MD5Digest* digest, MD5Context* context) {
struct Context* ctx = reinterpret_cast<struct Context*>(context);
unsigned count;
uint8_t* p;
count = (ctx->bits[0] >> 3) & 0x3F;
p = ctx->in + count;
*p++ = 0x80;
count = 64 - 1 - count;
if (count < 8) {
memset(p, 0, count);
byteReverse(ctx->in, 16);
MD5Transform(ctx->buf, reinterpret_cast<uint32_t*>(ctx->in));
memset(ctx->in, 0, 56);
} else {
memset(p, 0, count - 8);
}
byteReverse(ctx->in, 14);
memcpy(&ctx->in[14 * sizeof(ctx->bits[0])], &ctx->bits[0],
sizeof(ctx->bits[0]));
memcpy(&ctx->in[15 * sizeof(ctx->bits[1])], &ctx->bits[1],
sizeof(ctx->bits[1]));
MD5Transform(ctx->buf, reinterpret_cast<uint32_t*>(ctx->in));
byteReverse(reinterpret_cast<uint8_t*>(ctx->buf), 4);
memcpy(digest->a, ctx->buf, 16);
memset(ctx, 0, sizeof(*ctx));
}
void MD5IntermediateFinal(MD5Digest* digest, const MD5Context* context) {
MD5Context context_copy;
memcpy(&context_copy, context, sizeof(context_copy));
MD5Final(digest, &context_copy);
}
std::string MD5DigestToBase16(const MD5Digest& digest) {
static char const zEncode[] = "0123456789abcdef";
std::string ret;
ret.resize(32);
for (int i = 0, j = 0; i < 16; i++, j += 2) {
uint8_t a = digest.a[i];
ret[j] = zEncode[(a >> 4) & 0xf];
ret[j + 1] = zEncode[a & 0xf];
}
return ret;
}
void MD5Sum(const void* data, size_t length, MD5Digest* digest) {
MD5Context ctx;
MD5Init(&ctx);
MD5Update(&ctx, std::string(reinterpret_cast<const char*>(data), length));
MD5Final(digest, &ctx);
}
std::string MD5String(const std::string& str) {
MD5Digest digest;
MD5Sum(str.data(), str.length(), &digest);
return MD5DigestToBase16(digest);
}
}
} | #include "util/md5.h"
#include <cstring>
#include <memory>
#include <string>
#include <gtest/gtest.h>
namespace {
using i18n::addressinput::MD5Context;
using i18n::addressinput::MD5Digest;
using i18n::addressinput::MD5Init;
using i18n::addressinput::MD5String;
using i18n::addressinput::MD5Update;
TEST(MD5, DigestToBase16) {
MD5Digest digest;
int data[] = {
0xd4, 0x1d, 0x8c, 0xd9,
0x8f, 0x00, 0xb2, 0x04,
0xe9, 0x80, 0x09, 0x98,
0xec, 0xf8, 0x42, 0x7e
};
for (int i = 0; i < 16; ++i)
digest.a[i] = data[i] & 0xff;
std::string actual = MD5DigestToBase16(digest);
std::string expected = "d41d8cd98f00b204e9800998ecf8427e";
EXPECT_EQ(expected, actual);
}
TEST(MD5, MD5SumEmtpyData) {
MD5Digest digest;
const char data[] = "";
MD5Sum(data, strlen(data), &digest);
int expected[] = {
0xd4, 0x1d, 0x8c, 0xd9,
0x8f, 0x00, 0xb2, 0x04,
0xe9, 0x80, 0x09, 0x98,
0xec, 0xf8, 0x42, 0x7e
};
for (int i = 0; i < 16; ++i)
EXPECT_EQ(expected[i], digest.a[i] & 0xFF);
}
TEST(MD5, MD5SumOneByteData) {
MD5Digest digest;
const char data[] = "a";
MD5Sum(data, strlen(data), &digest);
int expected[] = {
0x0c, 0xc1, 0x75, 0xb9,
0xc0, 0xf1, 0xb6, 0xa8,
0x31, 0xc3, 0x99, 0xe2,
0x69, 0x77, 0x26, 0x61
};
for (int i = 0; i < 16; ++i)
EXPECT_EQ(expected[i], digest.a[i] & 0xFF);
}
TEST(MD5, MD5SumLongData) {
const int length = 10 * 1024 * 1024 + 1;
std::unique_ptr<char[]> data(new char[length]);
for (int i = 0; i < length; ++i)
data[i] = i & 0xFF;
MD5Digest digest;
MD5Sum(data.get(), length, &digest);
int expected[] = {
0x90, 0xbd, 0x6a, 0xd9,
0x0a, 0xce, 0xf5, 0xad,
0xaa, 0x92, 0x20, 0x3e,
0x21, 0xc7, 0xa1, 0x3e
};
for (int i = 0; i < 16; ++i)
EXPECT_EQ(expected[i], digest.a[i] & 0xFF);
}
TEST(MD5, ContextWithEmptyData) {
MD5Context ctx;
MD5Init(&ctx);
MD5Digest digest;
MD5Final(&digest, &ctx);
int expected[] = {
0xd4, 0x1d, 0x8c, 0xd9,
0x8f, 0x00, 0xb2, 0x04,
0xe9, 0x80, 0x09, 0x98,
0xec, 0xf8, 0x42, 0x7e
};
for (int i = 0; i < 16; ++i)
EXPECT_EQ(expected[i], digest.a[i] & 0xFF);
}
TEST(MD5, ContextWithLongData) {
MD5Context ctx;
MD5Init(&ctx);
const int length = 10 * 1024 * 1024 + 1;
std::unique_ptr<char[]> data(new char[length]);
for (int i = 0; i < length; ++i)
data[i] = i & 0xFF;
int total = 0;
while (total < length) {
int len = 4097;
if (len > length - total)
len = length - total;
MD5Update(&ctx,
std::string(reinterpret_cast<char*>(data.get() + total), len));
total += len;
}
EXPECT_EQ(length, total);
MD5Digest digest;
MD5Final(&digest, &ctx);
int expected[] = {
0x90, 0xbd, 0x6a, 0xd9,
0x0a, 0xce, 0xf5, 0xad,
0xaa, 0x92, 0x20, 0x3e,
0x21, 0xc7, 0xa1, 0x3e
};
for (int i = 0; i < 16; ++i)
EXPECT_EQ(expected[i], digest.a[i] & 0xFF);
}
TEST(MD5, MD5StringTestSuite1) {
std::string actual = MD5String("");
std::string expected = "d41d8cd98f00b204e9800998ecf8427e";
EXPECT_EQ(expected, actual);
}
TEST(MD5, MD5StringTestSuite2) {
std::string actual = MD5String("a");
std::string expected = "0cc175b9c0f1b6a831c399e269772661";
EXPECT_EQ(expected, actual);
}
TEST(MD5, MD5StringTestSuite3) {
std::string actual = MD5String("abc");
std::string expected = "900150983cd24fb0d6963f7d28e17f72";
EXPECT_EQ(expected, actual);
}
TEST(MD5, MD5StringTestSuite4) {
std::string actual = MD5String("message digest");
std::string expected = "f96b697d7cb7938d525a2f31aaf161d0";
EXPECT_EQ(expected, actual);
}
TEST(MD5, MD5StringTestSuite5) {
std::string actual = MD5String("abcdefghijklmnopqrstuvwxyz");
std::string expected = "c3fcd3d76192e4007dfb496cca67e13b";
EXPECT_EQ(expected, actual);
}
TEST(MD5, MD5StringTestSuite6) {
std::string actual = MD5String("ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"0123456789");
std::string expected = "d174ab98d277d9f5a5611c2c9f419d9f";
EXPECT_EQ(expected, actual);
}
TEST(MD5, MD5StringTestSuite7) {
std::string actual = MD5String("12345678901234567890"
"12345678901234567890"
"12345678901234567890"
"12345678901234567890");
std::string expected = "57edf4a22be3c955ac49da2e2107b67a";
EXPECT_EQ(expected, actual);
}
TEST(MD5, ContextWithStringData) {
MD5Context ctx;
MD5Init(&ctx);
MD5Update(&ctx, "abc");
MD5Digest digest;
MD5Final(&digest, &ctx);
std::string actual = MD5DigestToBase16(digest);
std::string expected = "900150983cd24fb0d6963f7d28e17f72";
EXPECT_EQ(expected, actual);
}
TEST(MD5, IntermediateFinal) {
MD5Context check_header_context;
MD5Init(&check_header_context);
MD5Context check_full_context;
MD5Init(&check_full_context);
MD5Context context;
MD5Init(&context);
static const char kHeader[] = "header data";
static const char kBody[] = "payload data";
MD5Update(&context, kHeader);
MD5Update(&check_header_context, kHeader);
MD5Update(&check_full_context, kHeader);
MD5Digest check_header_digest;
MD5Final(&check_header_digest, &check_header_context);
MD5Digest header_digest;
MD5IntermediateFinal(&header_digest, &context);
MD5Update(&context, kBody);
MD5Update(&check_full_context, kBody);
MD5Digest check_full_digest;
MD5Final(&check_full_digest, &check_full_context);
MD5Digest digest;
MD5Final(&digest, &context);
EXPECT_TRUE(!memcmp(&header_digest, &check_header_digest,
sizeof(header_digest)));
EXPECT_TRUE(!memcmp(&digest, &check_full_digest, sizeof(digest)));
EXPECT_TRUE(memcmp(&digest, &header_digest, sizeof(digest)));
}
} |
319 | #ifndef AROLLA_EXPR_OPERATOR_LOADER_DUMMY_OPERATOR_H_
#define AROLLA_EXPR_OPERATOR_LOADER_DUMMY_OPERATOR_H_
#include "absl/status/statusor.h"
#include "absl/strings/string_view.h"
#include "absl/types/span.h"
#include "arolla/expr/basic_expr_operator.h"
#include "arolla/expr/expr_attributes.h"
#include "arolla/expr/expr_operator_signature.h"
#include "arolla/qtype/qtype.h"
namespace arolla::operator_loader {
class DummyOperator final : public expr::ExprOperatorWithFixedSignature {
public:
DummyOperator(absl::string_view name, expr::ExprOperatorSignature signature,
absl::string_view doc, QTypePtr result_qtype);
QTypePtr GetOutputQType() const { return result_qtype_; }
absl::string_view py_qvalue_specialization_key() const override;
absl::StatusOr<expr::ExprAttributes> InferAttributes(
absl::Span<const expr::ExprAttributes> inputs) const final;
private:
QTypePtr result_qtype_;
};
}
#endif
#include "arolla/expr/operator_loader/dummy_operator.h"
#include <utility>
#include "absl/status/statusor.h"
#include "absl/strings/string_view.h"
#include "absl/types/span.h"
#include "arolla/expr/basic_expr_operator.h"
#include "arolla/expr/expr_attributes.h"
#include "arolla/expr/expr_operator.h"
#include "arolla/expr/expr_operator_signature.h"
#include "arolla/qtype/qtype.h"
#include "arolla/util/fingerprint.h"
#include "arolla/util/status_macros_backport.h"
namespace arolla::operator_loader {
using ::arolla::expr::ExprAttributes;
using ::arolla::expr::ExprOperatorPtr;
using ::arolla::expr::ExprOperatorSignature;
DummyOperator::DummyOperator(absl::string_view name,
ExprOperatorSignature signature,
absl::string_view doc, QTypePtr result_qtype)
: ExprOperatorWithFixedSignature(
name, signature, doc,
FingerprintHasher("::arolla::operator_loader::DummyOperator")
.Combine(name, signature, doc, result_qtype)
.Finish()),
result_qtype_(std::move(result_qtype)) {}
absl::string_view DummyOperator::py_qvalue_specialization_key() const {
return "::arolla::operator_loader::DummyOperator";
}
absl::StatusOr<ExprAttributes> DummyOperator::InferAttributes(
absl::Span<const ExprAttributes> inputs) const {
RETURN_IF_ERROR(ValidateOpInputsCount(inputs));
return ExprAttributes(result_qtype_);
}
} | #include "arolla/expr/operator_loader/dummy_operator.h"
#include <cstdint>
#include <memory>
#include <utility>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "arolla/array/qtype/types.h"
#include "arolla/expr/eval/invoke.h"
#include "arolla/expr/expr.h"
#include "arolla/expr/expr_operator.h"
#include "arolla/expr/expr_operator_signature.h"
#include "arolla/memory/optional_value.h"
#include "arolla/qtype/qtype_traits.h"
#include "arolla/util/init_arolla.h"
#include "arolla/util/testing/status_matchers_backport.h"
#include "arolla/util/unit.h"
namespace arolla::operator_loader {
namespace {
using ::arolla::expr::CallOp;
using ::arolla::expr::ExprOperatorPtr;
using ::arolla::expr::ExprOperatorSignature;
using ::arolla::expr::Leaf;
using ::arolla::expr::Literal;
using ::arolla::testing::IsOkAndHolds;
using ::arolla::testing::StatusIs;
using ::testing::AllOf;
using ::testing::HasSubstr;
class DummyOperatorTest : public ::testing::Test {
protected:
void SetUp() override { ASSERT_OK(InitArolla()); }
};
TEST_F(DummyOperatorTest, GetName) {
DummyOperator op("my_dummy_op", ExprOperatorSignature{{"x"}, {"y"}},
"dummy op docstring", std::move(GetArrayQType<int32_t>()));
ASSERT_THAT(op.display_name(), "my_dummy_op");
}
TEST_F(DummyOperatorTest, GetDoc) {
DummyOperator op("my_dummy_op", ExprOperatorSignature{{"x"}, {"y"}},
"dummy op docstring", std::move(GetArrayQType<int32_t>()));
ASSERT_THAT(op.doc(), "dummy op docstring");
ASSERT_THAT(op.GetDoc(), IsOkAndHolds("dummy op docstring"));
}
TEST_F(DummyOperatorTest, GetOutputQType) {
{
DummyOperator op("my_dummy_op", ExprOperatorSignature{{"x"}, {"y"}},
"dummy op docstring", std::move(GetArrayQType<int32_t>()));
EXPECT_EQ(op.GetOutputQType(), GetArrayQType<int32_t>());
}
{
DummyOperator op("my_dummy_op", ExprOperatorSignature{{"x"}, {"y"}},
"dummy op docstring",
std::move(GetQType<OptionalValue<float>>()));
EXPECT_EQ(op.GetOutputQType(), GetQType<OptionalValue<float>>());
}
}
TEST_F(DummyOperatorTest, QTypeInference) {
{
auto op = std::make_shared<DummyOperator>(
"my_dummy_op", ExprOperatorSignature{{"x"}, {"y"}},
"dummy op docstring", std::move(GetArrayQType<int32_t>()));
ASSERT_OK_AND_ASSIGN(auto expr,
CallOp(op, {Literal(1.5f), Literal(kUnit)}));
EXPECT_EQ(expr->qtype(), GetArrayQType<int32_t>());
}
{
auto op = std::make_shared<DummyOperator>(
"my_dummy_op", ExprOperatorSignature{{"x"}, {"y"}},
"dummy op docstring", std::move(GetArrayQType<int32_t>()));
ASSERT_OK_AND_ASSIGN(auto expr, CallOp(op, {Leaf("x"), Leaf("y")}));
EXPECT_EQ(expr->qtype(), GetArrayQType<int32_t>());
}
}
TEST_F(DummyOperatorTest, InferAttributesIncorrectArity) {
DummyOperator op("my_dummy_op", ExprOperatorSignature{{"x"}, {"y"}},
"dummy op docstring", std::move(GetArrayQType<int32_t>()));
EXPECT_THAT(op.InferAttributes({}),
StatusIs(absl::StatusCode::kInvalidArgument,
AllOf(HasSubstr("incorrect number of dependencies"),
HasSubstr("expected 2 but got 0"))));
}
TEST_F(DummyOperatorTest, Eval) {
auto op = std::make_shared<DummyOperator>(
"my_dummy_op", ExprOperatorSignature{{"x"}, {"y"}}, "dummy op docstring",
std::move(GetArrayQType<int32_t>()));
ASSERT_OK_AND_ASSIGN(
auto expr, CallOp(op, {Literal(1.5f), Literal(OptionalValue<Unit>())}));
EXPECT_THAT(
Invoke(expr, {}),
StatusIs(
absl::StatusCode::kInvalidArgument,
HasSubstr("my_dummy_op is not a builtin or backend ExprOperator")));
}
TEST_F(DummyOperatorTest, Fingerprint) {
DummyOperator op1("my_dummy_op", ExprOperatorSignature{{"x"}, {"y"}},
"dummy op docstring", std::move(GetQType<float>()));
{
DummyOperator op2("my_dummy_op", ExprOperatorSignature{{"x"}, {"y"}},
"dummy op docstring", std::move(GetQType<float>()));
EXPECT_EQ(op1.fingerprint(), op2.fingerprint());
}
{
DummyOperator op2("another_name", ExprOperatorSignature{{"x"}, {"y"}},
"dummy op docstring", std::move(GetQType<float>()));
EXPECT_NE(op1.fingerprint(), op2.fingerprint());
}
{
DummyOperator op2("my_dummy_op", ExprOperatorSignature{{"x"}},
"dummy op docstring", std::move(GetQType<float>()));
EXPECT_NE(op1.fingerprint(), op2.fingerprint());
}
{
DummyOperator op2("my_dummy_op", ExprOperatorSignature{{"x"}, {"y"}},
"another docstring", std::move(GetQType<float>()));
EXPECT_NE(op1.fingerprint(), op2.fingerprint());
}
{
DummyOperator op2("my_dummy_op", ExprOperatorSignature{{"x"}, {"y"}},
"dummy op docstring", std::move(GetQType<int32_t>()));
EXPECT_NE(op1.fingerprint(), op2.fingerprint());
}
}
}
} |
320 | #ifndef TENSORSTORE_DRIVER_ZARR3_CODEC_BYTES_H_
#define TENSORSTORE_DRIVER_ZARR3_CODEC_BYTES_H_
#include <optional>
#include "absl/status/status.h"
#include "tensorstore/driver/zarr3/codec/codec.h"
#include "tensorstore/driver/zarr3/codec/codec_spec.h"
#include "tensorstore/index.h"
#include "tensorstore/internal/intrusive_ptr.h"
#include "tensorstore/util/endian.h"
#include "tensorstore/util/result.h"
#include "tensorstore/util/span.h"
namespace tensorstore {
namespace internal_zarr3 {
class BytesCodecSpec : public ZarrArrayToBytesCodecSpec {
public:
struct Options {
std::optional<endian> endianness;
bool constraints = false;
};
BytesCodecSpec() = default;
explicit BytesCodecSpec(const Options& options) : options(options) {}
absl::Status MergeFrom(const ZarrCodecSpec& other, bool strict) override;
ZarrCodecSpec::Ptr Clone() const override;
absl::Status GetDecodedChunkLayout(
const ArrayDataTypeAndShapeInfo& array_info,
ArrayCodecChunkLayoutInfo& decoded) const override;
bool SupportsInnerOrder(
const ArrayCodecResolveParameters& decoded,
span<DimensionIndex> preferred_inner_order) const override;
Result<ZarrArrayToBytesCodec::Ptr> Resolve(
ArrayCodecResolveParameters&& decoded,
BytesCodecResolveParameters& encoded,
ZarrArrayToBytesCodecSpec::Ptr* resolved_spec) const override;
Options options;
};
internal::IntrusivePtr<const BytesCodecSpec> DefaultBytesCodec();
}
}
#endif
#include "tensorstore/driver/zarr3/codec/bytes.h"
#include <assert.h>
#include <stdint.h>
#include <optional>
#include <string_view>
#include <utility>
#include "absl/status/status.h"
#include "riegeli/bytes/reader.h"
#include "riegeli/bytes/writer.h"
#include "tensorstore/array.h"
#include "tensorstore/contiguous_layout.h"
#include "tensorstore/data_type.h"
#include "tensorstore/driver/zarr3/codec/codec.h"
#include "tensorstore/driver/zarr3/codec/codec_spec.h"
#include "tensorstore/driver/zarr3/codec/registry.h"
#include "tensorstore/index.h"
#include "tensorstore/index_space/dimension_permutation.h"
#include "tensorstore/internal/global_initializer.h"
#include "tensorstore/internal/integer_overflow.h"
#include "tensorstore/internal/intrusive_ptr.h"
#include "tensorstore/internal/json_binding/enum.h"
#include "tensorstore/internal/json_binding/json_binding.h"
#include "tensorstore/internal/json_binding/std_optional.h"
#include "tensorstore/internal/riegeli/array_endian_codec.h"
#include "tensorstore/internal/unaligned_data_type_functions.h"
#include "tensorstore/rank.h"
#include "tensorstore/util/endian.h"
#include "tensorstore/util/result.h"
#include "tensorstore/util/span.h"
#include "tensorstore/util/status.h"
#include "tensorstore/util/str_cat.h"
namespace tensorstore {
namespace internal_zarr3 {
namespace {
absl::Status InvalidDataTypeError(DataType dtype) {
return absl::InvalidArgumentError(tensorstore::StrCat(
"Data type ", dtype, " not compatible with \"bytes\" codec"));
}
class BytesCodec : public ZarrArrayToBytesCodec {
public:
explicit BytesCodec(DataType decoded_dtype, endian endianness)
: dtype_(decoded_dtype), endianness_(endianness) {}
Result<PreparedState::Ptr> Prepare(
span<const Index> decoded_shape) const final;
private:
DataType dtype_;
endian endianness_;
};
}
absl::Status BytesCodecSpec::GetDecodedChunkLayout(
const ArrayDataTypeAndShapeInfo& array_info,
ArrayCodecChunkLayoutInfo& decoded) const {
if (array_info.dtype.valid() &&
!internal::IsTrivialDataType(array_info.dtype)) {
return InvalidDataTypeError(array_info.dtype);
}
const DimensionIndex rank = array_info.rank;
if (rank != dynamic_rank) {
auto& inner_order = decoded.inner_order.emplace();
for (DimensionIndex i = 0; i < rank; ++i) {
inner_order[i] = i;
}
}
if (array_info.shape) {
auto& shape = *array_info.shape;
auto& read_chunk_shape = decoded.read_chunk_shape.emplace();
for (DimensionIndex i = 0; i < rank; ++i) {
read_chunk_shape[i] = shape[i];
}
}
return absl::OkStatus();
}
bool BytesCodecSpec::SupportsInnerOrder(
const ArrayCodecResolveParameters& decoded,
span<DimensionIndex> preferred_inner_order) const {
if (!decoded.inner_order) return true;
if (PermutationMatchesOrder(span(decoded.inner_order->data(), decoded.rank),
c_order)) {
return true;
}
SetPermutation(c_order, preferred_inner_order);
return false;
}
Result<ZarrArrayToBytesCodec::Ptr> BytesCodecSpec::Resolve(
ArrayCodecResolveParameters&& decoded, BytesCodecResolveParameters& encoded,
ZarrArrayToBytesCodecSpec::Ptr* resolved_spec) const {
assert(decoded.dtype.valid());
if (!internal::IsTrivialDataType(decoded.dtype)) {
return InvalidDataTypeError(decoded.dtype);
}
const bool is_endian_invariant =
internal::IsEndianInvariantDataType(decoded.dtype);
if (!options.constraints && !is_endian_invariant && !options.endianness) {
return absl::InvalidArgumentError(
tensorstore::StrCat("\"bytes\" codec requires that \"endian\" option "
"is specified for data type ",
decoded.dtype));
}
encoded.item_bits = decoded.dtype.size() * 8;
DimensionIndex rank = decoded.rank;
if (decoded.codec_chunk_shape) {
return absl::InvalidArgumentError(tensorstore::StrCat(
"\"bytes\" codec does not support codec_chunk_shape (",
span<const Index>(decoded.codec_chunk_shape->data(), rank),
" was specified"));
}
if (decoded.inner_order) {
auto& decoded_inner_order = *decoded.inner_order;
for (DimensionIndex i = 0; i < rank; ++i) {
if (decoded_inner_order[i] != i) {
return absl::InvalidArgumentError(tensorstore::StrCat(
"\"bytes\" codec does not support inner_order of ",
span<const DimensionIndex>(decoded_inner_order.data(), rank)));
}
}
}
endian resolved_endianness = options.endianness.value_or(endian::native);
if (resolved_spec) {
resolved_spec->reset(new BytesCodecSpec(Options{
is_endian_invariant ? std::optional<endian>()
: std::optional<endian>(resolved_endianness)}));
}
return internal::MakeIntrusivePtr<BytesCodec>(decoded.dtype,
resolved_endianness);
}
namespace {
namespace jb = ::tensorstore::internal_json_binding;
constexpr auto EndiannessBinder() {
return jb::Enum<endian, std::string_view>({
{endian::little, "little"},
{endian::big, "big"},
});
}
}
absl::Status BytesCodecSpec::MergeFrom(const ZarrCodecSpec& other,
bool strict) {
using Self = BytesCodecSpec;
const auto& other_options = static_cast<const Self&>(other).options;
TENSORSTORE_RETURN_IF_ERROR(MergeConstraint<&Options::endianness>(
"endian", options, other_options, EndiannessBinder()));
return absl::OkStatus();
}
ZarrCodecSpec::Ptr BytesCodecSpec::Clone() const {
return internal::MakeIntrusivePtr<BytesCodecSpec>(*this);
}
namespace {
class BytesCodecPreparedState : public ZarrArrayToBytesCodec::PreparedState {
public:
int64_t encoded_size() const final { return encoded_size_; }
absl::Status EncodeArray(SharedArrayView<const void> decoded,
riegeli::Writer& writer) const final {
if (internal::EncodeArrayEndian(std::move(decoded), endianness_, c_order,
writer)) {
return absl::OkStatus();
}
assert(!writer.ok());
return writer.status();
}
Result<SharedArray<const void>> DecodeArray(
span<const Index> decoded_shape, riegeli::Reader& reader) const final {
return internal::DecodeArrayEndian(reader, dtype_, decoded_shape,
endianness_, c_order);
}
DataType dtype_;
endian endianness_;
int64_t encoded_size_;
};
}
Result<ZarrArrayToBytesCodec::PreparedState::Ptr> BytesCodec::Prepare(
span<const Index> decoded_shape) const {
int64_t bytes = dtype_.size();
for (auto size : decoded_shape) {
if (internal::MulOverflow(size, bytes, &bytes)) {
return absl::OutOfRangeError(tensorstore::StrCat(
"Integer overflow computing encoded size of array of shape ",
decoded_shape));
}
}
auto state = internal::MakeIntrusivePtr<BytesCodecPreparedState>();
state->dtype_ = dtype_;
state->endianness_ = endianness_;
state->encoded_size_ = bytes;
return state;
}
internal::IntrusivePtr<const BytesCodecSpec> DefaultBytesCodec() {
return internal::MakeIntrusivePtr<BytesCodecSpec>(
BytesCodecSpec::Options{endian::native});
}
TENSORSTORE_GLOBAL_INITIALIZER {
using Self = BytesCodecSpec;
using Options = Self::Options;
RegisterCodec<Self>(
"bytes",
jb::Projection<&Self::options>(jb::Sequence(
[](auto is_loading, const auto& options, auto* obj, auto* j) {
if constexpr (is_loading) {
obj->constraints = options.constraints;
}
return absl::OkStatus();
},
jb::Member("endian",
jb::Projection<&Options::endianness>(
jb::Optional(EndiannessBinder())))
)));
}
}
} | #include <stdint.h>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "absl/status/status.h"
#include <nlohmann/json.hpp>
#include "tensorstore/data_type.h"
#include "tensorstore/driver/zarr3/codec/codec_chain_spec.h"
#include "tensorstore/driver/zarr3/codec/codec_spec.h"
#include "tensorstore/driver/zarr3/codec/codec_test_util.h"
#include "tensorstore/internal/json_gtest.h"
#include "tensorstore/util/status_testutil.h"
namespace {
using ::tensorstore::dtype_v;
using ::tensorstore::MatchesJson;
using ::tensorstore::MatchesStatus;
using ::tensorstore::internal_zarr3::ArrayCodecResolveParameters;
using ::tensorstore::internal_zarr3::CodecRoundTripTestParams;
using ::tensorstore::internal_zarr3::CodecSpecRoundTripTestParams;
using ::tensorstore::internal_zarr3::GetDefaultBytesCodecJson;
using ::tensorstore::internal_zarr3::TestCodecRoundTrip;
using ::tensorstore::internal_zarr3::TestCodecSpecRoundTrip;
using ::tensorstore::internal_zarr3::ZarrCodecChainSpec;
TEST(BytesTest, SpecRoundTrip) {
CodecSpecRoundTripTestParams p;
p.orig_spec = {"bytes"};
p.expected_spec = ::nlohmann::json::array_t{GetDefaultBytesCodecJson()};
TestCodecSpecRoundTrip(p);
}
TEST(BytesTest, DuplicateArrayToBytes) {
EXPECT_THAT(
ZarrCodecChainSpec::FromJson({
{{"name", "bytes"}, {"configuration", {{"endian", "little"}}}},
{{"name", "bytes"}, {"configuration", {{"endian", "little"}}}},
}),
MatchesStatus(absl::StatusCode::kInvalidArgument,
"Expected bytes -> bytes codec, but received: .*"));
}
TEST(BytesTest, RoundTrip) {
CodecRoundTripTestParams p;
p.spec = {"bytes"};
TestCodecRoundTrip(p);
}
TEST(BytesTest, AutomaticTranspose) {
ArrayCodecResolveParameters p;
p.dtype = dtype_v<uint16_t>;
p.rank = 2;
auto& inner_order = p.inner_order.emplace();
inner_order[0] = 1;
inner_order[1] = 0;
EXPECT_THAT(
TestCodecSpecResolve(
::nlohmann::json::array_t{GetDefaultBytesCodecJson()}, p),
::testing::Optional(MatchesJson({
{{"name", "transpose"}, {"configuration", {{"order", {1, 0}}}}},
GetDefaultBytesCodecJson(),
})));
}
TEST(BytesTest, EndianInvariantDataType) {
ArrayCodecResolveParameters p;
p.dtype = dtype_v<uint8_t>;
p.rank = 2;
EXPECT_THAT(
TestCodecSpecResolve(::nlohmann::json::array_t{{{"name", "bytes"}}}, p,
false),
::testing::Optional(
MatchesJson(::nlohmann::json::array_t{{{"name", "bytes"}}})));
}
TEST(BytesTest, MissingEndianEndianInvariantDataType) {
ArrayCodecResolveParameters p;
p.dtype = dtype_v<uint16_t>;
p.rank = 2;
EXPECT_THAT(
TestCodecSpecResolve(::nlohmann::json::array_t{{{"name", "bytes"}}}, p,
false),
MatchesStatus(absl::StatusCode::kInvalidArgument,
".*: \"bytes\" codec requires that \"endian\" option is "
"specified for data type uint16"));
}
} |
321 | #ifndef TENSORSTORE_KVSTORE_GCS_HTTP_OBJECT_METADATA_H_
#define TENSORSTORE_KVSTORE_GCS_HTTP_OBJECT_METADATA_H_
#include <stdint.h>
#include <string>
#include <string_view>
#include "absl/container/btree_map.h"
#include "absl/time/time.h"
#include <nlohmann/json.hpp>
#include "tensorstore/internal/json_binding/bindable.h"
#include "tensorstore/json_serialization_options_base.h"
#include "tensorstore/util/result.h"
namespace tensorstore {
namespace internal_kvstore_gcs_http {
struct ObjectMetadata {
std::string name;
std::string md5_hash;
std::string crc32c;
uint64_t size = 0;
int64_t generation = 0;
int64_t metageneration = 0;
absl::Time time_created = absl::InfinitePast();
absl::Time updated = absl::InfinitePast();
absl::Time time_deleted = absl::InfinitePast();
using ToJsonOptions = IncludeDefaults;
using FromJsonOptions = internal_json_binding::NoOptions;
TENSORSTORE_DECLARE_JSON_DEFAULT_BINDER(
ObjectMetadata,
internal_kvstore_gcs_http::ObjectMetadata::FromJsonOptions,
internal_kvstore_gcs_http::ObjectMetadata::ToJsonOptions)
};
Result<ObjectMetadata> ParseObjectMetadata(std::string_view source);
void SetObjectMetadataFromHeaders(
const absl::btree_multimap<std::string, std::string>& headers,
ObjectMetadata* result);
}
}
#endif
#include "tensorstore/kvstore/gcs_http/object_metadata.h"
#include <stdint.h>
#include <optional>
#include <string>
#include <string_view>
#include <utility>
#include "absl/container/btree_map.h"
#include "absl/status/status.h"
#include "absl/strings/numbers.h"
#include "absl/strings/str_split.h"
#include "absl/time/time.h"
#include <nlohmann/json.hpp>
#include "tensorstore/internal/http/http_header.h"
#include "tensorstore/internal/json/json.h"
#include "tensorstore/internal/json_binding/absl_time.h"
#include "tensorstore/internal/json_binding/bindable.h"
#include "tensorstore/internal/json_binding/json_binding.h"
#include "tensorstore/util/result.h"
#include "tensorstore/util/str_cat.h"
namespace tensorstore {
namespace internal_kvstore_gcs_http {
using ::tensorstore::internal_http::TryParseIntHeader;
using ::tensorstore::internal_json_binding::DefaultInitializedValue;
namespace jb = tensorstore::internal_json_binding;
inline constexpr auto ObjectMetadataBinder = jb::Object(
jb::Member("name", jb::Projection(&ObjectMetadata::name)),
jb::Member("md5Hash", jb::Projection(&ObjectMetadata::md5_hash,
DefaultInitializedValue())),
jb::Member("crc32c", jb::Projection(&ObjectMetadata::crc32c,
DefaultInitializedValue())),
jb::Member("size", jb::Projection(&ObjectMetadata::size,
jb::DefaultInitializedValue(
jb::LooseValueAsBinder))),
jb::Member("generation", jb::Projection(&ObjectMetadata::generation,
jb::DefaultInitializedValue(
jb::LooseValueAsBinder))),
jb::Member("metageneration", jb::Projection(&ObjectMetadata::metageneration,
jb::DefaultInitializedValue(
jb::LooseValueAsBinder))),
jb::Member("timeCreated", jb::Projection(&ObjectMetadata::time_created,
jb::DefaultValue([](auto* x) {
*x = absl::InfinitePast();
}))),
jb::Member("updated", jb::Projection(&ObjectMetadata::updated,
jb::DefaultValue([](auto* x) {
*x = absl::InfinitePast();
}))),
jb::Member("timeDeleted", jb::Projection(&ObjectMetadata::time_deleted,
jb::DefaultValue([](auto* x) {
*x = absl::InfinitePast();
}))),
jb::DiscardExtraMembers);
TENSORSTORE_DEFINE_JSON_DEFAULT_BINDER(ObjectMetadata,
[](auto is_loading, const auto& options,
auto* obj, ::nlohmann::json* j) {
return ObjectMetadataBinder(
is_loading, options, obj, j);
})
void SetObjectMetadataFromHeaders(
const absl::btree_multimap<std::string, std::string>& headers,
ObjectMetadata* result) {
result->size =
TryParseIntHeader<uint64_t>(headers, "content-length").value_or(0);
result->generation =
TryParseIntHeader<int64_t>(headers, "x-goog-generation").value_or(0);
result->metageneration =
TryParseIntHeader<uint64_t>(headers, "x-goog-metageneration").value_or(0);
auto it = headers.find("x-goog-hash");
if (it != headers.end()) {
for (std::string_view kv : absl::StrSplit(it->second, absl::ByChar(','))) {
std::pair<std::string_view, std::string_view> split =
absl::StrSplit(kv, absl::MaxSplits('=', 1));
if (split.first == "crc32c") {
result->crc32c = std::string(split.second);
} else if (split.first == "md5") {
result->md5_hash = std::string(split.second);
}
}
}
}
Result<ObjectMetadata> ParseObjectMetadata(std::string_view source) {
auto json = internal::ParseJson(source);
if (json.is_discarded()) {
return absl::InvalidArgumentError(
tensorstore::StrCat("Failed to parse object metadata: ", source));
}
return jb::FromJson<ObjectMetadata>(std::move(json));
}
}
} | #include "tensorstore/kvstore/gcs_http/object_metadata.h"
#include <string>
#include <gtest/gtest.h>
#include "absl/time/time.h"
#include "tensorstore/util/result.h"
namespace {
using ::tensorstore::internal_kvstore_gcs_http::ParseObjectMetadata;
const char kObjectMetadata[] = R"""({
"acl": [{
"kind": "storage#objectAccessControl",
"id": "acl-id-0",
"selfLink": "https:
"bucket": "foo-bar",
"object": "foo",
"generation": 12345,
"entity": "user-qux",
"role": "OWNER",
"email": "qux@example.com",
"entityId": "user-qux-id-123",
"domain": "example.com",
"projectTeam": {
"projectNumber": "4567",
"team": "owners"
},
"etag": "AYX="
}, {
"kind": "storage#objectAccessControl",
"id": "acl-id-1",
"selfLink": "https:
"bucket": "foo-bar",
"object": "foo",
"generation": 12345,
"entity": "user-quux",
"role": "READER",
"email": "qux@example.com",
"entityId": "user-quux-id-123",
"domain": "example.com",
"projectTeam": {
"projectNumber": "4567",
"team": "viewers"
},
"etag": "AYX="
}
],
"bucket": "foo-bar",
"cacheControl": "no-cache",
"componentCount": 7,
"contentDisposition": "a-disposition",
"contentEncoding": "an-encoding",
"contentLanguage": "a-language",
"contentType": "application/octet-stream",
"crc32c": "deadbeef",
"customerEncryption": {
"encryptionAlgorithm": "some-algo",
"keySha256": "abc123"
},
"etag": "XYZ=",
"eventBasedHold": true,
"generation": "12345",
"id": "foo-bar/baz/12345",
"kind": "storage#object",
"kmsKeyName": "/foo/bar/baz/key",
"md5Hash": "deaderBeef=",
"mediaLink": "https:
"metadata": {
"foo": "bar",
"baz": "qux"
},
"metageneration": "4",
"name": "baz",
"owner": {
"entity": "user-qux",
"entityId": "user-qux-id-123"
},
"retentionExpirationTime": "2019-01-01T00:00:00Z",
"selfLink": "https:
"size": 102400,
"storageClass": "STANDARD",
"temporaryHold": true,
"timeCreated": "2018-05-19T19:31:14Z",
"timeDeleted": "2018-05-19T19:32:24Z",
"timeStorageClassUpdated": "2018-05-19T19:31:34Z",
"updated": "2018-05-19T19:31:24Z"
})""";
absl::Time AsTime(const std::string& time) {
absl::Time result;
if (absl::ParseTime(absl::RFC3339_full, time, &result, nullptr)) {
return result;
}
return absl::InfinitePast();
}
TEST(ParseObjectMetadata, Basic) {
EXPECT_FALSE(ParseObjectMetadata("").ok());
auto result = ParseObjectMetadata(kObjectMetadata);
ASSERT_TRUE(result.ok()) << result.status();
EXPECT_EQ("baz", result->name);
EXPECT_EQ("deaderBeef=", result->md5_hash);
EXPECT_EQ(102400u, result->size);
EXPECT_EQ(12345, result->generation);
EXPECT_EQ(4, result->metageneration);
EXPECT_EQ(AsTime("2018-05-19T12:31:14-07:00"), result->time_created);
EXPECT_EQ(AsTime("2018-05-19T12:31:24-07:00"), result->updated);
EXPECT_EQ(AsTime("2018-05-19T12:32:24-07:00"), result->time_deleted);
}
const char kObjectMetadata2[] = R"""({
"name": "fafb_v14/fafb_v14_clahe/128_128_160/0-64_1408-1472_896-960",
"kind": "storage#object",
"id": "neuroglancer-fafb-data/fafb_v14/fafb_v14_clahe/128_128_160/0-64_1408-1472_896-960/1540426531840872",
"bucket": "neuroglancer-fafb-data",
"generation": "1540426531840872",
"contentType": "image/jpeg",
"timeCreated": "2018-10-25T00:15:31.840Z",
"updated": "2018-10-25T00:15:31.840Z",
"timeStorageClassUpdated": "2018-10-25T00:15:31.840Z",
"size": "3404"
})""";
TEST(ParseObjectMetadata, Example2) {
EXPECT_FALSE(ParseObjectMetadata("").ok());
auto result = ParseObjectMetadata(kObjectMetadata2);
ASSERT_TRUE(result.ok()) << result.status();
EXPECT_EQ("fafb_v14/fafb_v14_clahe/128_128_160/0-64_1408-1472_896-960",
result->name);
EXPECT_EQ(3404u, result->size);
EXPECT_EQ(1540426531840872, result->generation);
EXPECT_EQ(AsTime("2018-10-24T17:15:31.84-07:00"), result->time_created);
EXPECT_EQ(AsTime("2018-10-24T17:15:31.84-07:00"), result->updated);
EXPECT_EQ(0, result->metageneration);
}
} |
322 | #ifndef TENSORSTORE_INTERNAL_THREAD_H_
#define TENSORSTORE_INTERNAL_THREAD_H_
#include <climits>
#include <cstring>
#include <functional>
#include <thread>
#include <utility>
#include "absl/log/absl_check.h"
namespace tensorstore {
namespace internal {
void TrySetCurrentThreadName(const char* name);
class Thread {
public:
using Id = std::thread::id;
struct Options {
const char* name = nullptr;
};
Thread() = default;
template <class Function, class... Args>
explicit Thread(Options options, Function&& f, Args&&... args)
: Thread(private_t{}, options, std::forward<Function>(f),
std::forward<Args>(args)...) {}
Thread(Thread&& other) noexcept = default;
Thread& operator=(Thread&& other) = default;
Thread(const Thread& other) = delete;
Thread& operator=(const Thread& other) = delete;
~Thread() { ABSL_CHECK(!thread_.joinable()); }
template <class Function, class... Args>
static void StartDetached(Options options, Function&& f, Args&&... args) {
Thread(private_t{}, options, std::forward<Function>(f),
std::forward<Args>(args)...)
.thread_.detach();
}
void Join() {
ABSL_CHECK_NE(this_thread_id(), get_id());
thread_.join();
}
Id get_id() const { return thread_.get_id(); }
static Id this_thread_id() { return std::this_thread::get_id(); }
private:
struct private_t {};
template <class Function, class... Args>
Thread(private_t, Options options, Function&& f, Args&&... args)
: thread_(
[name = options.name, fn = std::bind(std::forward<Function>(f),
std::forward<Args>(args)...)] {
TrySetCurrentThreadName(name);
std::move(fn)();
}) {}
std::thread thread_;
};
}
}
#endif
#if defined(__linux__) || defined(__APPLE__)
#include <pthread.h>
#endif
#include <thread>
#include <type_traits>
namespace tensorstore {
namespace internal {
void TrySetCurrentThreadName(const char* name) {
if (name == nullptr) return;
#if defined(__linux__)
pthread_setname_np(pthread_self(), name);
#endif
#if defined(__APPLE__)
pthread_setname_np(name);
#endif
}
}
} | #include "tensorstore/internal/thread/thread.h"
#include <gtest/gtest.h>
namespace {
TEST(ThreadTest, Basic) {
tensorstore::internal::Thread my_thread;
int x = 0;
tensorstore::internal::Thread::Id id[2];
my_thread = tensorstore::internal::Thread({}, [&x, &id]() {
x = 1;
id[1] = tensorstore::internal::Thread::this_thread_id();
});
id[0] = my_thread.get_id();
my_thread.Join();
EXPECT_EQ(id[0], id[1]);
EXPECT_EQ(1, x);
}
} |
323 | #ifndef QUICHE_QUIC_LOAD_BALANCER_LOAD_BALANCER_SERVER_ID_H_
#define QUICHE_QUIC_LOAD_BALANCER_LOAD_BALANCER_SERVER_ID_H_
#include <array>
#include <cstdint>
#include <string>
#include "absl/strings/string_view.h"
#include "absl/types/span.h"
#include "quiche/quic/platform/api/quic_export.h"
namespace quic {
inline constexpr uint8_t kLoadBalancerMaxServerIdLen = 15;
inline constexpr uint8_t kLoadBalancerBlockSize = 16;
static_assert(kLoadBalancerMaxServerIdLen <= kLoadBalancerBlockSize,
"LoadBalancerServerId array not large enough to hold Server ID");
class QUIC_EXPORT_PRIVATE LoadBalancerServerId {
public:
LoadBalancerServerId() : length_(0) {}
explicit LoadBalancerServerId(absl::Span<const uint8_t> data);
explicit LoadBalancerServerId(absl::string_view data);
bool operator<(const LoadBalancerServerId& other) const {
return data() < other.data();
}
bool operator==(const LoadBalancerServerId& other) const {
return data() == other.data();
}
template <typename H>
friend H AbslHashValue(H h, const LoadBalancerServerId& server_id) {
return H::combine_contiguous(std::move(h), server_id.data().data(),
server_id.length());
}
absl::Span<const uint8_t> data() const {
return absl::MakeConstSpan(data_.data(), length_);
}
uint8_t* mutable_data() { return data_.data(); }
uint8_t length() const { return length_; }
void set_length(uint8_t length);
std::string ToString() const;
bool IsValid() { return length_ != 0; }
private:
std::array<uint8_t, kLoadBalancerBlockSize> data_;
uint8_t length_;
};
}
#endif
#include "quiche/quic/load_balancer/load_balancer_server_id.h"
#include <array>
#include <cstdint>
#include <cstring>
#include <string>
#include "absl/strings/escaping.h"
#include "absl/strings/string_view.h"
#include "absl/types/span.h"
#include "quiche/quic/platform/api/quic_bug_tracker.h"
namespace quic {
LoadBalancerServerId::LoadBalancerServerId(absl::string_view data)
: LoadBalancerServerId(absl::MakeSpan(
reinterpret_cast<const uint8_t*>(data.data()), data.length())) {}
LoadBalancerServerId::LoadBalancerServerId(absl::Span<const uint8_t> data)
: length_(data.length()) {
if (length_ == 0 || length_ > kLoadBalancerMaxServerIdLen) {
QUIC_BUG(quic_bug_433312504_02)
<< "Attempted to create LoadBalancerServerId with length "
<< static_cast<int>(length_);
length_ = 0;
return;
}
memcpy(data_.data(), data.data(), data.length());
}
void LoadBalancerServerId::set_length(uint8_t length) {
QUIC_BUG_IF(quic_bug_599862571_01,
length == 0 || length > kLoadBalancerMaxServerIdLen)
<< "Attempted to set LoadBalancerServerId length to "
<< static_cast<int>(length);
length_ = length;
}
std::string LoadBalancerServerId::ToString() const {
return absl::BytesToHexString(
absl::string_view(reinterpret_cast<const char*>(data_.data()), length_));
}
} | #include "quiche/quic/load_balancer/load_balancer_server_id.h"
#include <cstdint>
#include <cstring>
#include "absl/hash/hash_testing.h"
#include "absl/types/span.h"
#include "quiche/quic/platform/api/quic_expect_bug.h"
#include "quiche/quic/platform/api/quic_test.h"
namespace quic {
namespace test {
namespace {
class LoadBalancerServerIdTest : public QuicTest {};
constexpr uint8_t kRawServerId[] = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05,
0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b,
0x0c, 0x0d, 0x0e, 0x0f};
TEST_F(LoadBalancerServerIdTest, CreateReturnsNullIfTooLong) {
EXPECT_QUIC_BUG(EXPECT_FALSE(LoadBalancerServerId(
absl::Span<const uint8_t>(kRawServerId, 16))
.IsValid()),
"Attempted to create LoadBalancerServerId with length 16");
EXPECT_QUIC_BUG(
EXPECT_FALSE(LoadBalancerServerId(absl::Span<const uint8_t>()).IsValid()),
"Attempted to create LoadBalancerServerId with length 0");
}
TEST_F(LoadBalancerServerIdTest, CompareIdenticalExceptLength) {
LoadBalancerServerId server_id(absl::Span<const uint8_t>(kRawServerId, 15));
ASSERT_TRUE(server_id.IsValid());
EXPECT_EQ(server_id.length(), 15);
LoadBalancerServerId shorter_server_id(
absl::Span<const uint8_t>(kRawServerId, 5));
ASSERT_TRUE(shorter_server_id.IsValid());
EXPECT_EQ(shorter_server_id.length(), 5);
EXPECT_TRUE(shorter_server_id < server_id);
EXPECT_FALSE(server_id < shorter_server_id);
EXPECT_FALSE(shorter_server_id == server_id);
}
TEST_F(LoadBalancerServerIdTest, AccessorFunctions) {
LoadBalancerServerId server_id(absl::Span<const uint8_t>(kRawServerId, 5));
EXPECT_TRUE(server_id.IsValid());
EXPECT_EQ(server_id.length(), 5);
EXPECT_EQ(memcmp(server_id.data().data(), kRawServerId, 5), 0);
EXPECT_EQ(server_id.ToString(), "0001020304");
}
TEST_F(LoadBalancerServerIdTest, CompareDifferentServerIds) {
LoadBalancerServerId server_id(absl::Span<const uint8_t>(kRawServerId, 5));
ASSERT_TRUE(server_id.IsValid());
LoadBalancerServerId reverse({0x0f, 0x0e, 0x0d, 0x0c, 0x0b});
ASSERT_TRUE(reverse.IsValid());
EXPECT_TRUE(server_id < reverse);
LoadBalancerServerId long_server_id(
absl::Span<const uint8_t>(kRawServerId, 15));
EXPECT_TRUE(long_server_id < reverse);
}
TEST_F(LoadBalancerServerIdTest, EqualityOperators) {
LoadBalancerServerId server_id(absl::Span<const uint8_t>(kRawServerId, 15));
ASSERT_TRUE(server_id.IsValid());
LoadBalancerServerId shorter_server_id(
absl::Span<const uint8_t>(kRawServerId, 5));
ASSERT_TRUE(shorter_server_id.IsValid());
EXPECT_FALSE(server_id == shorter_server_id);
LoadBalancerServerId server_id2 = server_id;
EXPECT_TRUE(server_id == server_id2);
}
TEST_F(LoadBalancerServerIdTest, SupportsHash) {
LoadBalancerServerId server_id(absl::Span<const uint8_t>(kRawServerId, 15));
ASSERT_TRUE(server_id.IsValid());
LoadBalancerServerId shorter_server_id(
absl::Span<const uint8_t>(kRawServerId, 5));
ASSERT_TRUE(shorter_server_id.IsValid());
LoadBalancerServerId different_server_id({0x0f, 0x0e, 0x0d, 0x0c, 0x0b});
ASSERT_TRUE(different_server_id.IsValid());
EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly({
server_id,
shorter_server_id,
different_server_id,
}));
}
TEST_F(LoadBalancerServerIdTest, SetLengthInvalid) {
LoadBalancerServerId server_id;
EXPECT_QUIC_BUG(server_id.set_length(16),
"Attempted to set LoadBalancerServerId length to 16");
EXPECT_QUIC_BUG(server_id.set_length(0),
"Attempted to set LoadBalancerServerId length to 0");
server_id.set_length(1);
EXPECT_EQ(server_id.length(), 1);
server_id.set_length(15);
EXPECT_EQ(server_id.length(), 15);
}
}
}
} |
324 | #ifndef TENSORFLOW_LITE_SIMPLE_PLANNER_H_
#define TENSORFLOW_LITE_SIMPLE_PLANNER_H_
#include <cassert>
#include <cstdint>
#include <memory>
#include <vector>
#include "tensorflow/lite/core/c/common.h"
#include "tensorflow/lite/graph_info.h"
#include "tensorflow/lite/memory_planner.h"
#include "tensorflow/lite/util.h"
namespace tflite {
struct SimpleAlloc {
SimpleAlloc() { reset(); }
size_t size;
int32_t node;
char* ptr;
inline void reset() {
size = 0;
node = 0;
ptr = nullptr;
}
inline bool alloc(size_t new_size, int32_t new_first_node) {
if (new_size == 0) {
return false;
}
size = new_size;
node = new_first_node;
assert(ptr == nullptr);
ptr = static_cast<char*>(malloc(new_size));
return true;
}
inline void free() {
if (ptr) {
::free(ptr);
}
reset();
}
};
class SimplePlanner : public MemoryPlanner {
public:
SimplePlanner(TfLiteContext* context, std::unique_ptr<GraphInfo> graph_info);
~SimplePlanner() override;
SimplePlanner(const SimplePlanner&) = delete;
SimplePlanner& operator=(const SimplePlanner&) = delete;
TfLiteStatus ResetAllocations() override;
TfLiteStatus ResetAllocationsAfter(int node) override;
TfLiteStatus PlanAllocations() override;
TfLiteStatus ExecuteAllocations(int first_node, int last_node) override;
TfLiteStatus ReleaseNonPersistentMemory() override;
TfLiteStatus AcquireNonPersistentMemory() override;
bool HasNonPersistentMemory() override { return true; };
void DumpDebugInfo(const std::vector<int>& execution_plan) const override{};
void GetAllocInfo(size_t* arena_size,
size_t* arena_persist_size) const override{};
private:
void FreeAllAllocations();
TfLiteStatus ResolveTensorAllocation(int tensor_index);
TfLiteContext* context_;
std::unique_ptr<GraphInfo> graph_info_;
std::vector<SimpleAlloc> allocs_;
std::vector<int32_t> alloc_node_;
std::vector<int32_t> dealloc_node_;
};
}
#endif
#include "tensorflow/lite/simple_planner.h"
#include <cstdint>
#include <limits>
#include <memory>
#include <utility>
#include <vector>
#include "tensorflow/lite/core/c/common.h"
#include "tensorflow/lite/graph_info.h"
namespace tflite {
namespace {
constexpr int32_t kNodeNotAssigned = std::numeric_limits<int32_t>::max();
}
SimplePlanner::SimplePlanner(TfLiteContext* context,
std::unique_ptr<GraphInfo> graph_info)
: context_(context), graph_info_(std::move(graph_info)) {}
SimplePlanner::~SimplePlanner() { FreeAllAllocations(); }
void SimplePlanner::FreeAllAllocations() {
for (int i = 0; i < static_cast<int>(allocs_.size()); ++i) {
allocs_[i].free();
}
}
TfLiteStatus SimplePlanner::ResetAllocations() {
FreeAllAllocations();
allocs_.clear();
allocs_.resize(graph_info_->num_tensors());
return kTfLiteOk;
}
TfLiteStatus SimplePlanner::ResetAllocationsAfter(int node) {
TfLiteTensor* tensors = graph_info_->tensors();
for (int i = 0; i < static_cast<int>(allocs_.size()); ++i) {
if (allocs_[i].node > node && allocs_[i].size > 0) {
TfLiteTensor& tensor = tensors[i];
if (tensor.allocation_type == kTfLiteArenaRw) {
allocs_[i].free();
tensor.data.raw = nullptr;
}
}
}
return kTfLiteOk;
}
TfLiteStatus SimplePlanner::PlanAllocations() {
TF_LITE_ENSURE_STATUS(ResetAllocations());
alloc_node_.assign(graph_info_->num_tensors(), kNodeNotAssigned);
dealloc_node_.assign(graph_info_->num_tensors(), kNodeNotAssigned);
std::vector<int> refcounts(graph_info_->num_tensors(), 0);
auto allocate = [this](int node, int tensor) -> TfLiteStatus {
if (alloc_node_[tensor] != kNodeNotAssigned) {
return kTfLiteOk;
}
TF_LITE_ENSURE(context_, dealloc_node_[tensor] == kNodeNotAssigned);
alloc_node_[tensor] = node;
return kTfLiteOk;
};
auto deallocate = [this](int node, int tensor) -> TfLiteStatus {
if (alloc_node_[tensor] == kNodeNotAssigned) {
return kTfLiteOk;
}
TF_LITE_ENSURE(context_, dealloc_node_[tensor] == kNodeNotAssigned);
dealloc_node_[tensor] = node;
return kTfLiteOk;
};
for (int tensor_index : graph_info_->outputs()) {
if (tensor_index != kTfLiteOptionalTensor) {
refcounts[tensor_index]++;
}
}
for (int tensor_index : graph_info_->variables()) {
refcounts[tensor_index]++;
TF_LITE_ENSURE(context_, tensor_index != kTfLiteOptionalTensor);
TF_LITE_ENSURE_STATUS(allocate(0, tensor_index));
}
for (int tensor_index : graph_info_->inputs()) {
if (tensor_index != kTfLiteOptionalTensor) {
refcounts[tensor_index]++;
TF_LITE_ENSURE_STATUS(allocate(0, tensor_index));
}
}
const size_t num_execution_nodes = graph_info_->num_execution_nodes();
for (size_t i = 0; i < num_execution_nodes; ++i) {
const TfLiteNode& node = graph_info_->node(i);
TfLiteIntArray* node_inputs = node.inputs;
for (int j = 0; j < node_inputs->size; ++j) {
int tensor_index = node_inputs->data[j];
if (tensor_index != kTfLiteOptionalTensor) {
refcounts[tensor_index]++;
}
}
}
for (size_t i = 0; i < num_execution_nodes; ++i) {
const TfLiteNode& node = graph_info_->node(i);
TfLiteIntArray* node_outputs = node.outputs;
for (int j = 0; j < node_outputs->size; ++j) {
int tensor_index = node_outputs->data[j];
TF_LITE_ENSURE_STATUS(allocate(i, tensor_index));
}
TfLiteIntArray* node_inputs = node.inputs;
for (int j = 0; j < node_inputs->size; ++j) {
int tensor_index = node_inputs->data[j];
if (tensor_index != kTfLiteOptionalTensor) {
refcounts[tensor_index]--;
if (refcounts[tensor_index] == 0) {
TF_LITE_ENSURE_STATUS(deallocate(i, tensor_index));
}
}
}
}
return kTfLiteOk;
}
TfLiteStatus SimplePlanner::ExecuteAllocations(int first_node, int last_node) {
alloc_node_.resize(graph_info_->num_tensors(), kNodeNotAssigned);
dealloc_node_.resize(graph_info_->num_tensors(), kNodeNotAssigned);
allocs_.resize(graph_info_->num_tensors());
const size_t num_execution_nodes = graph_info_->num_execution_nodes();
for (size_t i = first_node;
i <= static_cast<size_t>(last_node) && i < num_execution_nodes; ++i) {
const TfLiteNode& node = graph_info_->node(i);
TfLiteIntArray* node_temporaries = node.temporaries;
for (int j = 0; j < node_temporaries->size; ++j) {
int tensor_index = node_temporaries->data[j];
alloc_node_[tensor_index] = i;
dealloc_node_[tensor_index] = i;
}
}
const int num_tensors = static_cast<int>(graph_info_->num_tensors());
TfLiteTensor* tensors = graph_info_->tensors();
for (int i = 0; i < num_tensors; ++i) {
bool allocated = false;
if (alloc_node_[i] >= first_node && alloc_node_[i] <= last_node) {
TfLiteTensor& tensor = tensors[i];
if (tensor.allocation_type == kTfLiteArenaRw) {
if (allocs_[i].size != 0) {
allocs_[i].free();
}
allocated = allocs_[i].alloc(tensor.bytes, alloc_node_[i]);
} else if (tensor.allocation_type == kTfLiteArenaRwPersistent &&
allocs_[i].size == 0) {
allocated = allocs_[i].alloc(tensor.bytes, alloc_node_[i]);
}
}
if (allocated) {
TF_LITE_ENSURE_STATUS(ResolveTensorAllocation(i));
}
}
return kTfLiteOk;
}
TfLiteStatus SimplePlanner::ReleaseNonPersistentMemory() {
const int num_tensors = static_cast<int>(graph_info_->num_tensors());
TfLiteTensor* tensors = graph_info_->tensors();
for (int i = 0; i < num_tensors; ++i) {
TfLiteTensor& tensor = tensors[i];
if (tensor.allocation_type == kTfLiteArenaRw) {
allocs_[i].free();
tensor.data.raw = nullptr;
}
}
return kTfLiteOk;
}
TfLiteStatus SimplePlanner::AcquireNonPersistentMemory() {
const int num_tensors = static_cast<int>(graph_info_->num_tensors());
TfLiteTensor* tensors = graph_info_->tensors();
for (int i = 0; i < num_tensors; ++i) {
TfLiteTensor& tensor = tensors[i];
if (tensor.allocation_type == kTfLiteArenaRw) {
TF_LITE_ENSURE_STATUS(ResolveTensorAllocation(i));
}
}
return kTfLiteOk;
}
TfLiteStatus SimplePlanner::ResolveTensorAllocation(int tensor_index) {
TfLiteTensor& tensor = *graph_info_->tensor(tensor_index);
if (tensor.allocation_type == kTfLiteArenaRw) {
if (allocs_[tensor_index].size != 0) {
tensor.data.raw = allocs_[tensor_index].ptr;
}
}
if (tensor.allocation_type == kTfLiteArenaRwPersistent) {
tensor.data.raw = allocs_[tensor_index].ptr;
}
return kTfLiteOk;
}
} | #include "tensorflow/lite/simple_planner.h"
#include <algorithm>
#include <cstdarg>
#include <initializer_list>
#include <memory>
#include <utility>
#include <vector>
#include <gtest/gtest.h>
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/lite/core/c/common.h"
#include "tensorflow/lite/graph_info.h"
namespace tflite {
namespace {
class TestOp {
public:
TestOp(std::initializer_list<int> inputs, std::initializer_list<int> outputs,
std::initializer_list<int> temporaries)
: inputs_(inputs), outputs_(outputs), temporaries_(temporaries) {}
const std::vector<int>& inputs() const { return inputs_; }
const std::vector<int>& outputs() const { return outputs_; }
const std::vector<int>& temporaries() const { return temporaries_; }
const TfLiteRegistration& registration() const { return registration_; }
private:
std::vector<int> inputs_;
std::vector<int> outputs_;
std::vector<int> temporaries_;
TfLiteRegistration registration_{};
};
class TestGraph {
public:
TestGraph(std::initializer_list<int> inputs,
std::initializer_list<TestOp> nodes,
std::initializer_list<int> outputs)
: inputs_(inputs), outputs_(outputs) {
int max_tensor_index = 0;
for (int t : inputs) {
max_tensor_index = std::max(max_tensor_index, t);
}
for (int t : outputs) {
max_tensor_index = std::max(max_tensor_index, t);
}
for (const auto& node : nodes) {
auto int_array = [](const std::vector<int>& x) {
TfLiteIntArray* lite = TfLiteIntArrayCreate(x.size());
for (size_t i = 0; i < x.size(); i++) lite->data[i] = x[i];
return lite;
};
registrations_.push_back(node.registration());
nodes_.push_back(TfLiteNode());
nodes_.back().inputs = int_array(node.inputs());
for (int t : node.inputs()) {
max_tensor_index = std::max(max_tensor_index, t);
}
nodes_.back().outputs = int_array(node.outputs());
for (int t : node.outputs()) {
max_tensor_index = std::max(max_tensor_index, t);
}
nodes_.back().temporaries = int_array(node.temporaries());
for (int t : node.temporaries()) {
max_tensor_index = std::max(max_tensor_index, t);
}
}
for (int i = 0; i <= max_tensor_index; ++i) {
tensors_.push_back(TfLiteTensor());
tensors_.back().allocation_type = kTfLiteArenaRw;
tensors_.back().bytes = (i + 1) * 3;
}
}
~TestGraph() {
for (auto node : nodes_) {
TfLiteIntArrayFree(node.inputs);
TfLiteIntArrayFree(node.outputs);
TfLiteIntArrayFree(node.temporaries);
}
}
const std::vector<TfLiteNode>& nodes() { return nodes_; }
std::vector<TfLiteTensor>* tensors() { return &tensors_; }
const std::vector<int>& inputs() { return inputs_; }
const std::vector<int>& outputs() { return outputs_; }
const std::vector<int>& variables() { return variables_; }
const std::vector<TfLiteRegistration>& registrations() {
return registrations_;
}
void SetVariables(const std::vector<int>& variables) {
variables_ = variables;
}
void Swap(TestGraph* other) {
std::swap(nodes_, other->nodes_);
std::swap(tensors_, other->tensors_);
std::swap(inputs_, other->inputs_);
std::swap(outputs_, other->outputs_);
std::swap(variables_, other->variables_);
}
private:
std::vector<TfLiteNode> nodes_;
std::vector<TfLiteTensor> tensors_;
std::vector<TfLiteRegistration> registrations_;
std::vector<int> inputs_;
std::vector<int> outputs_;
std::vector<int> variables_;
};
class TestGraphInfo : public GraphInfo {
public:
explicit TestGraphInfo(TestGraph* graph) : graph_(graph) {}
size_t num_tensors() const override { return graph_->tensors()->size(); }
const TfLiteRegistration& registration(size_t index) const override {
return graph_->registrations()[index];
}
TfLiteTensor* tensor(size_t index) override {
return &graph_->tensors()->at(index);
}
TfLiteTensor* tensors() override { return graph_->tensors()->data(); }
size_t num_execution_nodes() const override { return graph_->nodes().size(); }
size_t num_total_nodes() const override { return graph_->nodes().size(); }
const TfLiteNode& node(size_t index) const override {
return graph_->nodes()[index];
}
size_t node_index(size_t index) const override { return index; }
const std::vector<int>& inputs() const override { return graph_->inputs(); }
const std::vector<int>& outputs() const override { return graph_->outputs(); }
const std::vector<int>& variables() const override {
return graph_->variables();
}
private:
TestGraph* graph_;
};
void ReportError(TfLiteContext* context, const char* format, ...) {
const size_t kBufferSize = 1024;
char temp_buffer[kBufferSize];
va_list args;
va_start(args, format);
vsnprintf(temp_buffer, kBufferSize, format, args);
va_end(args);
LOG(INFO) << temp_buffer;
}
class SimplePlannerTest : public ::testing::Test {
protected:
void SetGraph(TestGraph* graph, bool preserve_all_tensors = false) {
graph_ = graph;
context_.ReportError = ReportError;
planner_ = std::make_unique<SimplePlanner>(
&context_, std::unique_ptr<GraphInfo>(new TestGraphInfo(graph)));
CHECK(planner_->ResetAllocations() == kTfLiteOk);
CHECK(planner_->PlanAllocations() == kTfLiteOk);
}
void SwapGraph(TestGraph* graph) {
graph_->Swap(graph);
CHECK(planner_->PlanAllocations() == kTfLiteOk);
}
void Execute(int start, int end) {
CHECK(planner_->ExecuteAllocations(start, end) == kTfLiteOk);
}
void ReleaseNonPersistentMemory() {
CHECK(planner_->ReleaseNonPersistentMemory() == kTfLiteOk);
}
void AcquireNonPersistentMemory() {
CHECK(planner_->AcquireNonPersistentMemory() == kTfLiteOk);
}
void ResetAllocationsAfter(int node) {
CHECK(planner_->ResetAllocationsAfter(node) == kTfLiteOk);
}
bool HasNonPersistentMemory() {
return planner_ && planner_->HasNonPersistentMemory();
}
bool IsAllocated(int tensor_index) {
return (*graph_->tensors())[tensor_index].data.raw != nullptr;
}
TfLiteContext context_;
TestGraph* graph_;
std::unique_ptr<SimplePlanner> planner_;
};
TEST_F(SimplePlannerTest, EmptyGraph) {
TestGraph graph({}, {}, {});
SetGraph(&graph);
Execute(0, 10);
}
TEST_F(SimplePlannerTest, GraphWithNoOps) {
TestGraph graph({0, 10}, {}, {5, 11});
SetGraph(&graph);
Execute(0, 10);
EXPECT_FALSE(IsAllocated(5));
EXPECT_FALSE(IsAllocated(11));
}
TEST_F(SimplePlannerTest, ZeroSizedTensors) {
TestGraph graph({1}, {{{1}, {2}, {}}}, {2});
(*graph.tensors())[1].bytes = 0;
SetGraph(&graph);
ASSERT_EQ(planner_->ExecuteAllocations(0, 10), kTfLiteOk);
EXPECT_FALSE(IsAllocated(1));
EXPECT_TRUE(IsAllocated(2));
}
TEST_F(SimplePlannerTest, SimpleGraph) {
TestGraph graph({0, 1},
{
{{0, 1}, {2}, {}},
{{2, 0}, {4, 5}, {}},
{{4, 5}, {3}, {}}
},
{3});
SetGraph(&graph);
Execute(0, 10);
EXPECT_TRUE(IsAllocated(1));
EXPECT_TRUE(IsAllocated(2));
EXPECT_TRUE(IsAllocated(3));
EXPECT_TRUE(IsAllocated(4));
EXPECT_TRUE(IsAllocated(5));
}
TEST_F(SimplePlannerTest, SimpleGraphInputsPreserved) {
TestGraph graph({0, 1},
{
{{0, 1}, {2}, {}},
{{2, 0}, {4, 5}, {}},
{{4, 5}, {3}, {}}
},
{3});
SetGraph(&graph);
Execute(0, 10);
EXPECT_TRUE(IsAllocated(1));
EXPECT_TRUE(IsAllocated(2));
EXPECT_TRUE(IsAllocated(3));
EXPECT_TRUE(IsAllocated(4));
EXPECT_TRUE(IsAllocated(5));
}
TEST_F(SimplePlannerTest, SimpleGraphWithTemporary) {
TestGraph graph({0, 1},
{
{{0, 1}, {2}, {}},
{{2, 0}, {4}, {5}},
{{4}, {3}, {}}
},
{3});
SetGraph(&graph);
Execute(0, 10);
EXPECT_TRUE(IsAllocated(1));
EXPECT_TRUE(IsAllocated(2));
EXPECT_TRUE(IsAllocated(3));
EXPECT_TRUE(IsAllocated(4));
EXPECT_TRUE(IsAllocated(5));
}
TEST_F(SimplePlannerTest, SimpleGraphWithResetAllocationsAfter) {
TestGraph graph({0, 1},
{
{{0, 1}, {2}, {}},
{{2, 0}, {4}, {5}},
{{4}, {3}, {}}
},
{3});
SetGraph(&graph);
Execute(0, 10);
EXPECT_TRUE(IsAllocated(2));
EXPECT_TRUE(IsAllocated(3));
EXPECT_TRUE(IsAllocated(4));
EXPECT_TRUE(IsAllocated(5));
ResetAllocationsAfter(0);
EXPECT_TRUE(IsAllocated(0));
EXPECT_TRUE(IsAllocated(1));
EXPECT_TRUE(IsAllocated(2));
EXPECT_FALSE(IsAllocated(3));
EXPECT_FALSE(IsAllocated(4));
EXPECT_FALSE(IsAllocated(5));
}
TEST_F(SimplePlannerTest, SimpleGraphWithPersistentResetAllocationsAfter) {
TestGraph graph({0, 1},
{
{{0, 1}, {2}, {}},
{{2, 0}, {4}, {5}},
{{4}, {3}, {}}
},
{3});
(*graph.tensors())[5].allocation_type = kTfLiteArenaRwPersistent;
SetGraph(&graph);
Execute(0, 10);
void* tensor5_ptr = (*graph.tensors())[5].data.raw;
ResetAllocationsAfter(0);
EXPECT_TRUE(IsAllocated(0));
EXPECT_TRUE(IsAllocated(1));
EXPECT_TRUE(IsAllocated(2));
EXPECT_FALSE(IsAllocated(3));
EXPECT_FALSE(IsAllocated(4));
EXPECT_TRUE(IsAllocated(5));
Execute(0, 10);
EXPECT_TRUE(tensor5_ptr == (*graph.tensors())[5].data.raw);
}
TEST_F(SimplePlannerTest, SimpleGraphOptionalOutput) {
TestGraph graph({0, 1},
{
{{0, 1}, {2}, {}},
{{2, 0}, {4, 5}, {}},
{{4, 5}, {3}, {}}
},
{-1, 3});
SetGraph(&graph);
Execute(0, 10);
EXPECT_TRUE(IsAllocated(1));
EXPECT_TRUE(IsAllocated(2));
EXPECT_TRUE(IsAllocated(3));
EXPECT_TRUE(IsAllocated(4));
EXPECT_TRUE(IsAllocated(5));
}
}
} |
325 | #ifndef XLA_SERVICE_DOT_DIMENSION_MERGER_H_
#define XLA_SERVICE_DOT_DIMENSION_MERGER_H_
#include "absl/container/flat_hash_set.h"
#include "absl/status/statusor.h"
#include "absl/strings/string_view.h"
#include "xla/hlo/ir/hlo_module.h"
#include "xla/service/hlo_pass_interface.h"
namespace xla {
class DotDimensionMerger : public HloModulePass {
public:
absl::string_view name() const override { return "dot_dimension_merger"; }
using HloPassInterface::Run;
absl::StatusOr<bool> Run(
HloModule* module,
const absl::flat_hash_set<absl::string_view>& execution_threads) override;
};
}
#endif
#include "xla/service/dot_dimension_merger.h"
#include <cstdint>
#include <memory>
#include <utility>
#include <vector>
#include "absl/algorithm/container.h"
#include "absl/container/flat_hash_set.h"
#include "absl/status/status.h"
#include "absl/strings/string_view.h"
#include "absl/types/span.h"
#include "xla/hlo/ir/dfs_hlo_visitor_with_default.h"
#include "xla/hlo/ir/hlo_casting_utils.h"
#include "xla/hlo/ir/hlo_computation.h"
#include "xla/hlo/ir/hlo_instruction.h"
#include "xla/hlo/ir/hlo_instructions.h"
#include "xla/layout_util.h"
#include "xla/service/hlo_creation_utils.h"
#include "xla/shape.h"
#include "xla/util.h"
#include "xla/xla_data.pb.h"
#include "tsl/platform/statusor.h"
namespace xla {
namespace {
std::vector<int64_t> ShiftDimensions(absl::Span<const int64_t> dimensions,
const int64_t start, const int64_t shift) {
std::vector<int64_t> new_dimensions;
new_dimensions.reserve(dimensions.size());
for (const int64_t i : dimensions) {
if (i < start) {
new_dimensions.push_back(i);
} else {
new_dimensions.push_back(i - shift);
}
}
return new_dimensions;
}
class BatchDimensionMerger : public DfsHloRewriteVisitor {
public:
absl::Status HandleDot(HloInstruction* dot) override {
const DotDimensionNumbers& dnums = dot->dot_dimension_numbers();
const Shape& lhs_shape = dot->operand(0)->shape();
const Shape& rhs_shape = dot->operand(1)->shape();
CHECK_EQ(dnums.lhs_batch_dimensions_size(),
dnums.rhs_batch_dimensions_size());
const int64_t batch_dimension_count = dnums.lhs_batch_dimensions_size();
if (batch_dimension_count < 2 ||
!DistinctNumbersAreConsecutiveIfSorted(dnums.lhs_batch_dimensions()) ||
!DistinctNumbersAreConsecutiveIfSorted(dnums.rhs_batch_dimensions()) ||
!absl::c_is_sorted(dnums.lhs_batch_dimensions()) ||
!absl::c_is_sorted(dnums.rhs_batch_dimensions()) ||
!LayoutUtil::AreDimensionsConsecutive(lhs_shape.layout(),
dnums.lhs_batch_dimensions()) ||
!LayoutUtil::AreDimensionsConsecutive(rhs_shape.layout(),
dnums.rhs_batch_dimensions())) {
return absl::OkStatus();
}
const int64_t lhs_batch_dimension =
*absl::c_min_element(dnums.lhs_batch_dimensions());
const int64_t rhs_batch_dimension =
*absl::c_min_element(dnums.rhs_batch_dimensions());
int64_t batch_size = 1;
for (const int64_t dimension_number : dnums.lhs_batch_dimensions()) {
batch_size *= lhs_shape.dimensions(dimension_number);
}
auto merge_batch_dims = [&](Shape old_shape, int64_t batch_dim) {
Shape new_shape = old_shape;
for (int64_t i = 1; i < batch_dimension_count; ++i) {
new_shape.DeleteDimension(batch_dim + 1);
}
new_shape.set_dimensions(batch_dim, batch_size);
return new_shape;
};
Shape new_lhs_shape = merge_batch_dims(lhs_shape, lhs_batch_dimension);
Shape new_rhs_shape = merge_batch_dims(rhs_shape, rhs_batch_dimension);
DotDimensionNumbers new_dot_dimension_numbers;
new_dot_dimension_numbers.add_lhs_batch_dimensions(lhs_batch_dimension);
new_dot_dimension_numbers.add_rhs_batch_dimensions(rhs_batch_dimension);
{
const std::vector<int64_t> shifted_contracting_dimensions =
ShiftDimensions(dnums.lhs_contracting_dimensions(),
lhs_batch_dimension, batch_dimension_count - 1);
new_dot_dimension_numbers.mutable_lhs_contracting_dimensions()->Assign(
shifted_contracting_dimensions.begin(),
shifted_contracting_dimensions.end());
}
{
const std::vector<int64_t> shifted_contracting_dimensions =
ShiftDimensions(dnums.rhs_contracting_dimensions(),
rhs_batch_dimension, batch_dimension_count - 1);
new_dot_dimension_numbers.mutable_rhs_contracting_dimensions()->Assign(
shifted_contracting_dimensions.begin(),
shifted_contracting_dimensions.end());
}
auto sparsity = Cast<HloDotInstruction>(dot)->sparsity();
std::vector<SparsityDescriptor> new_sparsity(sparsity.begin(),
sparsity.end());
std::vector<HloInstruction*> sparse_meta(sparsity.size());
for (int i = 0; i < sparsity.size(); ++i) {
SparsityDescriptor& descriptor = new_sparsity[i];
int64_t sparse_batch_dim =
descriptor.index() == 0 ? lhs_batch_dimension : rhs_batch_dimension;
if (descriptor.dimension() > sparse_batch_dim)
descriptor.set_dimension(descriptor.dimension() -
(batch_dimension_count - 1));
HloInstruction* meta =
dot->mutable_operand(HloDotInstruction::kOperands + i);
Shape new_meta_shape = merge_batch_dims(meta->shape(), sparse_batch_dim);
TF_ASSIGN_OR_RETURN(sparse_meta[i], MakeReshapeHlo(new_meta_shape, meta));
}
TF_ASSIGN_OR_RETURN(HloInstruction * reshaped_lhs,
MakeReshapeHlo(new_lhs_shape, dot->mutable_operand(0)));
TF_ASSIGN_OR_RETURN(HloInstruction * reshaped_rhs,
MakeReshapeHlo(new_rhs_shape, dot->mutable_operand(1)));
Shape new_dot_shape = merge_batch_dims(dot->shape(), 0);
HloInstruction* new_dot = dot->parent()->AddInstruction(
HloInstruction::CreateDot(new_dot_shape, reshaped_lhs, reshaped_rhs,
new_dot_dimension_numbers,
dot->precision_config(), new_sparsity,
sparse_meta),
&dot->metadata());
dot->SetupDerivedInstruction(new_dot);
std::unique_ptr<HloInstruction> out_reshape =
HloInstruction::CreateReshape(dot->shape(), new_dot);
return ReplaceWithNewInstruction(dot, std::move(out_reshape));
}
};
}
absl::StatusOr<bool> DotDimensionMerger::Run(
HloModule* module,
const absl::flat_hash_set<absl::string_view>& execution_threads) {
return BatchDimensionMerger().RunOnModule(module, execution_threads);
}
} | #include "xla/service/dot_dimension_merger.h"
#include <memory>
#include <string>
#include <gtest/gtest.h>
#include "xla/service/hlo_parser.h"
#include "xla/tests/hlo_test_base.h"
#include "tsl/platform/statusor.h"
namespace xla {
namespace {
using DotDimensionMergerTest = HloTestBase;
TEST_F(DotDimensionMergerTest, MergeConsecutiveBatchDimensions) {
const std::string kHloText = R"(
HloModule m
ENTRY e {
p0 = bf16[79,2,4,12,11] parameter(0)
p1 = bf16[79,2,4,11,44] parameter(1)
ROOT d = bf16[2,4,12,44] dot(p0, p1),
lhs_batch_dims={1,2}, lhs_contracting_dims={0,4},
rhs_batch_dims={1,2}, rhs_contracting_dims={0,3},
metadata={op_name="testname"}
})";
RunAndFilecheckHloRewrite(kHloText, DotDimensionMerger(), R"(
; CHECK: %[[R0:.*]] = bf16[79,8,12,11]{3,2,1,0} reshape(%p0)
; CHECK: %[[R1:.*]] = bf16[79,8,11,44]{3,2,1,0} reshape(%p1)
; CHECK: %[[DOT:.*]] = bf16[8,12,44]{2,1,0} dot(%[[R0]], %[[R1]])
; CHECK-SAME: lhs_batch_dims={1}
; CHECK-SAME: lhs_contracting_dims={0,3}
; CHECK-SAME: rhs_batch_dims={1}
; CHECK-SAME: rhs_contracting_dims={0,2}
; CHECK-NEXT: ROOT {{[^ ]+}} = bf16[2,4,12,44]{3,2,1,0} reshape(%[[DOT]])
; CHECK-SAME: metadata={op_name="testname"}
)");
}
TEST_F(DotDimensionMergerTest,
MergeConsecutiveBatchDimensionsNonDefaultLayouts) {
const std::string kHloText = R"(
HloModule m
ENTRY e {
p0 = bf16[79,2,4,12,11]{4,0,3,2,1} parameter(0)
p1 = bf16[79,2,4,11,44]{3,0,4,2,1} parameter(1)
ROOT d = bf16[2,4,12,44]{3,1,0,2} dot(p0, p1),
lhs_batch_dims={1,2}, lhs_contracting_dims={0,4},
rhs_batch_dims={1,2}, rhs_contracting_dims={0,3},
metadata={op_name="testname"}
})";
RunAndFilecheckHloRewrite(kHloText, DotDimensionMerger(), R"(
; CHECK: %[[R0:.*]] = bf16[79,8,12,11]{3,0,2,1} reshape(%p0)
; CHECK: %[[R1:.*]] = bf16[79,8,11,44]{2,0,3,1} reshape(%p1)
; CHECK: %[[DOT:.*]] = bf16[8,12,44]{2,0,1} dot(%[[R0]], %[[R1]])
; CHECK-SAME: lhs_batch_dims={1}
; CHECK-SAME: lhs_contracting_dims={0,3}
; CHECK-SAME: rhs_batch_dims={1}
; CHECK-SAME: rhs_contracting_dims={0,2}
; CHECK-NEXT: ROOT {{[^ ]+}} = bf16[2,4,12,44]{3,1,0,2} reshape(%[[DOT]])
; CHECK-SAME: metadata={op_name="testname"}
)");
}
TEST_F(DotDimensionMergerTest, SkipPhysicallyNonConsecutiveBatchDimensions) {
const std::string kHloText = R"(
HloModule m
ENTRY e {
p0 = bf16[2,4,12,13]{3,1,2,0} parameter(0)
p1 = bf16[2,4,13,55]{3,2,1,0} parameter(1)
ROOT d = bf16[2,4,12,55]{3,2,1,0} dot(p0, p1),
lhs_batch_dims={0,1}, lhs_contracting_dims={3},
rhs_batch_dims={0,1}, rhs_contracting_dims={2}
})";
TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<VerifiedHloModule> module,
ParseAndReturnVerifiedModule(kHloText));
TF_ASSERT_OK_AND_ASSIGN(bool modified,
DotDimensionMerger().Run(module.get()));
EXPECT_FALSE(modified);
}
TEST_F(DotDimensionMergerTest, SkipUnsortedBatchDimensions) {
const std::string kHloText = R"(
HloModule m
ENTRY e {
p0 = bf16[4,2,12,13] parameter(0)
p1 = bf16[2,4,13,55] parameter(1)
ROOT d = bf16[2,4,12,55] dot(p0, p1),
lhs_batch_dims={1,0}, lhs_contracting_dims={3},
rhs_batch_dims={0,1}, rhs_contracting_dims={2}
})";
TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<VerifiedHloModule> module,
ParseAndReturnVerifiedModule(kHloText));
TF_ASSERT_OK_AND_ASSIGN(bool modified,
DotDimensionMerger().Run(module.get()));
EXPECT_FALSE(modified);
}
TEST_F(DotDimensionMergerTest, SkipLogicallyNonConsecutiveBatchDimensions) {
const std::string kHloText = R"(
HloModule m
ENTRY e {
p0 = bf16[2,12,4,13] parameter(0)
p1 = bf16[2,4,13,55] parameter(1)
ROOT d = bf16[2,4,12,55] dot(p0, p1),
lhs_batch_dims={0,2}, lhs_contracting_dims={3},
rhs_batch_dims={0,1}, rhs_contracting_dims={2}
})";
TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<VerifiedHloModule> module,
ParseAndReturnVerifiedModule(kHloText));
TF_ASSERT_OK_AND_ASSIGN(bool modified,
DotDimensionMerger().Run(module.get()));
EXPECT_FALSE(modified);
}
TEST_F(DotDimensionMergerTest, SparseDotUpdatesDescriptor) {
const std::string kHloText = R"(
HloModule m
ENTRY e {
p0 = bf16[3,4,5,6,16] parameter(0)
p1 = bf16[3,4,5,32,6] parameter(1)
meta = u16[3,4,5,6,2] parameter(2)
ROOT d = bf16[4,5,6,6] dot(p0, p1, meta), sparsity=L.4@2:4,
lhs_batch_dims={1,2}, lhs_contracting_dims={0,4},
rhs_batch_dims={1,2}, rhs_contracting_dims={0,3}
})";
RunAndFilecheckHloRewrite(kHloText, DotDimensionMerger(), R"(
; CHECK: %[[R0:.*]] = bf16[3,20,6,16]{3,2,1,0} reshape(%p0)
; CHECK: %[[R1:.*]] = bf16[3,20,32,6]{3,2,1,0} reshape(%p1)
; CHECK: %[[R2:.*]] = u16[3,20,6,2]{3,2,1,0} reshape(%meta)
; CHECK: %[[DOT:.*]] = bf16[20,6,6]{2,1,0} dot(%[[R0]], %[[R1]], %[[R2]])
; CHECK-SAME: lhs_batch_dims={1}
; CHECK-SAME: lhs_contracting_dims={0,3}
; CHECK-SAME: rhs_batch_dims={1}
; CHECK-SAME: rhs_contracting_dims={0,2}
; CHECK-SAME: sparsity=L.3@2:4
; CHECK-NEXT: ROOT {{.+}} = bf16[4,5,6,6]{3,2,1,0} reshape(%[[DOT]])
)");
}
}
} |
326 | #ifndef QUICHE_QUIC_CORE_CRYPTO_CLIENT_PROOF_SOURCE_H_
#define QUICHE_QUIC_CORE_CRYPTO_CLIENT_PROOF_SOURCE_H_
#include <memory>
#include "absl/container/flat_hash_map.h"
#include "quiche/quic/core/crypto/certificate_view.h"
#include "quiche/quic/core/crypto/proof_source.h"
namespace quic {
class QUICHE_EXPORT ClientProofSource {
public:
using Chain = ProofSource::Chain;
virtual ~ClientProofSource() {}
struct QUICHE_EXPORT CertAndKey {
CertAndKey(quiche::QuicheReferenceCountedPointer<Chain> chain,
CertificatePrivateKey private_key)
: chain(std::move(chain)), private_key(std::move(private_key)) {}
quiche::QuicheReferenceCountedPointer<Chain> chain;
CertificatePrivateKey private_key;
};
virtual std::shared_ptr<const CertAndKey> GetCertAndKey(
absl::string_view server_hostname) const = 0;
};
class QUICHE_EXPORT DefaultClientProofSource : public ClientProofSource {
public:
~DefaultClientProofSource() override {}
bool AddCertAndKey(std::vector<std::string> server_hostnames,
quiche::QuicheReferenceCountedPointer<Chain> chain,
CertificatePrivateKey private_key);
std::shared_ptr<const CertAndKey> GetCertAndKey(
absl::string_view hostname) const override;
private:
std::shared_ptr<const CertAndKey> LookupExact(
absl::string_view map_key) const;
absl::flat_hash_map<std::string, std::shared_ptr<CertAndKey>> cert_and_keys_;
};
}
#endif
#include "quiche/quic/core/crypto/client_proof_source.h"
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "absl/strings/match.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/string_view.h"
namespace quic {
bool DefaultClientProofSource::AddCertAndKey(
std::vector<std::string> server_hostnames,
quiche::QuicheReferenceCountedPointer<Chain> chain,
CertificatePrivateKey private_key) {
if (!ValidateCertAndKey(chain, private_key)) {
return false;
}
auto cert_and_key =
std::make_shared<CertAndKey>(std::move(chain), std::move(private_key));
for (const std::string& domain : server_hostnames) {
cert_and_keys_[domain] = cert_and_key;
}
return true;
}
std::shared_ptr<const ClientProofSource::CertAndKey>
DefaultClientProofSource::GetCertAndKey(absl::string_view hostname) const {
if (std::shared_ptr<const CertAndKey> result = LookupExact(hostname);
result || hostname == "*") {
return result;
}
if (hostname.size() > 1 && !absl::StartsWith(hostname, "*.")) {
auto dot_pos = hostname.find('.');
if (dot_pos != std::string::npos) {
std::string wildcard = absl::StrCat("*", hostname.substr(dot_pos));
std::shared_ptr<const CertAndKey> result = LookupExact(wildcard);
if (result != nullptr) {
return result;
}
}
}
return LookupExact("*");
}
std::shared_ptr<const ClientProofSource::CertAndKey>
DefaultClientProofSource::LookupExact(absl::string_view map_key) const {
const auto it = cert_and_keys_.find(map_key);
QUIC_DVLOG(1) << "LookupExact(" << map_key
<< ") found:" << (it != cert_and_keys_.end());
if (it != cert_and_keys_.end()) {
return it->second;
}
return nullptr;
}
} | #include "quiche/quic/core/crypto/client_proof_source.h"
#include <string>
#include "quiche/quic/platform/api/quic_expect_bug.h"
#include "quiche/quic/platform/api/quic_test.h"
#include "quiche/quic/test_tools/test_certificates.h"
namespace quic {
namespace test {
quiche::QuicheReferenceCountedPointer<ClientProofSource::Chain>
TestCertChain() {
return quiche::QuicheReferenceCountedPointer<ClientProofSource::Chain>(
new ClientProofSource::Chain({std::string(kTestCertificate)}));
}
CertificatePrivateKey TestPrivateKey() {
CBS private_key_cbs;
CBS_init(&private_key_cbs,
reinterpret_cast<const uint8_t*>(kTestCertificatePrivateKey.data()),
kTestCertificatePrivateKey.size());
return CertificatePrivateKey(
bssl::UniquePtr<EVP_PKEY>(EVP_parse_private_key(&private_key_cbs)));
}
const ClientProofSource::CertAndKey* TestCertAndKey() {
static const ClientProofSource::CertAndKey cert_and_key(TestCertChain(),
TestPrivateKey());
return &cert_and_key;
}
quiche::QuicheReferenceCountedPointer<ClientProofSource::Chain>
NullCertChain() {
return quiche::QuicheReferenceCountedPointer<ClientProofSource::Chain>();
}
quiche::QuicheReferenceCountedPointer<ClientProofSource::Chain>
EmptyCertChain() {
return quiche::QuicheReferenceCountedPointer<ClientProofSource::Chain>(
new ClientProofSource::Chain(std::vector<std::string>()));
}
quiche::QuicheReferenceCountedPointer<ClientProofSource::Chain> BadCertChain() {
return quiche::QuicheReferenceCountedPointer<ClientProofSource::Chain>(
new ClientProofSource::Chain({"This is the content of a bad cert."}));
}
CertificatePrivateKey EmptyPrivateKey() {
return CertificatePrivateKey(bssl::UniquePtr<EVP_PKEY>(EVP_PKEY_new()));
}
#define VERIFY_CERT_AND_KEY_MATCHES(lhs, rhs) \
do { \
SCOPED_TRACE(testing::Message()); \
VerifyCertAndKeyMatches(lhs.get(), rhs); \
} while (0)
void VerifyCertAndKeyMatches(const ClientProofSource::CertAndKey* lhs,
const ClientProofSource::CertAndKey* rhs) {
if (lhs == rhs) {
return;
}
if (lhs == nullptr) {
ADD_FAILURE() << "lhs is nullptr, but rhs is not";
return;
}
if (rhs == nullptr) {
ADD_FAILURE() << "rhs is nullptr, but lhs is not";
return;
}
if (1 != EVP_PKEY_cmp(lhs->private_key.private_key(),
rhs->private_key.private_key())) {
ADD_FAILURE() << "Private keys mismatch";
return;
}
const ClientProofSource::Chain* lhs_chain = lhs->chain.get();
const ClientProofSource::Chain* rhs_chain = rhs->chain.get();
if (lhs_chain == rhs_chain) {
return;
}
if (lhs_chain == nullptr) {
ADD_FAILURE() << "lhs->chain is nullptr, but rhs->chain is not";
return;
}
if (rhs_chain == nullptr) {
ADD_FAILURE() << "rhs->chain is nullptr, but lhs->chain is not";
return;
}
if (lhs_chain->certs.size() != rhs_chain->certs.size()) {
ADD_FAILURE() << "Cert chain length differ. lhs:" << lhs_chain->certs.size()
<< ", rhs:" << rhs_chain->certs.size();
return;
}
for (size_t i = 0; i < lhs_chain->certs.size(); ++i) {
if (lhs_chain->certs[i] != rhs_chain->certs[i]) {
ADD_FAILURE() << "The " << i << "-th certs differ.";
return;
}
}
}
TEST(DefaultClientProofSource, FullDomain) {
DefaultClientProofSource proof_source;
ASSERT_TRUE(proof_source.AddCertAndKey({"www.google.com"}, TestCertChain(),
TestPrivateKey()));
VERIFY_CERT_AND_KEY_MATCHES(proof_source.GetCertAndKey("www.google.com"),
TestCertAndKey());
EXPECT_EQ(proof_source.GetCertAndKey("*.google.com"), nullptr);
EXPECT_EQ(proof_source.GetCertAndKey("*"), nullptr);
}
TEST(DefaultClientProofSource, WildcardDomain) {
DefaultClientProofSource proof_source;
ASSERT_TRUE(proof_source.AddCertAndKey({"*.google.com"}, TestCertChain(),
TestPrivateKey()));
VERIFY_CERT_AND_KEY_MATCHES(proof_source.GetCertAndKey("www.google.com"),
TestCertAndKey());
VERIFY_CERT_AND_KEY_MATCHES(proof_source.GetCertAndKey("*.google.com"),
TestCertAndKey());
EXPECT_EQ(proof_source.GetCertAndKey("*"), nullptr);
}
TEST(DefaultClientProofSource, DefaultDomain) {
DefaultClientProofSource proof_source;
ASSERT_TRUE(
proof_source.AddCertAndKey({"*"}, TestCertChain(), TestPrivateKey()));
VERIFY_CERT_AND_KEY_MATCHES(proof_source.GetCertAndKey("www.google.com"),
TestCertAndKey());
VERIFY_CERT_AND_KEY_MATCHES(proof_source.GetCertAndKey("*.google.com"),
TestCertAndKey());
VERIFY_CERT_AND_KEY_MATCHES(proof_source.GetCertAndKey("*"),
TestCertAndKey());
}
TEST(DefaultClientProofSource, FullAndWildcard) {
DefaultClientProofSource proof_source;
ASSERT_TRUE(proof_source.AddCertAndKey({"www.google.com", "*.google.com"},
TestCertChain(), TestPrivateKey()));
VERIFY_CERT_AND_KEY_MATCHES(proof_source.GetCertAndKey("www.google.com"),
TestCertAndKey());
VERIFY_CERT_AND_KEY_MATCHES(proof_source.GetCertAndKey("foo.google.com"),
TestCertAndKey());
EXPECT_EQ(proof_source.GetCertAndKey("www.example.com"), nullptr);
EXPECT_EQ(proof_source.GetCertAndKey("*"), nullptr);
}
TEST(DefaultClientProofSource, FullWildcardAndDefault) {
DefaultClientProofSource proof_source;
ASSERT_TRUE(
proof_source.AddCertAndKey({"www.google.com", "*.google.com", "*"},
TestCertChain(), TestPrivateKey()));
VERIFY_CERT_AND_KEY_MATCHES(proof_source.GetCertAndKey("www.google.com"),
TestCertAndKey());
VERIFY_CERT_AND_KEY_MATCHES(proof_source.GetCertAndKey("foo.google.com"),
TestCertAndKey());
VERIFY_CERT_AND_KEY_MATCHES(proof_source.GetCertAndKey("www.example.com"),
TestCertAndKey());
VERIFY_CERT_AND_KEY_MATCHES(proof_source.GetCertAndKey("*.google.com"),
TestCertAndKey());
VERIFY_CERT_AND_KEY_MATCHES(proof_source.GetCertAndKey("*"),
TestCertAndKey());
}
TEST(DefaultClientProofSource, EmptyCerts) {
DefaultClientProofSource proof_source;
EXPECT_QUIC_BUG(ASSERT_FALSE(proof_source.AddCertAndKey(
{"*"}, NullCertChain(), TestPrivateKey())),
"Certificate chain is empty");
EXPECT_QUIC_BUG(ASSERT_FALSE(proof_source.AddCertAndKey(
{"*"}, EmptyCertChain(), TestPrivateKey())),
"Certificate chain is empty");
EXPECT_EQ(proof_source.GetCertAndKey("*"), nullptr);
}
TEST(DefaultClientProofSource, BadCerts) {
DefaultClientProofSource proof_source;
EXPECT_QUIC_BUG(ASSERT_FALSE(proof_source.AddCertAndKey({"*"}, BadCertChain(),
TestPrivateKey())),
"Unabled to parse leaf certificate");
EXPECT_EQ(proof_source.GetCertAndKey("*"), nullptr);
}
TEST(DefaultClientProofSource, KeyMismatch) {
DefaultClientProofSource proof_source;
EXPECT_QUIC_BUG(ASSERT_FALSE(proof_source.AddCertAndKey(
{"www.google.com"}, TestCertChain(), EmptyPrivateKey())),
"Private key does not match the leaf certificate");
EXPECT_EQ(proof_source.GetCertAndKey("*"), nullptr);
}
}
} |
327 | #ifndef TENSORFLOW_CORE_KERNELS_DATA_FILTER_DATASET_OP_H_
#define TENSORFLOW_CORE_KERNELS_DATA_FILTER_DATASET_OP_H_
#include "tensorflow/core/data/captured_function.h"
#include "tensorflow/core/framework/dataset.h"
namespace tensorflow {
namespace data {
class FilterDatasetOp : public UnaryDatasetOpKernel {
public:
static constexpr const char* const kDatasetType = "Filter";
static constexpr const char* const kInputDataset = "input_dataset";
static constexpr const char* const kOtherArguments = "other_arguments";
static constexpr const char* const kPredicate = "predicate";
static constexpr const char* const kTarguments = "Targuments";
static constexpr const char* const kOutputTypes = "output_types";
static constexpr const char* const kOutputShapes = "output_shapes";
explicit FilterDatasetOp(OpKernelConstruction* ctx);
protected:
void MakeDataset(OpKernelContext* ctx, DatasetBase* input,
DatasetBase** output) override;
private:
class Dataset;
std::shared_ptr<FunctionMetadata> func_metadata_ = nullptr;
};
}
}
#endif
#include "tensorflow/core/kernels/data/filter_dataset_op.h"
#include <memory>
#include <utility>
#include <vector>
#include "tensorflow/core/common_runtime/function.h"
#include "tensorflow/core/common_runtime/input_colocation_exemption_registry.h"
#include "tensorflow/core/data/dataset_utils.h"
#include "tensorflow/core/data/name_utils.h"
#include "tensorflow/core/data/stats_utils.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/partial_tensor_shape.h"
#include "tensorflow/core/framework/stats_aggregator.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/lib/gtl/cleanup.h"
#include "tensorflow/core/lib/random/random.h"
#include "tensorflow/core/lib/strings/str_util.h"
namespace tensorflow {
namespace data {
constexpr const char* const FilterDatasetOp::kDatasetType;
constexpr const char* const FilterDatasetOp::kInputDataset;
constexpr const char* const FilterDatasetOp::kOtherArguments;
constexpr const char* const FilterDatasetOp::kPredicate;
constexpr const char* const FilterDatasetOp::kTarguments;
constexpr const char* const FilterDatasetOp::kOutputTypes;
constexpr const char* const FilterDatasetOp::kOutputShapes;
constexpr char kInputImplEmpty[] = "input_impl_empty";
constexpr char kFilteredElements[] = "filtered_elements";
constexpr char kDroppedElements[] = "dropped_elements";
class FilterDatasetOp::Dataset : public DatasetBase {
public:
Dataset(OpKernelContext* ctx, const DatasetBase* input,
std::unique_ptr<CapturedFunction> captured_func)
: DatasetBase(DatasetContext(ctx)),
input_(input),
captured_func_(std::move(captured_func)) {
input_->Ref();
}
~Dataset() override { input_->Unref(); }
std::unique_ptr<IteratorBase> MakeIteratorInternal(
const string& prefix) const override {
return std::make_unique<Iterator>(Iterator::Params{
this, name_utils::IteratorPrefix(kDatasetType, prefix)});
}
const DataTypeVector& output_dtypes() const override {
return input_->output_dtypes();
}
const std::vector<PartialTensorShape>& output_shapes() const override {
return input_->output_shapes();
}
string DebugString() const override {
return name_utils::DatasetDebugString(kDatasetType);
}
Status InputDatasets(std::vector<const DatasetBase*>* inputs) const override {
inputs->push_back(input_);
return absl::OkStatus();
}
Status CheckExternalState() const override {
TF_RETURN_IF_ERROR(captured_func_->CheckExternalState());
return input_->CheckExternalState();
}
protected:
Status AsGraphDefInternal(SerializationContext* ctx,
DatasetGraphDefBuilder* b,
Node** output) const override {
Node* input_graph_node;
TF_RETURN_IF_ERROR(b->AddInputDataset(ctx, input_, &input_graph_node));
std::vector<Node*> other_arguments;
DataTypeVector other_arguments_types;
TF_RETURN_IF_ERROR(captured_func_->AddToGraph(ctx, b, &other_arguments,
&other_arguments_types));
AttrValue f;
b->BuildAttrValue(captured_func_->func(), &f);
AttrValue other_arguments_types_attr;
b->BuildAttrValue(other_arguments_types, &other_arguments_types_attr);
TF_RETURN_IF_ERROR(b->AddDataset(
this, {{0, input_graph_node}}, {{1, other_arguments}},
{{kPredicate, f}, {kTarguments, other_arguments_types_attr}}, output));
return absl::OkStatus();
}
private:
class Iterator : public DatasetIterator<Dataset> {
public:
explicit Iterator(const Params& params)
: DatasetIterator<Dataset>(params),
filtered_elements_(0),
dropped_elements_(0) {}
bool SymbolicCheckpointCompatible() const override { return true; }
Status Initialize(IteratorContext* ctx) override {
TF_RETURN_IF_ERROR(
dataset()->input_->MakeIterator(ctx, this, prefix(), &input_impl_));
return dataset()->captured_func_->Instantiate(
ctx, &instantiated_captured_func_);
}
Status GetNextInternal(IteratorContext* ctx,
std::vector<Tensor>* out_tensors,
bool* end_of_sequence) override {
auto stats_aggregator = ctx->stats_aggregator();
bool matched;
do {
{
tf_shared_lock l(mu_);
if (!input_impl_) {
*end_of_sequence = true;
return absl::OkStatus();
}
TF_RETURN_IF_ERROR(
input_impl_->GetNext(ctx, out_tensors, end_of_sequence));
}
if (*end_of_sequence) {
mutex_lock l(mu_);
input_impl_.reset();
return absl::OkStatus();
}
std::vector<Tensor> result;
auto status = instantiated_captured_func_->RunWithBorrowedArgs(
ctx, *out_tensors, &result, model_node());
if (!status.ok()) {
return AddErrorContext(status);
}
if (result.size() != 1 || result[0].dtype() != DT_BOOL ||
result[0].NumElements() != 1) {
out_tensors->clear();
return errors::InvalidArgument(
"Filter predicate `f` must return a scalar bool.");
}
matched = result[0].scalar<bool>()();
if (!matched) {
out_tensors->clear();
{
mutex_lock l(mu_);
dropped_elements_++;
}
if (stats_aggregator) {
mutex_lock l(mu_);
stats_aggregator->AddScalar(
stats_utils::DroppedElementsScalarName(dataset()->node_name()),
static_cast<float>(dropped_elements_), num_elements());
stats_aggregator->IncrementCounter(dataset()->node_name(),
stats_utils::kDroppedElements,
static_cast<float>(1));
}
}
} while (!matched);
{
mutex_lock l(mu_);
filtered_elements_++;
}
if (stats_aggregator) {
mutex_lock l(mu_);
stats_aggregator->AddScalar(
stats_utils::FilterdElementsScalarName(dataset()->node_name()),
static_cast<float>(filtered_elements_), num_elements());
stats_aggregator->IncrementCounter(dataset()->node_name(),
stats_utils::kFilteredElements,
static_cast<float>(1));
}
*end_of_sequence = false;
return absl::OkStatus();
}
protected:
std::shared_ptr<model::Node> CreateNode(
IteratorContext* ctx, model::Node::Args args) const override {
return model::MakeUnknownRatioNode(std::move(args));
}
Status SaveInternal(SerializationContext* ctx,
IteratorStateWriter* writer) override {
TF_RETURN_IF_ERROR(ctx->HandleCheckExternalStateStatus(
dataset()->captured_func_->CheckExternalState()));
mutex_lock l(mu_);
TF_RETURN_IF_ERROR(writer->WriteScalar(
prefix(), kInputImplEmpty, static_cast<int64_t>(!input_impl_)));
if (input_impl_) {
TF_RETURN_IF_ERROR(SaveInput(ctx, writer, input_impl_));
}
TF_RETURN_IF_ERROR(
writer->WriteScalar(prefix(), kFilteredElements, filtered_elements_));
TF_RETURN_IF_ERROR(
writer->WriteScalar(prefix(), kDroppedElements, dropped_elements_));
return absl::OkStatus();
}
Status RestoreInternal(IteratorContext* ctx,
IteratorStateReader* reader) override {
mutex_lock l(mu_);
int64_t input_empty;
TF_RETURN_IF_ERROR(
reader->ReadScalar(prefix(), kInputImplEmpty, &input_empty));
if (static_cast<bool>(input_empty)) {
input_impl_.reset();
} else {
TF_RETURN_IF_ERROR(RestoreInput(ctx, reader, input_impl_));
}
TF_RETURN_IF_ERROR(
reader->ReadScalar(prefix(), kFilteredElements, &filtered_elements_));
TF_RETURN_IF_ERROR(
reader->ReadScalar(prefix(), kDroppedElements, &dropped_elements_));
return absl::OkStatus();
}
data::TraceMeMetadata GetTraceMeMetadata() const override {
tf_shared_lock l(mu_);
data::TraceMeMetadata result;
result.push_back(std::make_pair(
"passed",
strings::Printf("%lld", static_cast<long long>(filtered_elements_))));
result.push_back(std::make_pair(
"filtered",
strings::Printf("%lld", static_cast<long long>(dropped_elements_))));
return result;
}
private:
mutable mutex mu_;
std::unique_ptr<IteratorBase> input_impl_ TF_GUARDED_BY(mu_);
int64_t filtered_elements_ TF_GUARDED_BY(mu_);
int64_t dropped_elements_ TF_GUARDED_BY(mu_);
std::unique_ptr<InstantiatedCapturedFunction> instantiated_captured_func_;
};
const DatasetBase* const input_;
const std::unique_ptr<CapturedFunction> captured_func_;
};
FilterDatasetOp::FilterDatasetOp(OpKernelConstruction* ctx)
: UnaryDatasetOpKernel(ctx) {
OP_REQUIRES_OK(ctx, FunctionMetadata::Create(ctx, kPredicate, {},
&func_metadata_));
OP_REQUIRES(ctx, func_metadata_->short_circuit_info().indices.size() <= 1,
errors::InvalidArgument(
"predicate function has more than one return value."));
}
void FilterDatasetOp::MakeDataset(OpKernelContext* ctx, DatasetBase* input,
DatasetBase** output) {
std::unique_ptr<CapturedFunction> captured_func;
OP_REQUIRES_OK(ctx,
CapturedFunction::Create(ctx, func_metadata_, kOtherArguments,
&captured_func));
*output = new Dataset(ctx, input, std::move(captured_func));
}
namespace {
REGISTER_KERNEL_BUILDER(Name("FilterDataset").Device(DEVICE_CPU),
FilterDatasetOp);
REGISTER_INPUT_COLOCATION_EXEMPTION("FilterDataset");
}
}
} | #include "tensorflow/core/kernels/data/filter_dataset_op.h"
#include "tensorflow/core/data/dataset_test_base.h"
namespace tensorflow {
namespace data {
namespace {
constexpr char kNodeName[] = "filter_dataset";
class FilterDatasetParams : public DatasetParams {
public:
template <typename T>
FilterDatasetParams(T input_dataset_params,
std::vector<Tensor> other_arguments,
FunctionDefHelper::AttrValueWrapper pred_func,
std::vector<FunctionDef> func_lib,
DataTypeVector type_arguments,
DataTypeVector output_dtypes,
std::vector<PartialTensorShape> output_shapes,
string node_name)
: DatasetParams(std::move(output_dtypes), std::move(output_shapes),
std::move(node_name)),
other_arguments_(std::move(other_arguments)),
pred_func_(std::move(pred_func)),
func_lib_(std::move(func_lib)),
type_arguments_(std::move(type_arguments)) {
input_dataset_params_.push_back(std::make_unique<T>(input_dataset_params));
iterator_prefix_ =
name_utils::IteratorPrefix(input_dataset_params.dataset_type(),
input_dataset_params.iterator_prefix());
}
std::vector<Tensor> GetInputTensors() const override {
return other_arguments_;
}
Status GetInputNames(std::vector<string>* input_names) const override {
input_names->clear();
input_names->reserve(input_dataset_params_.size() +
other_arguments_.size());
input_names->emplace_back(FilterDatasetOp::kInputDataset);
for (int i = 0; i < other_arguments_.size(); ++i) {
input_names->emplace_back(
absl::StrCat(FilterDatasetOp::kOtherArguments, "_", i));
}
return absl::OkStatus();
}
Status GetAttributes(AttributeVector* attr_vector) const override {
*attr_vector = {{"predicate", pred_func_},
{"Targuments", type_arguments_},
{"output_shapes", output_shapes_},
{"output_types", output_dtypes_},
{"metadata", ""}};
return absl::OkStatus();
}
std::vector<FunctionDef> func_lib() const override { return func_lib_; }
string dataset_type() const override { return FilterDatasetOp::kDatasetType; }
private:
std::vector<Tensor> other_arguments_;
FunctionDefHelper::AttrValueWrapper pred_func_;
std::vector<FunctionDef> func_lib_;
DataTypeVector type_arguments_;
};
class FilterDatasetOpTest : public DatasetOpsTestBase {};
FilterDatasetParams FilterDatasetParams1() {
auto tensor_slice_dataset_params = TensorSliceDatasetParams(
{CreateTensor<int64_t>(TensorShape{9, 1}, {0, 0, 0, 3, 4, 5, 6, 7, 8})},
"tensor_slice_dataset");
return FilterDatasetParams(
std::move(tensor_slice_dataset_params),
{},
FunctionDefHelper::FunctionRef("IsZero", {{"T", DT_INT64}}),
{test::function::IsZero()},
{},
{DT_INT64},
{PartialTensorShape({1})},
kNodeName);
}
FilterDatasetParams FilterDatasetParams2() {
auto tensor_slice_dataset_params = TensorSliceDatasetParams(
{CreateTensor<int64_t>(TensorShape{0}, {})},
"tensor_slice_dataset");
return FilterDatasetParams(
std::move(tensor_slice_dataset_params),
{},
FunctionDefHelper::FunctionRef("IsZero", {{"T", DT_INT64}}),
{test::function::IsZero()},
{},
{DT_INT64},
{PartialTensorShape({})},
kNodeName);
}
FilterDatasetParams InvalidPredFuncFilterDatasetParams1() {
auto tensor_slice_dataset_params = TensorSliceDatasetParams(
{CreateTensor<int64_t>(TensorShape{3, 3}, {0, 0, 0, 3, 4, 5, 6, 7, 8})},
"tensor_slice_dataset");
return FilterDatasetParams(
std::move(tensor_slice_dataset_params),
{},
FunctionDefHelper::FunctionRef("GetUnique",
{{"T", DT_INT64}, {"out_idx", DT_INT32}}),
{test::function::Unique()},
{},
{DT_INT64},
{PartialTensorShape({3, 1})},
kNodeName);
}
FilterDatasetParams InvalidPredFuncFilterDatasetParams2() {
auto tensor_slice_dataset_params = TensorSliceDatasetParams(
{CreateTensor<int64_t>(TensorShape{3, 3, 1},
{0, 0, 0, 3, 4, 5, 6, 7, 8})},
"tensor_slice_dataset");
return FilterDatasetParams(
std::move(tensor_slice_dataset_params),
{},
FunctionDefHelper::FunctionRef("IsZero", {{"T", DT_INT64}}),
{test::function::IsZero()},
{},
{DT_INT64},
{PartialTensorShape({3, 1})},
kNodeName);
}
FilterDatasetParams InvalidPredFuncFilterDatasetParams3() {
auto tensor_slice_dataset_params = TensorSliceDatasetParams(
{CreateTensor<int64_t>(TensorShape{9}, {0, 0, 0, 3, 4, 5, 6, 7, 8})},
"tensor_slice_dataset");
return FilterDatasetParams(
std::move(tensor_slice_dataset_params),
{},
FunctionDefHelper::FunctionRef("NonZero", {{"T", DT_INT64}}),
{test::function::NonZero()},
{},
{DT_INT64},
{PartialTensorShape({})},
kNodeName);
}
std::vector<GetNextTestCase<FilterDatasetParams>> GetNextTestCases() {
return {{FilterDatasetParams1(),
CreateTensors<int64_t>(TensorShape({1}), {{0}, {0}, {0}})},
{FilterDatasetParams2(),
{}}};
}
ITERATOR_GET_NEXT_TEST_P(FilterDatasetOpTest, FilterDatasetParams,
GetNextTestCases())
TEST_F(FilterDatasetOpTest, DatasetNodeName) {
auto dataset_params = FilterDatasetParams1();
TF_ASSERT_OK(Initialize(dataset_params));
TF_ASSERT_OK(CheckDatasetNodeName(dataset_params.node_name()));
}
TEST_F(FilterDatasetOpTest, DatasetTypeString) {
auto dataset_params = FilterDatasetParams1();
TF_ASSERT_OK(Initialize(dataset_params));
TF_ASSERT_OK(CheckDatasetTypeString(
name_utils::OpName(FilterDatasetOp::kDatasetType)));
}
TEST_F(FilterDatasetOpTest, DatasetOutputDtypes) {
auto dataset_params = FilterDatasetParams1();
TF_ASSERT_OK(Initialize(dataset_params));
TF_ASSERT_OK(CheckDatasetOutputDtypes({DT_INT64}));
}
std::vector<DatasetOutputShapesTestCase<FilterDatasetParams>>
DatasetOutputShapesTestCases() {
return {{FilterDatasetParams1(),
{PartialTensorShape({1})}},
{FilterDatasetParams2(),
{PartialTensorShape({})}}};
}
DATASET_OUTPUT_SHAPES_TEST_P(FilterDatasetOpTest, FilterDatasetParams,
DatasetOutputShapesTestCases())
std::vector<CardinalityTestCase<FilterDatasetParams>> CardinalityTestCases() {
return {{FilterDatasetParams1(),
kUnknownCardinality},
{FilterDatasetParams2(),
kUnknownCardinality}};
}
DATASET_CARDINALITY_TEST_P(FilterDatasetOpTest, FilterDatasetParams,
CardinalityTestCases())
TEST_F(FilterDatasetOpTest, IteratorOutputDtypes) {
auto dataset_params = FilterDatasetParams1();
TF_ASSERT_OK(Initialize(dataset_params));
TF_ASSERT_OK(CheckIteratorOutputDtypes({DT_INT64}));
}
std::vector<IteratorOutputShapesTestCase<FilterDatasetParams>>
IteratorOutputShapesTestCases() {
return {{FilterDatasetParams1(),
{PartialTensorShape({1})}},
{FilterDatasetParams2(),
{PartialTensorShape({})}}};
}
ITERATOR_OUTPUT_SHAPES_TEST_P(FilterDatasetOpTest, FilterDatasetParams,
IteratorOutputShapesTestCases())
TEST_F(FilterDatasetOpTest, IteratorPrefix) {
auto dataset_params = FilterDatasetParams1();
TF_ASSERT_OK(Initialize(dataset_params));
TF_ASSERT_OK(CheckIteratorPrefix(name_utils::IteratorPrefix(
FilterDatasetOp::kDatasetType, dataset_params.iterator_prefix())));
}
std::vector<IteratorSaveAndRestoreTestCase<FilterDatasetParams>>
IteratorSaveAndRestoreTestCases() {
return {{FilterDatasetParams1(),
{0, 2, 6},
CreateTensors<int64_t>(TensorShape({1}), {{0}, {0}, {0}})},
{FilterDatasetParams2(),
{0, 2, 6},
{}}};
}
ITERATOR_SAVE_AND_RESTORE_TEST_P(FilterDatasetOpTest, FilterDatasetParams,
IteratorSaveAndRestoreTestCases())
class ParameterizedInvalidPredicateFuncTest
: public FilterDatasetOpTest,
public ::testing::WithParamInterface<FilterDatasetParams> {};
TEST_P(ParameterizedInvalidPredicateFuncTest, InvalidPredicateFunc) {
auto dataset_params = GetParam();
TF_ASSERT_OK(Initialize(dataset_params));
bool end_of_sequence = false;
std::vector<Tensor> out_tensors;
EXPECT_EQ(
iterator_->GetNext(iterator_ctx_.get(), &out_tensors, &end_of_sequence)
.code(),
absl::StatusCode::kInvalidArgument);
EXPECT_TRUE(out_tensors.empty());
}
INSTANTIATE_TEST_SUITE_P(
FilterDatasetOpTest, ParameterizedInvalidPredicateFuncTest,
::testing::ValuesIn({InvalidPredFuncFilterDatasetParams1(),
InvalidPredFuncFilterDatasetParams2(),
InvalidPredFuncFilterDatasetParams3()}));
}
}
} |
328 | #ifndef TENSORFLOW_CORE_KERNELS_RANGE_SAMPLER_H_
#define TENSORFLOW_CORE_KERNELS_RANGE_SAMPLER_H_
#include <vector>
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/lib/gtl/array_slice.h"
#include "tensorflow/core/lib/random/distribution_sampler.h"
#include "tensorflow/core/lib/random/random_distributions.h"
#include "tensorflow/core/lib/random/weighted_picker.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/mutex.h"
#include "tensorflow/core/platform/thread_annotations.h"
#include "tensorflow/core/platform/types.h"
namespace tsl {
class Env;
}
namespace tensorflow {
using Env = tsl::Env;
class RangeSampler {
public:
explicit RangeSampler(int64_t range) : range_(range) { CHECK_GT(range_, 0); }
virtual ~RangeSampler();
virtual int64_t Sample(random::SimplePhilox* rnd) const = 0;
virtual float Probability(int64_t value) const = 0;
void SampleBatch(random::SimplePhilox* rnd, bool unique,
absl::Span<int64_t> batch) const;
void SampleBatchGetExpectedCount(
random::SimplePhilox* rnd, bool unique, absl::Span<int64_t> batch,
absl::Span<float> batch_expected_count, absl::Span<const int64_t> extras,
absl::Span<float> extras_expected_count) const;
virtual void SampleBatchGetExpectedCountAvoid(
random::SimplePhilox* rnd, bool unique, absl::Span<int64_t> batch,
absl::Span<float> batch_expected_count, absl::Span<const int64_t> extras,
absl::Span<float> extras_expected_count,
absl::Span<const int64_t> avoided_values) const;
virtual bool NeedsUpdates() const { return false; }
virtual void Update(absl::Span<const int64_t> values) {
LOG(FATAL) << "Update not supported for this sampler type.";
}
int64_t range() { return range_; }
protected:
const int64_t range_;
};
class AllSampler : public RangeSampler {
public:
explicit AllSampler(int64_t range);
~AllSampler() override {}
int64_t Sample(random::SimplePhilox* rnd) const override {
LOG(FATAL) << "Should not be called";
return 0;
}
float Probability(int64_t value) const override {
LOG(FATAL) << "Should not be called";
return 0;
}
void SampleBatchGetExpectedCountAvoid(
random::SimplePhilox* rnd, bool unique, absl::Span<int64_t> batch,
absl::Span<float> batch_expected_count, absl::Span<const int64_t> extras,
absl::Span<float> extras_expected_count,
absl::Span<const int64_t> avoided_values) const override;
};
class UniformSampler : public RangeSampler {
public:
explicit UniformSampler(int64_t range);
~UniformSampler() override {}
int64_t Sample(random::SimplePhilox* rnd) const override;
float Probability(int64_t value) const override;
private:
const float inv_range_;
};
class LogUniformSampler : public RangeSampler {
public:
explicit LogUniformSampler(int64_t range);
~LogUniformSampler() override {}
int64_t Sample(random::SimplePhilox* rnd) const override;
float Probability(int64_t value) const override;
private:
const double log_range_;
};
class ThreadUnsafeUnigramSampler : public RangeSampler {
public:
explicit ThreadUnsafeUnigramSampler(int64_t range);
~ThreadUnsafeUnigramSampler() override {}
int64_t Sample(random::SimplePhilox* rnd) const override;
float Probability(int64_t value) const override;
bool NeedsUpdates() const override { return true; }
void Update(absl::Span<const int64_t> values) override;
private:
random::WeightedPicker picker_;
};
class UnigramSampler : public RangeSampler {
public:
explicit UnigramSampler(int64_t range);
~UnigramSampler() override {}
int64_t Sample(random::SimplePhilox* rnd) const override;
float Probability(int64_t value) const override;
void SampleBatchGetExpectedCountAvoid(
random::SimplePhilox* rnd, bool unique, absl::Span<int64_t> batch,
absl::Span<float> batch_expected_count, absl::Span<const int64_t> extras,
absl::Span<float> extras_expected_count,
absl::Span<const int64_t> avoided_values) const override;
bool NeedsUpdates() const override { return true; }
void Update(absl::Span<const int64_t> values) override;
private:
ThreadUnsafeUnigramSampler unsafe_sampler_ TF_GUARDED_BY(mu_);
mutable mutex mu_;
};
class FixedUnigramSampler : public RangeSampler {
public:
FixedUnigramSampler(int64_t range, float distortion, int32_t num_reserved_ids,
int32_t num_shards, int32_t shard);
Status SetDistributionSampler(Env* env, const string& vocab_file);
Status SetDistributionSampler(const std::vector<float>& unigrams);
float Probability(int64_t value) const override;
int64_t Sample(random::SimplePhilox* rnd) const override;
private:
std::unique_ptr<random::DistributionSampler> dist_sampler_;
std::vector<float> weights_;
float total_weight_;
int32 num_shards_;
int32 shard_;
float distortion_;
void FillReservedIds(int32_t num_reserved_ids);
Status LoadFromFile(Env* env, const string& vocab_file, float distortion);
void LoadFromUnigrams(const std::vector<float>& unigrams, float distortion);
};
}
#endif
#include "tensorflow/core/kernels/range_sampler.h"
#include <cmath>
#include <unordered_set>
#include <vector>
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/gtl/map_util.h"
#include "tensorflow/core/lib/io/inputbuffer.h"
#include "tensorflow/core/lib/strings/numbers.h"
#include "tensorflow/core/lib/strings/str_util.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/mutex.h"
#include "tensorflow/core/platform/types.h"
namespace tensorflow {
using gtl::ArraySlice;
using gtl::MutableArraySlice;
RangeSampler::~RangeSampler() {}
void RangeSampler::SampleBatch(random::SimplePhilox* rnd, bool unique,
absl::Span<int64_t> batch) const {
SampleBatchGetExpectedCount(rnd, unique, batch, absl::Span<float>(),
absl::Span<const int64_t>(), absl::Span<float>());
}
void RangeSampler::SampleBatchGetExpectedCount(
random::SimplePhilox* rnd, bool unique, absl::Span<int64_t> batch,
absl::Span<float> batch_expected_count, absl::Span<const int64_t> extras,
absl::Span<float> extras_expected_count) const {
SampleBatchGetExpectedCountAvoid(rnd, unique, batch, batch_expected_count,
extras, extras_expected_count,
absl::Span<const int64_t>());
}
namespace {
static float ExpectedCountHelper(float p, int batch_size, int num_tries) {
if (num_tries == batch_size) {
return p * batch_size;
}
return -std::expm1(num_tries * std::log1p(-p));
}
}
void RangeSampler::SampleBatchGetExpectedCountAvoid(
random::SimplePhilox* rnd, bool unique, absl::Span<int64_t> batch,
absl::Span<float> batch_expected_count, absl::Span<const int64_t> extras,
absl::Span<float> extras_expected_count,
absl::Span<const int64_t> avoided_values) const {
const int batch_size = batch.size();
int num_tries;
if (unique) {
CHECK_LE(static_cast<int64_t>(batch_size + avoided_values.size()), range_);
std::unordered_set<int64_t> used(batch_size);
used.insert(avoided_values.begin(), avoided_values.end());
int num_picked = 0;
num_tries = 0;
while (num_picked < batch_size) {
num_tries++;
CHECK_LT(num_tries, kint32max);
int64_t value = Sample(rnd);
if (gtl::InsertIfNotPresent(&used, value)) {
batch[num_picked++] = value;
}
}
} else {
CHECK_EQ(avoided_values.size(), size_t{0})
<< "avoided_values only supported with unique=true";
for (int i = 0; i < batch_size; i++) {
batch[i] = Sample(rnd);
}
num_tries = batch_size;
}
if (!batch_expected_count.empty()) {
CHECK_EQ(batch_size, batch_expected_count.size());
for (int i = 0; i < batch_size; i++) {
batch_expected_count[i] =
ExpectedCountHelper(Probability(batch[i]), batch_size, num_tries);
}
}
CHECK_EQ(extras.size(), extras_expected_count.size());
for (size_t i = 0; i < extras.size(); i++) {
extras_expected_count[i] =
ExpectedCountHelper(Probability(extras[i]), batch_size, num_tries);
}
}
AllSampler::AllSampler(int64_t range) : RangeSampler(range) {}
void AllSampler::SampleBatchGetExpectedCountAvoid(
random::SimplePhilox* rnd, bool unique, absl::Span<int64_t> batch,
absl::Span<float> batch_expected_count, absl::Span<const int64_t> extras,
absl::Span<float> extras_expected_count,
absl::Span<const int64_t> avoided_values) const {
const int batch_size = batch.size();
CHECK_EQ(range_, batch_size);
for (int i = 0; i < batch_size; i++) {
batch[i] = i;
}
if (!batch_expected_count.empty()) {
CHECK_EQ(batch_size, batch_expected_count.size());
for (int i = 0; i < batch_size; i++) {
batch_expected_count[i] = 1;
}
}
CHECK_EQ(size_t{0}, avoided_values.size());
CHECK_EQ(extras.size(), extras_expected_count.size());
for (size_t i = 0; i < extras.size(); i++) {
extras_expected_count[i] = 1;
}
}
UniformSampler::UniformSampler(int64_t range)
: RangeSampler(range), inv_range_(1.0 / range) {}
int64_t UniformSampler::Sample(random::SimplePhilox* rnd) const {
return rnd->Uniform64(range_);
}
float UniformSampler::Probability(int64_t value) const { return inv_range_; }
LogUniformSampler::LogUniformSampler(int64_t range)
: RangeSampler(range), log_range_(log1p(range)) {}
int64_t LogUniformSampler::Sample(random::SimplePhilox* rnd) const {
const int64_t value =
static_cast<int64_t>(exp(rnd->RandDouble() * log_range_)) - 1;
DCHECK_GE(value, 0);
return value % range_;
}
float LogUniformSampler::Probability(int64_t value) const {
return (log((value + 2.0) / (value + 1.0))) / log_range_;
}
ThreadUnsafeUnigramSampler::ThreadUnsafeUnigramSampler(int64_t range)
: RangeSampler(range), picker_(range) {
CHECK_LT(range, kint32max);
}
int64_t ThreadUnsafeUnigramSampler::Sample(random::SimplePhilox* rnd) const {
return picker_.Pick(rnd);
}
float ThreadUnsafeUnigramSampler::Probability(int64_t value) const {
return static_cast<float>(picker_.get_weight(value)) / picker_.total_weight();
}
void ThreadUnsafeUnigramSampler::Update(absl::Span<const int64_t> values) {
int num_updates = std::min(static_cast<int>(values.size()),
kint32max - picker_.total_weight());
for (int i = 0; i < num_updates; i++) {
const int64_t value = values[i];
picker_.set_weight(value, picker_.get_weight(value) + 1);
}
}
UnigramSampler::UnigramSampler(int64_t range)
: RangeSampler(range), unsafe_sampler_(range) {
CHECK_LT(range, kint32max);
}
int64_t UnigramSampler::Sample(random::SimplePhilox* rnd) const {
tf_shared_lock lock(mu_);
return unsafe_sampler_.Sample(rnd);
}
float UnigramSampler::Probability(int64_t value) const {
tf_shared_lock lock(mu_);
return unsafe_sampler_.Probability(value);
}
void UnigramSampler::SampleBatchGetExpectedCountAvoid(
random::SimplePhilox* rnd, bool unique, absl::Span<int64_t> batch,
absl::Span<float> batch_expected_count, absl::Span<const int64_t> extras,
absl::Span<float> extras_expected_count,
absl::Span<const int64_t> avoided_values) const {
tf_shared_lock lock(mu_);
unsafe_sampler_.SampleBatchGetExpectedCountAvoid(
rnd, unique, batch, batch_expected_count, extras, extras_expected_count,
avoided_values);
}
void UnigramSampler::Update(absl::Span<const int64_t> values) {
mutex_lock lock(mu_);
unsafe_sampler_.Update(values);
}
FixedUnigramSampler::FixedUnigramSampler(int64_t range, float distortion,
int32_t num_reserved_ids,
int32_t num_shards, int32_t shard)
: RangeSampler(range),
total_weight_(0.0),
num_shards_(num_shards),
shard_(shard),
distortion_(distortion) {
FillReservedIds(num_reserved_ids);
}
Status FixedUnigramSampler::SetDistributionSampler(Env* env,
const string& vocab_file) {
TF_RETURN_IF_ERROR(LoadFromFile(env, vocab_file, distortion_));
if (!TF_PREDICT_TRUE(FixedUnigramSampler::range() == weights_.size()))
return (errors::InvalidArgument("range is ", FixedUnigramSampler::range(),
" must be equal to weights size ",
weights_.size()));
dist_sampler_.reset(new random::DistributionSampler(weights_));
return absl::OkStatus();
}
Status FixedUnigramSampler::SetDistributionSampler(
const std::vector<float>& unigrams) {
LoadFromUnigrams(unigrams, distortion_);
if (!TF_PREDICT_TRUE(FixedUnigramSampler::range() == weights_.size()))
return (errors::InvalidArgument("range is ", FixedUnigramSampler::range(),
" must be equal to weights size ",
weights_.size()));
dist_sampler_.reset(new random::DistributionSampler(weights_));
return absl::OkStatus();
}
float FixedUnigramSampler::Probability(int64_t value) const {
if (value < 0 || static_cast<size_t>(value) >= weights_.size()) {
return 0.0;
}
return weights_.at(value) / total_weight_;
}
int64_t FixedUnigramSampler::Sample(random::SimplePhilox* rnd) const {
return dist_sampler_->Sample(rnd);
}
void FixedUnigramSampler::FillReservedIds(int32_t num_reserved_ids) {
for (int32_t word_id = 0; word_id < num_reserved_ids; ++word_id) {
if (word_id % num_shards_ == shard_) weights_.push_back(0.0);
}
}
Status FixedUnigramSampler::LoadFromFile(Env* env, const string& vocab_file,
float distortion) {
std::unique_ptr<RandomAccessFile> file;
TF_RETURN_IF_ERROR(env->NewRandomAccessFile(vocab_file, &file));
io::InputBuffer in(file.get(), 262144 );
string line;
int32_t word_id = weights_.size();
while (in.ReadLine(&line).ok()) {
std::vector<string> cols = str_util::Split(line, ',');
if (cols.empty()) continue;
if (word_id % num_shards_ == shard_) {
float w = 0.0;
if (!strings::safe_strtof(cols.at(cols.size() - 1), &w)) {
return errors::InvalidArgument("Wrong vocabulary format at line: ",
line);
}
w = std::pow(w, distortion);
total_weight_ += w;
weights_.push_back(w);
}
++word_id;
}
return absl::OkStatus();
}
void FixedUnigramSampler::LoadFromUnigrams(const std::vector<float>& unigrams,
float distortion) {
int32_t word_id = weights_.size();
for (float w : unigrams) {
if (word_id % num_shards_ == shard_) {
w = std::pow(w, distortion);
total_weight_ += w;
weights_.push_back(w);
}
++word_id;
}
}
} | #include "tensorflow/core/kernels/range_sampler.h"
#include <vector>
#include "absl/status/status.h"
#include "tensorflow/core/lib/core/status_test_util.h"
#include "tensorflow/core/lib/io/path.h"
#include "tensorflow/core/lib/random/simple_philox.h"
#include "tensorflow/core/platform/env.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/test.h"
namespace tensorflow {
namespace {
using gtl::ArraySlice;
using gtl::MutableArraySlice;
class RangeSamplerTest : public ::testing::Test {
protected:
void CheckProbabilitiesSumToOne() {
double sum = 0;
for (int i = 0; i < sampler_->range(); i++) {
sum += sampler_->Probability(i);
}
EXPECT_NEAR(sum, 1.0, 1e-4);
}
void CheckHistogram(int num_samples, float tolerance) {
const int range = sampler_->range();
std::vector<int> h(range);
std::vector<int64_t> a(num_samples);
random::PhiloxRandom philox(123, 17);
random::SimplePhilox rnd(&philox);
sampler_->SampleBatch(&rnd, false, absl::MakeSpan(a));
for (int i = 0; i < num_samples; i++) {
int64_t val = a[i];
ASSERT_GE(val, 0);
ASSERT_LT(val, range);
h[val]++;
}
for (int val = 0; val < range; val++) {
EXPECT_NEAR((h[val] + 0.0) / num_samples, sampler_->Probability(val),
tolerance);
}
}
void Update1() {
std::vector<int64_t> a(10);
for (int i = 0; i < 10; i++) {
a[i] = 3;
}
sampler_->Update(a);
}
void Update2() {
int64_t a[10];
for (int i = 0; i < 10; i++) {
a[i] = i;
}
for (int64_t i = 1; i < 10; i++) {
sampler_->Update(absl::Span<const int64_t>(a + i, 10 - i));
}
}
std::unique_ptr<RangeSampler> sampler_;
};
TEST_F(RangeSamplerTest, UniformProbabilities) {
sampler_.reset(new UniformSampler(10));
for (int i = 0; i < 10; i++) {
CHECK_EQ(sampler_->Probability(i), sampler_->Probability(0));
}
}
TEST_F(RangeSamplerTest, UniformChecksum) {
sampler_.reset(new UniformSampler(10));
CheckProbabilitiesSumToOne();
}
TEST_F(RangeSamplerTest, UniformHistogram) {
sampler_.reset(new UniformSampler(10));
CheckHistogram(1000, 0.05);
}
TEST_F(RangeSamplerTest, LogUniformProbabilities) {
int range = 1000000;
sampler_.reset(new LogUniformSampler(range));
for (int i = 100; i < range; i *= 2) {
float ratio = sampler_->Probability(i) / sampler_->Probability(i / 2);
EXPECT_NEAR(ratio, 0.5, 0.1);
}
}
TEST_F(RangeSamplerTest, LogUniformChecksum) {
sampler_.reset(new LogUniformSampler(10));
CheckProbabilitiesSumToOne();
}
TEST_F(RangeSamplerTest, LogUniformHistogram) {
sampler_.reset(new LogUniformSampler(10));
CheckHistogram(1000, 0.05);
}
TEST_F(RangeSamplerTest, UnigramProbabilities1) {
sampler_.reset(new UnigramSampler(10));
Update1();
EXPECT_NEAR(sampler_->Probability(3), 0.55, 1e-4);
for (int i = 0; i < 10; i++) {
if (i != 3) {
ASSERT_NEAR(sampler_->Probability(i), 0.05, 1e-4);
}
}
}
TEST_F(RangeSamplerTest, UnigramProbabilities2) {
sampler_.reset(new UnigramSampler(10));
Update2();
for (int i = 0; i < 10; i++) {
ASSERT_NEAR(sampler_->Probability(i), (i + 1) / 55.0, 1e-4);
}
}
TEST_F(RangeSamplerTest, UnigramChecksum) {
sampler_.reset(new UnigramSampler(10));
Update1();
CheckProbabilitiesSumToOne();
}
TEST_F(RangeSamplerTest, UnigramHistogram) {
sampler_.reset(new UnigramSampler(10));
Update1();
CheckHistogram(1000, 0.05);
}
static const char kVocabContent[] =
"w1,1\n"
"w2,2\n"
"w3,4\n"
"w4,8\n"
"w5,16\n"
"w6,32\n"
"w7,64\n"
"w8,128\n"
"w9,256";
TEST_F(RangeSamplerTest, FixedUnigramProbabilities) {
Env* env = Env::Default();
string fname = io::JoinPath(testing::TmpDir(), "vocab_file");
TF_CHECK_OK(WriteStringToFile(env, fname, kVocabContent));
FixedUnigramSampler* test_sampler = new FixedUnigramSampler(9, 0.8, 0, 1, 0);
TF_CHECK_OK(test_sampler->SetDistributionSampler(env, fname));
sampler_.reset(test_sampler);
for (int i = 0; i < 9; i++) {
ASSERT_NEAR(sampler_->Probability(i), pow(2, i * 0.8) / 197.05, 1e-4);
}
}
TEST_F(RangeSamplerTest, FixedUnigramNoExistingFilename) {
Env* env = Env::Default();
string fname = "NoExistingFile";
FixedUnigramSampler* test_sampler = new FixedUnigramSampler(9, 0.8, 0, 1, 0);
Status s = test_sampler->SetDistributionSampler(env, fname);
sampler_.reset(test_sampler);
EXPECT_TRUE(absl::IsNotFound(s)) << s;
}
TEST_F(RangeSamplerTest, FixedUnigramNoMatchingRangeWeights) {
Env* env = Env::Default();
string fname = io::JoinPath(testing::TmpDir(), "vocab_file");
TF_CHECK_OK(WriteStringToFile(env, fname, kVocabContent));
FixedUnigramSampler* test_sampler = new FixedUnigramSampler(8, 0.8, 0, 1, 0);
Status s = test_sampler->SetDistributionSampler(env, fname);
sampler_.reset(test_sampler);
EXPECT_TRUE(absl::IsInvalidArgument(s)) << s;
}
TEST_F(RangeSamplerTest, FixedUnigramChecksum) {
Env* env = Env::Default();
string fname = io::JoinPath(testing::TmpDir(), "vocab_file");
TF_CHECK_OK(WriteStringToFile(env, fname, kVocabContent));
FixedUnigramSampler* test_sampler = new FixedUnigramSampler(9, 0.8, 0, 1, 0);
TF_CHECK_OK(test_sampler->SetDistributionSampler(env, fname));
sampler_.reset(test_sampler);
CheckProbabilitiesSumToOne();
}
TEST_F(RangeSamplerTest, FixedUnigramHistogram) {
Env* env = Env::Default();
string fname = io::JoinPath(testing::TmpDir(), "vocab_file");
TF_CHECK_OK(WriteStringToFile(env, fname, kVocabContent));
FixedUnigramSampler* test_sampler = new FixedUnigramSampler(9, 0.8, 0, 1, 0);
TF_CHECK_OK(test_sampler->SetDistributionSampler(env, fname));
sampler_.reset(test_sampler);
CheckHistogram(1000, 0.05);
}
TEST_F(RangeSamplerTest, FixedUnigramProbabilitiesReserve1) {
Env* env = Env::Default();
string fname = io::JoinPath(testing::TmpDir(), "vocab_file");
TF_CHECK_OK(WriteStringToFile(env, fname, kVocabContent));
FixedUnigramSampler* test_sampler = new FixedUnigramSampler(10, 0.8, 1, 1, 0);
TF_CHECK_OK(test_sampler->SetDistributionSampler(env, fname));
sampler_.reset(test_sampler);
ASSERT_NEAR(sampler_->Probability(0), 0, 1e-4);
for (int i = 1; i < 10; i++) {
ASSERT_NEAR(sampler_->Probability(i), pow(2, (i - 1) * 0.8) / 197.05, 1e-4);
}
}
TEST_F(RangeSamplerTest, FixedUnigramProbabilitiesReserve2) {
Env* env = Env::Default();
string fname = io::JoinPath(testing::TmpDir(), "vocab_file");
TF_CHECK_OK(WriteStringToFile(env, fname, kVocabContent));
FixedUnigramSampler* test_sampler = new FixedUnigramSampler(11, 0.8, 2, 1, 0);
TF_CHECK_OK(test_sampler->SetDistributionSampler(env, fname));
sampler_.reset(test_sampler);
ASSERT_NEAR(sampler_->Probability(0), 0, 1e-4);
ASSERT_NEAR(sampler_->Probability(1), 0, 1e-4);
for (int i = 2; i < 11; i++) {
ASSERT_NEAR(sampler_->Probability(i), pow(2, (i - 2) * 0.8) / 197.05, 1e-4);
}
}
TEST_F(RangeSamplerTest, FixedUnigramProbabilitiesFromVector) {
std::vector<float> weights = {1, 2, 4, 8, 16, 32, 64, 128, 256};
FixedUnigramSampler* test_sampler = new FixedUnigramSampler(9, 0.8, 0, 1, 0);
TF_CHECK_OK(test_sampler->SetDistributionSampler(weights));
sampler_.reset(test_sampler);
for (int i = 0; i < 9; i++) {
ASSERT_NEAR(sampler_->Probability(i), pow(2, i * 0.8) / 197.05, 1e-4);
}
}
TEST_F(RangeSamplerTest, FixedUnigramChecksumFromVector) {
std::vector<float> weights = {1, 2, 4, 8, 16, 32, 64, 128, 256};
FixedUnigramSampler* test_sampler = new FixedUnigramSampler(9, 0.8, 0, 1, 0);
TF_CHECK_OK(test_sampler->SetDistributionSampler(weights));
sampler_.reset(test_sampler);
CheckProbabilitiesSumToOne();
}
TEST_F(RangeSamplerTest, FixedUnigramHistogramFromVector) {
std::vector<float> weights = {1, 2, 4, 8, 16, 32, 64, 128, 256};
FixedUnigramSampler* test_sampler = new FixedUnigramSampler(9, 0.8, 0, 1, 0);
TF_CHECK_OK(test_sampler->SetDistributionSampler(weights));
sampler_.reset(test_sampler);
CheckHistogram(1000, 0.05);
}
TEST_F(RangeSamplerTest, FixedUnigramProbabilitiesReserve1FromVector) {
std::vector<float> weights = {1, 2, 4, 8, 16, 32, 64, 128, 256};
FixedUnigramSampler* test_sampler = new FixedUnigramSampler(10, 0.8, 1, 1, 0);
TF_CHECK_OK(test_sampler->SetDistributionSampler(weights));
sampler_.reset(test_sampler);
ASSERT_NEAR(sampler_->Probability(0), 0, 1e-4);
for (int i = 1; i < 10; i++) {
ASSERT_NEAR(sampler_->Probability(i), pow(2, (i - 1) * 0.8) / 197.05, 1e-4);
}
}
TEST_F(RangeSamplerTest, FixedUnigramProbabilitiesReserve2FromVector) {
std::vector<float> weights = {1, 2, 4, 8, 16, 32, 64, 128, 256};
FixedUnigramSampler* test_sampler = new FixedUnigramSampler(11, 0.8, 2, 1, 0);
TF_CHECK_OK(test_sampler->SetDistributionSampler(weights));
sampler_.reset(test_sampler);
ASSERT_NEAR(sampler_->Probability(0), 0, 1e-4);
ASSERT_NEAR(sampler_->Probability(1), 0, 1e-4);
for (int i = 2; i < 11; i++) {
ASSERT_NEAR(sampler_->Probability(i), pow(2, (i - 2) * 0.8) / 197.05, 1e-4);
}
}
TEST_F(RangeSamplerTest, All) {
int batch_size = 10;
sampler_.reset(new AllSampler(10));
std::vector<int64_t> batch(batch_size);
std::vector<float> batch_expected(batch_size);
std::vector<int64_t> extras(2);
std::vector<float> extras_expected(2);
extras[0] = 0;
extras[1] = batch_size - 1;
sampler_->SampleBatchGetExpectedCount(nullptr,
false, absl::MakeSpan(batch),
absl::MakeSpan(batch_expected), extras,
absl::MakeSpan(extras_expected));
for (int i = 0; i < batch_size; i++) {
EXPECT_EQ(i, batch[i]);
EXPECT_EQ(1, batch_expected[i]);
}
EXPECT_EQ(1, extras_expected[0]);
EXPECT_EQ(1, extras_expected[1]);
}
TEST_F(RangeSamplerTest, Unique) {
random::PhiloxRandom philox(123, 17);
random::SimplePhilox rnd(&philox);
const int range = 100;
const int batch_size = 50;
const int num_batches = 100;
sampler_.reset(new LogUniformSampler(range));
std::vector<int> histogram(range);
std::vector<int64_t> batch(batch_size);
std::vector<int64_t> all_values(range);
for (int i = 0; i < range; i++) {
all_values[i] = i;
}
std::vector<float> expected(range);
sampler_->SampleBatchGetExpectedCount(&rnd, true, absl::MakeSpan(batch),
absl::Span<float>(), all_values,
absl::MakeSpan(expected));
std::set<int64_t> s(batch.begin(), batch.end());
CHECK_EQ(batch_size, s.size());
for (int trial = 0; trial < num_batches; trial++) {
std::vector<float> trial_expected(range);
sampler_->SampleBatchGetExpectedCount(&rnd, true, absl::MakeSpan(batch),
absl::Span<float>(), all_values,
absl::MakeSpan(trial_expected));
for (int i = 0; i < range; i++) {
EXPECT_NEAR(expected[i], trial_expected[i], expected[i] * 0.5);
}
for (int i = 0; i < batch_size; i++) {
histogram[batch[i]]++;
}
}
for (int i = 0; i < range; i++) {
const float average_count = static_cast<float>(histogram[i]) / num_batches;
EXPECT_NEAR(expected[i], average_count, 0.2);
}
}
TEST_F(RangeSamplerTest, Avoid) {
random::PhiloxRandom philox(123, 17);
random::SimplePhilox rnd(&philox);
sampler_.reset(new LogUniformSampler(100));
std::vector<int64_t> avoided(2);
avoided[0] = 17;
avoided[1] = 23;
std::vector<int64_t> batch(98);
sampler_->SampleBatchGetExpectedCountAvoid(
&rnd, true, absl::MakeSpan(batch), absl::Span<float>(),
absl::Span<const int64_t>(), absl::Span<float>(), avoided);
int sum = 0;
for (auto val : batch) {
sum += val;
}
const int expected_sum = 100 * 99 / 2 - avoided[0] - avoided[1];
EXPECT_EQ(expected_sum, sum);
}
}
} |
329 | #ifndef QUICHE_QUIC_CORE_QUIC_CRYPTO_CLIENT_STREAM_H_
#define QUICHE_QUIC_CORE_QUIC_CRYPTO_CLIENT_STREAM_H_
#include <cstdint>
#include <memory>
#include <string>
#include "quiche/quic/core/crypto/proof_verifier.h"
#include "quiche/quic/core/crypto/quic_crypto_client_config.h"
#include "quiche/quic/core/proto/cached_network_parameters_proto.h"
#include "quiche/quic/core/quic_config.h"
#include "quiche/quic/core/quic_crypto_handshaker.h"
#include "quiche/quic/core/quic_crypto_stream.h"
#include "quiche/quic/core/quic_server_id.h"
#include "quiche/quic/core/quic_session.h"
#include "quiche/quic/core/quic_types.h"
#include "quiche/quic/core/quic_versions.h"
#include "quiche/quic/platform/api/quic_export.h"
namespace quic {
namespace test {
class QuicCryptoClientStreamPeer;
}
class TlsClientHandshaker;
class QUICHE_EXPORT QuicCryptoClientStreamBase : public QuicCryptoStream {
public:
explicit QuicCryptoClientStreamBase(QuicSession* session);
~QuicCryptoClientStreamBase() override {}
virtual bool CryptoConnect() = 0;
virtual int num_sent_client_hellos() const = 0;
virtual bool ResumptionAttempted() const = 0;
virtual bool IsResumption() const = 0;
virtual bool EarlyDataAccepted() const = 0;
virtual bool ReceivedInchoateReject() const = 0;
virtual int num_scup_messages_received() const = 0;
bool ExportKeyingMaterial(absl::string_view ,
absl::string_view ,
size_t ,
std::string* ) override {
QUICHE_NOTREACHED();
return false;
}
std::string GetAddressToken(
const CachedNetworkParameters* ) const override {
QUICHE_DCHECK(false);
return "";
}
bool ValidateAddressToken(absl::string_view ) const override {
QUICHE_DCHECK(false);
return false;
}
const CachedNetworkParameters* PreviousCachedNetworkParams() const override {
QUICHE_DCHECK(false);
return nullptr;
}
void SetPreviousCachedNetworkParams(
CachedNetworkParameters ) override {
QUICHE_DCHECK(false);
}
};
class QUICHE_EXPORT QuicCryptoClientStream : public QuicCryptoClientStreamBase {
public:
static const int kMaxClientHellos = 4;
class QUICHE_EXPORT HandshakerInterface {
public:
virtual ~HandshakerInterface() {}
virtual bool CryptoConnect() = 0;
virtual int num_sent_client_hellos() const = 0;
virtual bool ResumptionAttempted() const = 0;
virtual bool IsResumption() const = 0;
virtual bool EarlyDataAccepted() const = 0;
virtual ssl_early_data_reason_t EarlyDataReason() const = 0;
virtual bool ReceivedInchoateReject() const = 0;
virtual int num_scup_messages_received() const = 0;
virtual std::string chlo_hash() const = 0;
virtual bool encryption_established() const = 0;
virtual bool IsCryptoFrameExpectedForEncryptionLevel(
EncryptionLevel level) const = 0;
virtual EncryptionLevel GetEncryptionLevelToSendCryptoDataOfSpace(
PacketNumberSpace space) const = 0;
virtual bool one_rtt_keys_available() const = 0;
virtual const QuicCryptoNegotiatedParameters& crypto_negotiated_params()
const = 0;
virtual CryptoMessageParser* crypto_message_parser() = 0;
virtual size_t BufferSizeLimitForLevel(EncryptionLevel level) const = 0;
virtual std::unique_ptr<QuicDecrypter>
AdvanceKeysAndCreateCurrentOneRttDecrypter() = 0;
virtual std::unique_ptr<QuicEncrypter> CreateCurrentOneRttEncrypter() = 0;
virtual HandshakeState GetHandshakeState() const = 0;
virtual void OnOneRttPacketAcknowledged() = 0;
virtual void OnHandshakePacketSent() = 0;
virtual void OnConnectionClosed(QuicErrorCode error,
ConnectionCloseSource source) = 0;
virtual void OnHandshakeDoneReceived() = 0;
virtual void OnNewTokenReceived(absl::string_view token) = 0;
virtual void SetServerApplicationStateForResumption(
std::unique_ptr<ApplicationState> application_state) = 0;
virtual bool ExportKeyingMaterial(absl::string_view label,
absl::string_view context,
size_t result_len,
std::string* result) = 0;
};
class QUICHE_EXPORT ProofHandler {
public:
virtual ~ProofHandler() {}
virtual void OnProofValid(
const QuicCryptoClientConfig::CachedState& cached) = 0;
virtual void OnProofVerifyDetailsAvailable(
const ProofVerifyDetails& verify_details) = 0;
};
QuicCryptoClientStream(const QuicServerId& server_id, QuicSession* session,
std::unique_ptr<ProofVerifyContext> verify_context,
QuicCryptoClientConfig* crypto_config,
ProofHandler* proof_handler,
bool has_application_state);
QuicCryptoClientStream(const QuicCryptoClientStream&) = delete;
QuicCryptoClientStream& operator=(const QuicCryptoClientStream&) = delete;
~QuicCryptoClientStream() override;
bool CryptoConnect() override;
int num_sent_client_hellos() const override;
bool ResumptionAttempted() const override;
bool IsResumption() const override;
bool EarlyDataAccepted() const override;
ssl_early_data_reason_t EarlyDataReason() const override;
bool ReceivedInchoateReject() const override;
int num_scup_messages_received() const override;
bool encryption_established() const override;
bool one_rtt_keys_available() const override;
const QuicCryptoNegotiatedParameters& crypto_negotiated_params()
const override;
CryptoMessageParser* crypto_message_parser() override;
void OnPacketDecrypted(EncryptionLevel ) override {}
void OnOneRttPacketAcknowledged() override;
void OnHandshakePacketSent() override;
void OnConnectionClosed(const QuicConnectionCloseFrame& frame,
ConnectionCloseSource source) override;
void OnHandshakeDoneReceived() override;
void OnNewTokenReceived(absl::string_view token) override;
HandshakeState GetHandshakeState() const override;
void SetServerApplicationStateForResumption(
std::unique_ptr<ApplicationState> application_state) override;
size_t BufferSizeLimitForLevel(EncryptionLevel level) const override;
std::unique_ptr<QuicDecrypter> AdvanceKeysAndCreateCurrentOneRttDecrypter()
override;
std::unique_ptr<QuicEncrypter> CreateCurrentOneRttEncrypter() override;
SSL* GetSsl() const override;
bool IsCryptoFrameExpectedForEncryptionLevel(
EncryptionLevel level) const override;
EncryptionLevel GetEncryptionLevelToSendCryptoDataOfSpace(
PacketNumberSpace space) const override;
bool ExportKeyingMaterial(absl::string_view label, absl::string_view context,
size_t result_len, std::string* result) override;
std::string chlo_hash() const;
protected:
void set_handshaker(std::unique_ptr<HandshakerInterface> handshaker) {
handshaker_ = std::move(handshaker);
}
private:
friend class test::QuicCryptoClientStreamPeer;
std::unique_ptr<HandshakerInterface> handshaker_;
TlsClientHandshaker* tls_handshaker_{nullptr};
};
}
#endif
#include "quiche/quic/core/quic_crypto_client_stream.h"
#include <memory>
#include <string>
#include <utility>
#include "quiche/quic/core/crypto/crypto_protocol.h"
#include "quiche/quic/core/crypto/crypto_utils.h"
#include "quiche/quic/core/crypto/null_encrypter.h"
#include "quiche/quic/core/crypto/quic_crypto_client_config.h"
#include "quiche/quic/core/quic_crypto_client_handshaker.h"
#include "quiche/quic/core/quic_packets.h"
#include "quiche/quic/core/quic_session.h"
#include "quiche/quic/core/quic_utils.h"
#include "quiche/quic/core/tls_client_handshaker.h"
#include "quiche/quic/platform/api/quic_flags.h"
#include "quiche/quic/platform/api/quic_logging.h"
namespace quic {
const int QuicCryptoClientStream::kMaxClientHellos;
QuicCryptoClientStreamBase::QuicCryptoClientStreamBase(QuicSession* session)
: QuicCryptoStream(session) {}
QuicCryptoClientStream::QuicCryptoClientStream(
const QuicServerId& server_id, QuicSession* session,
std::unique_ptr<ProofVerifyContext> verify_context,
QuicCryptoClientConfig* crypto_config, ProofHandler* proof_handler,
bool has_application_state)
: QuicCryptoClientStreamBase(session) {
QUICHE_DCHECK_EQ(Perspective::IS_CLIENT,
session->connection()->perspective());
switch (session->connection()->version().handshake_protocol) {
case PROTOCOL_QUIC_CRYPTO:
handshaker_ = std::make_unique<QuicCryptoClientHandshaker>(
server_id, this, session, std::move(verify_context), crypto_config,
proof_handler);
break;
case PROTOCOL_TLS1_3: {
auto handshaker = std::make_unique<TlsClientHandshaker>(
server_id, this, session, std::move(verify_context), crypto_config,
proof_handler, has_application_state);
tls_handshaker_ = handshaker.get();
handshaker_ = std::move(handshaker);
break;
}
case PROTOCOL_UNSUPPORTED:
QUIC_BUG(quic_bug_10296_1)
<< "Attempting to create QuicCryptoClientStream for unknown "
"handshake protocol";
}
}
QuicCryptoClientStream::~QuicCryptoClientStream() {}
bool QuicCryptoClientStream::CryptoConnect() {
return handshaker_->CryptoConnect();
}
int QuicCryptoClientStream::num_sent_client_hellos() const {
return handshaker_->num_sent_client_hellos();
}
bool QuicCryptoClientStream::ResumptionAttempted() const {
return handshaker_->ResumptionAttempted();
}
bool QuicCryptoClientStream::IsResumption() const {
return handshaker_->IsResumption();
}
bool QuicCryptoClientStream::EarlyDataAccepted() const {
return handshaker_->EarlyDataAccepted();
}
ssl_early_data_reason_t QuicCryptoClientStream::EarlyDataReason() const {
return handshaker_->EarlyDataReason();
}
bool QuicCryptoClientStream::ReceivedInchoateReject() const {
return handshaker_->ReceivedInchoateReject();
}
int QuicCryptoClientStream::num_scup_messages_received() const {
return handshaker_->num_scup_messages_received();
}
bool QuicCryptoClientStream::encryption_established() const {
return handshaker_->encryption_established();
}
bool QuicCryptoClientStream::one_rtt_keys_available() const {
return handshaker_->one_rtt_keys_available();
}
const QuicCryptoNegotiatedParameters&
QuicCryptoClientStream::crypto_negotiated_params() const {
return handshaker_->crypto_negotiated_params();
}
CryptoMessageParser* QuicCryptoClientStream::crypto_message_parser() {
return handshaker_->crypto_message_parser();
}
HandshakeState QuicCryptoClientStream::GetHandshakeState() const {
return handshaker_->GetHandshakeState();
}
size_t QuicCryptoClientStream::BufferSizeLimitForLevel(
EncryptionLevel level) const {
return handshaker_->BufferSizeLimitForLevel(level);
}
std::unique_ptr<QuicDecrypter>
QuicCryptoClientStream::AdvanceKeysAndCreateCurrentOneRttDecrypter() {
return handshaker_->AdvanceKeysAndCreateCurrentOneRttDecrypter();
}
std::unique_ptr<QuicEncrypter>
QuicCryptoClientStream::CreateCurrentOneRttEncrypter() {
return handshaker_->CreateCurrentOneRttEncrypter();
}
bool QuicCryptoClientStream::ExportKeyingMaterial(absl::string_view label,
absl::string_view context,
size_t result_len,
std::string* result) {
return handshaker_->ExportKeyingMaterial(label, context, result_len, result);
}
std::string QuicCryptoClientStream::chlo_hash() const {
return handshaker_->chlo_hash();
}
void QuicCryptoClientStream::OnOneRttPacketAcknowledged() {
handshaker_->OnOneRttPacketAcknowledged();
}
void QuicCryptoClientStream::OnHandshakePacketSent() {
handshaker_->OnHandshakePacketSent();
}
void QuicCryptoClientStream::OnConnectionClosed(
const QuicConnectionCloseFrame& frame, ConnectionCloseSource source) {
handshaker_->OnConnectionClosed(frame.quic_error_code, source);
}
void QuicCryptoClientStream::OnHandshakeDoneReceived() {
handshaker_->OnHandshakeDoneReceived();
}
void QuicCryptoClientStream::OnNewTokenReceived(absl::string_view token) {
handshaker_->OnNewTokenReceived(token);
}
void QuicCryptoClientStream::SetServerApplicationStateForResumption(
std::unique_ptr<ApplicationState> application_state) {
handshaker_->SetServerApplicationStateForResumption(
std::move(application_state));
}
SSL* QuicCryptoClientStream::GetSsl() const {
return tls_handshaker_ == nullptr ? nullptr : tls_handshaker_->ssl();
}
bool QuicCryptoClientStream::IsCryptoFrameExpectedForEncryptionLevel(
EncryptionLevel level) const {
return handshaker_->IsCryptoFrameExpectedForEncryptionLevel(level);
}
EncryptionLevel
QuicCryptoClientStream::GetEncryptionLevelToSendCryptoDataOfSpace(
PacketNumberSpace space) const {
return handshaker_->GetEncryptionLevelToSendCryptoDataOfSpace(space);
}
} | #include "quiche/quic/core/quic_crypto_client_stream.h"
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "absl/base/macros.h"
#include "quiche/quic/core/crypto/aes_128_gcm_12_encrypter.h"
#include "quiche/quic/core/crypto/quic_decrypter.h"
#include "quiche/quic/core/crypto/quic_encrypter.h"
#include "quiche/quic/core/quic_packets.h"
#include "quiche/quic/core/quic_server_id.h"
#include "quiche/quic/core/quic_utils.h"
#include "quiche/quic/platform/api/quic_flags.h"
#include "quiche/quic/platform/api/quic_test.h"
#include "quiche/quic/test_tools/crypto_test_utils.h"
#include "quiche/quic/test_tools/quic_stream_peer.h"
#include "quiche/quic/test_tools/quic_stream_sequencer_peer.h"
#include "quiche/quic/test_tools/quic_test_utils.h"
#include "quiche/quic/test_tools/simple_quic_framer.h"
#include "quiche/quic/test_tools/simple_session_cache.h"
#include "quiche/common/test_tools/quiche_test_utils.h"
using testing::_;
namespace quic {
namespace test {
namespace {
const char kServerHostname[] = "test.example.com";
const uint16_t kServerPort = 443;
class QuicCryptoClientStreamTest : public QuicTest {
public:
QuicCryptoClientStreamTest()
: supported_versions_(AllSupportedVersionsWithQuicCrypto()),
server_id_(kServerHostname, kServerPort, false),
crypto_config_(crypto_test_utils::ProofVerifierForTesting(),
std::make_unique<test::SimpleSessionCache>()),
server_crypto_config_(
crypto_test_utils::CryptoServerConfigForTesting()) {
CreateConnection();
}
void CreateSession() {
session_ = std::make_unique<TestQuicSpdyClientSession>(
connection_, DefaultQuicConfig(), supported_versions_, server_id_,
&crypto_config_);
EXPECT_CALL(*session_, GetAlpnsToOffer())
.WillRepeatedly(testing::Return(std::vector<std::string>(
{AlpnForVersion(connection_->version())})));
}
void CreateConnection() {
connection_ =
new PacketSavingConnection(&client_helper_, &alarm_factory_,
Perspective::IS_CLIENT, supported_versions_);
connection_->AdvanceTime(QuicTime::Delta::FromSeconds(1));
CreateSession();
}
void CompleteCryptoHandshake() {
int proof_verify_details_calls = 1;
if (stream()->handshake_protocol() != PROTOCOL_TLS1_3) {
EXPECT_CALL(*session_, OnProofValid(testing::_))
.Times(testing::AtLeast(1));
proof_verify_details_calls = 0;
}
EXPECT_CALL(*session_, OnProofVerifyDetailsAvailable(testing::_))
.Times(testing::AtLeast(proof_verify_details_calls));
stream()->CryptoConnect();
QuicConfig config;
crypto_test_utils::HandshakeWithFakeServer(
&config, server_crypto_config_.get(), &server_helper_, &alarm_factory_,
connection_, stream(), AlpnForVersion(connection_->version()));
}
QuicCryptoClientStream* stream() {
return session_->GetMutableCryptoStream();
}
MockQuicConnectionHelper server_helper_;
MockQuicConnectionHelper client_helper_;
MockAlarmFactory alarm_factory_;
PacketSavingConnection* connection_;
ParsedQuicVersionVector supported_versions_;
std::unique_ptr<TestQuicSpdyClientSession> session_;
QuicServerId server_id_;
CryptoHandshakeMessage message_;
QuicCryptoClientConfig crypto_config_;
std::unique_ptr<QuicCryptoServerConfig> server_crypto_config_;
};
TEST_F(QuicCryptoClientStreamTest, NotInitiallyConected) {
EXPECT_FALSE(stream()->encryption_established());
EXPECT_FALSE(stream()->one_rtt_keys_available());
}
TEST_F(QuicCryptoClientStreamTest, ConnectedAfterSHLO) {
CompleteCryptoHandshake();
EXPECT_TRUE(stream()->encryption_established());
EXPECT_TRUE(stream()->one_rtt_keys_available());
EXPECT_FALSE(stream()->IsResumption());
EXPECT_EQ(stream()->EarlyDataReason(), ssl_early_data_no_session_offered);
}
TEST_F(QuicCryptoClientStreamTest, MessageAfterHandshake) {
CompleteCryptoHandshake();
EXPECT_CALL(
*connection_,
CloseConnection(QUIC_CRYPTO_MESSAGE_AFTER_HANDSHAKE_COMPLETE, _, _));
message_.set_tag(kCHLO);
crypto_test_utils::SendHandshakeMessageToStream(stream(), message_,
Perspective::IS_CLIENT);
}
TEST_F(QuicCryptoClientStreamTest, BadMessageType) {
stream()->CryptoConnect();
message_.set_tag(kCHLO);
EXPECT_CALL(*connection_, CloseConnection(QUIC_INVALID_CRYPTO_MESSAGE_TYPE,
"Expected REJ", _));
crypto_test_utils::SendHandshakeMessageToStream(stream(), message_,
Perspective::IS_CLIENT);
}
TEST_F(QuicCryptoClientStreamTest, NegotiatedParameters) {
CompleteCryptoHandshake();
const QuicConfig* config = session_->config();
EXPECT_EQ(kMaximumIdleTimeoutSecs, config->IdleNetworkTimeout().ToSeconds());
const QuicCryptoNegotiatedParameters& crypto_params(
stream()->crypto_negotiated_params());
EXPECT_EQ(crypto_config_.aead[0], crypto_params.aead);
EXPECT_EQ(crypto_config_.kexs[0], crypto_params.key_exchange);
}
TEST_F(QuicCryptoClientStreamTest, ExpiredServerConfig) {
CompleteCryptoHandshake();
CreateConnection();
connection_->AdvanceTime(
QuicTime::Delta::FromSeconds(60 * 60 * 24 * 365 * 5));
EXPECT_CALL(*session_, OnProofValid(testing::_));
stream()->CryptoConnect();
ASSERT_EQ(1u, connection_->encrypted_packets_.size());
EXPECT_EQ(ENCRYPTION_INITIAL, connection_->encryption_level());
}
TEST_F(QuicCryptoClientStreamTest, ClientTurnedOffZeroRtt) {
CompleteCryptoHandshake();
CreateConnection();
QuicTagVector options;
options.push_back(kQNZ2);
session_->config()->SetClientConnectionOptions(options);
CompleteCryptoHandshake();
EXPECT_EQ(2, stream()->num_sent_client_hellos());
EXPECT_FALSE(stream()->EarlyDataAccepted());
EXPECT_EQ(stream()->EarlyDataReason(), ssl_early_data_disabled);
}
TEST_F(QuicCryptoClientStreamTest, ClockSkew) {
connection_->AdvanceTime(
QuicTime::Delta::FromSeconds(60 * 60 * 24 * 365 * 5));
CompleteCryptoHandshake();
}
TEST_F(QuicCryptoClientStreamTest, InvalidCachedServerConfig) {
CompleteCryptoHandshake();
CreateConnection();
QuicCryptoClientConfig::CachedState* state =
crypto_config_.LookupOrCreate(server_id_);
std::vector<std::string> certs = state->certs();
std::string cert_sct = state->cert_sct();
std::string signature = state->signature();
std::string chlo_hash = state->chlo_hash();
state->SetProof(certs, cert_sct, chlo_hash, signature + signature);
EXPECT_CALL(*session_, OnProofVerifyDetailsAvailable(testing::_))
.Times(testing::AnyNumber());
stream()->CryptoConnect();
ASSERT_EQ(1u, connection_->encrypted_packets_.size());
}
TEST_F(QuicCryptoClientStreamTest, ServerConfigUpdate) {
CompleteCryptoHandshake();
QuicCryptoClientConfig::CachedState* state =
crypto_config_.LookupOrCreate(server_id_);
EXPECT_NE("xstk", state->source_address_token());
unsigned char stk[] = {'x', 's', 't', 'k'};
unsigned char scfg[] = {
0x53, 0x43, 0x46, 0x47,
0x01, 0x00,
0x00, 0x00,
0x45, 0x58, 0x50, 0x59,
0x08, 0x00, 0x00, 0x00,
'1', '2', '3', '4', '5', '6', '7', '8'};
CryptoHandshakeMessage server_config_update;
server_config_update.set_tag(kSCUP);
server_config_update.SetValue(kSourceAddressTokenTag, stk);
server_config_update.SetValue(kSCFG, scfg);
const uint64_t expiry_seconds = 60 * 60 * 24 * 2;
server_config_update.SetValue(kSTTL, expiry_seconds);
crypto_test_utils::SendHandshakeMessageToStream(
stream(), server_config_update, Perspective::IS_SERVER);
EXPECT_EQ("xstk", state->source_address_token());
const std::string& cached_scfg = state->server_config();
quiche::test::CompareCharArraysWithHexError(
"scfg", cached_scfg.data(), cached_scfg.length(),
reinterpret_cast<char*>(scfg), ABSL_ARRAYSIZE(scfg));
QuicStreamSequencer* sequencer = QuicStreamPeer::sequencer(stream());
EXPECT_FALSE(QuicStreamSequencerPeer::IsUnderlyingBufferAllocated(sequencer));
}
TEST_F(QuicCryptoClientStreamTest, ServerConfigUpdateWithCert) {
CompleteCryptoHandshake();
QuicCryptoServerConfig crypto_config(
QuicCryptoServerConfig::TESTING, QuicRandom::GetInstance(),
crypto_test_utils::ProofSourceForTesting(), KeyExchangeSource::Default());
crypto_test_utils::SetupCryptoServerConfigForTest(
connection_->clock(), QuicRandom::GetInstance(), &crypto_config);
SourceAddressTokens tokens;
QuicCompressedCertsCache cache(1);
CachedNetworkParameters network_params;
CryptoHandshakeMessage server_config_update;
class Callback : public BuildServerConfigUpdateMessageResultCallback {
public:
Callback(bool* ok, CryptoHandshakeMessage* message)
: ok_(ok), message_(message) {}
void Run(bool ok, const CryptoHandshakeMessage& message) override {
*ok_ = ok;
*message_ = message;
}
private:
bool* ok_;
CryptoHandshakeMessage* message_;
};
bool ok = false;
crypto_config.BuildServerConfigUpdateMessage(
session_->transport_version(), stream()->chlo_hash(), tokens,
QuicSocketAddress(QuicIpAddress::Loopback6(), 1234),
QuicSocketAddress(QuicIpAddress::Loopback6(), 4321), connection_->clock(),
QuicRandom::GetInstance(), &cache, stream()->crypto_negotiated_params(),
&network_params,
std::unique_ptr<BuildServerConfigUpdateMessageResultCallback>(
new Callback(&ok, &server_config_update)));
EXPECT_TRUE(ok);
EXPECT_CALL(*session_, OnProofValid(testing::_));
crypto_test_utils::SendHandshakeMessageToStream(
stream(), server_config_update, Perspective::IS_SERVER);
CreateConnection();
EXPECT_CALL(*session_, OnProofValid(testing::_));
EXPECT_CALL(*session_, OnProofVerifyDetailsAvailable(testing::_))
.Times(testing::AnyNumber());
stream()->CryptoConnect();
EXPECT_TRUE(session_->IsEncryptionEstablished());
}
TEST_F(QuicCryptoClientStreamTest, ServerConfigUpdateBeforeHandshake) {
EXPECT_CALL(
*connection_,
CloseConnection(QUIC_CRYPTO_UPDATE_BEFORE_HANDSHAKE_COMPLETE, _, _));
CryptoHandshakeMessage server_config_update;
server_config_update.set_tag(kSCUP);
crypto_test_utils::SendHandshakeMessageToStream(
stream(), server_config_update, Perspective::IS_SERVER);
}
}
}
} |
330 | #ifndef TENSORSTORE_INTERNAL_COMPRESSION_ZLIB_H_
#define TENSORSTORE_INTERNAL_COMPRESSION_ZLIB_H_
#include <cstddef>
#include <string>
#include "absl/status/status.h"
#include "absl/strings/cord.h"
#include "tensorstore/util/status.h"
namespace tensorstore {
namespace zlib {
struct Options {
int level = -1;
bool use_gzip_header = false;
};
void Encode(const absl::Cord& input, absl::Cord* output,
const Options& options);
absl::Status Decode(const absl::Cord& input, absl::Cord* output,
bool use_gzip_header);
}
}
#endif
#include "tensorstore/internal/compression/zlib.h"
#include "absl/base/optimization.h"
#include "absl/log/absl_check.h"
#include "absl/status/status.h"
#include "tensorstore/internal/compression/cord_stream_manager.h"
#include <zlib.h>
namespace tensorstore {
namespace zlib {
namespace {
struct InflateOp {
static int Init(z_stream* s, [[maybe_unused]] int level, int header_option) {
return inflateInit2(s, 15
+ header_option);
}
static int Process(z_stream* s, int flags) { return inflate(s, flags); }
static int Destroy(z_stream* s) { return inflateEnd(s); }
static constexpr bool kDataErrorPossible = true;
};
struct DeflateOp {
static int Init(z_stream* s, int level, int header_option) {
return deflateInit2(s, level, Z_DEFLATED,
15
+ header_option,
8 ,
Z_DEFAULT_STRATEGY);
}
static int Process(z_stream* s, int flags) { return deflate(s, flags); }
static int Destroy(z_stream* s) { return deflateEnd(s); }
static constexpr bool kDataErrorPossible = false;
};
template <typename Op>
absl::Status ProcessZlib(const absl::Cord& input, absl::Cord* output, int level,
bool use_gzip_header) {
z_stream s = {};
internal::CordStreamManager<z_stream, 16 * 1024>
stream_manager(s, input, output);
const int header_option = use_gzip_header ? 16
: 0;
int err = Op::Init(&s, level, header_option);
if (err != Z_OK) {
ABSL_CHECK(false);
}
struct StreamDestroyer {
z_stream* s;
~StreamDestroyer() { Op::Destroy(s); }
} stream_destroyer{&s};
while (true) {
const bool input_complete = stream_manager.FeedInputAndOutputBuffers();
err = Op::Process(&s, input_complete ? Z_FINISH : Z_NO_FLUSH);
const bool made_progress = stream_manager.HandleOutput();
if (err == Z_OK) continue;
if (err == Z_BUF_ERROR && made_progress) continue;
break;
}
switch (err) {
case Z_STREAM_END:
if (!stream_manager.has_input_remaining()) {
return absl::OkStatus();
}
[[fallthrough]];
case Z_NEED_DICT:
case Z_DATA_ERROR:
case Z_BUF_ERROR:
if (!Op::kDataErrorPossible) {
ABSL_CHECK(false);
}
return absl::InvalidArgumentError("Error decoding zlib-compressed data");
default:
ABSL_CHECK(false);
}
ABSL_UNREACHABLE();
}
}
void Encode(const absl::Cord& input, absl::Cord* output,
const Options& options) {
ProcessZlib<DeflateOp>(input, output, options.level, options.use_gzip_header)
.IgnoreError();
}
absl::Status Decode(const absl::Cord& input, absl::Cord* output,
bool use_gzip_header) {
return ProcessZlib<InflateOp>(input, output, 0, use_gzip_header);
}
}
} | #include "tensorstore/internal/compression/zlib.h"
#include <string>
#include <vector>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "absl/strings/cord.h"
#include "absl/strings/cord_test_helpers.h"
#include "tensorstore/util/status.h"
#include "tensorstore/util/status_testutil.h"
namespace {
using ::tensorstore::MatchesStatus;
namespace zlib = tensorstore::zlib;
class ZlibCompressorTest : public ::testing::TestWithParam<bool> {};
INSTANTIATE_TEST_SUITE_P(ZlibCompressorTestCases, ZlibCompressorTest,
::testing::Values(false, true));
TEST_P(ZlibCompressorTest, SmallRoundtrip) {
const bool use_gzip_header = GetParam();
zlib::Options options{6, use_gzip_header};
const absl::Cord input("The quick brown fox jumped over the lazy dog.");
absl::Cord encode_result("abc"), decode_result("def");
zlib::Encode(input, &encode_result, options);
ASSERT_GE(encode_result.size(), 3);
EXPECT_EQ("abc", encode_result.Subcord(0, 3));
TENSORSTORE_ASSERT_OK(
zlib::Decode(encode_result.Subcord(3, encode_result.size() - 3),
&decode_result, options.use_gzip_header));
EXPECT_EQ("def" + std::string(input), decode_result);
}
TEST_P(ZlibCompressorTest, SmallRoundtripFragmented) {
const bool use_gzip_header = GetParam();
zlib::Options options{6, use_gzip_header};
const absl::Cord input = absl::MakeFragmentedCord(
{"The quick", " brown fox", " jumped over", " ", "the lazy dog."});
absl::Cord encode_result("abc"), decode_result("def");
zlib::Encode(input, &encode_result, options);
ASSERT_GE(encode_result.size(), 3);
EXPECT_EQ("abc", encode_result.Subcord(0, 3));
std::vector<std::string> encode_result_fragments;
for (size_t i = 3; i < encode_result.size(); ++i) {
encode_result_fragments.push_back(std::string(encode_result.Subcord(i, 1)));
}
TENSORSTORE_ASSERT_OK(
zlib::Decode(absl::MakeFragmentedCord(encode_result_fragments),
&decode_result, options.use_gzip_header));
EXPECT_EQ("def" + std::string(input), decode_result);
}
TEST_P(ZlibCompressorTest, LargeRoundtrip) {
const bool use_gzip_header = GetParam();
std::string input(100000, '\0');
unsigned char x = 0;
for (auto& v : input) {
v = x;
x += 7;
}
zlib::Options options{6, use_gzip_header};
absl::Cord encode_result, decode_result;
zlib::Encode(absl::Cord(input), &encode_result, options);
ASSERT_EQ(absl::OkStatus(), zlib::Decode(encode_result, &decode_result,
options.use_gzip_header));
EXPECT_EQ(input, decode_result);
}
TEST_P(ZlibCompressorTest, NonDefaultLevel) {
const bool use_gzip_header = GetParam();
zlib::Options options1{
0, use_gzip_header};
zlib::Options options2{9, use_gzip_header};
const absl::Cord input("The quick brown fox jumped over the lazy dog.");
absl::Cord encode_result1, encode_result2;
zlib::Encode(input, &encode_result1, options1);
zlib::Encode(input, &encode_result2, options2);
EXPECT_NE(encode_result1, encode_result2);
absl::Cord decode_result;
TENSORSTORE_ASSERT_OK(
zlib::Decode(encode_result2, &decode_result, options2.use_gzip_header));
EXPECT_EQ(input, decode_result);
}
TEST_P(ZlibCompressorTest, DecodeCorruptData) {
const bool use_gzip_header = GetParam();
zlib::Options options{6, use_gzip_header};
const absl::Cord input("The quick brown fox jumped over the lazy dog.");
{
absl::Cord encode_result, decode_result;
zlib::Encode(input, &encode_result, options);
ASSERT_GE(encode_result.size(), 1);
std::string corrupted(encode_result);
corrupted[0] = 0;
EXPECT_THAT(zlib::Decode(absl::Cord(corrupted), &decode_result,
options.use_gzip_header),
MatchesStatus(absl::StatusCode::kInvalidArgument));
}
{
absl::Cord encode_result, decode_result;
zlib::Encode(input, &encode_result, options);
ASSERT_GE(encode_result.size(), 1);
std::string corrupted(encode_result);
corrupted.resize(corrupted.size() - 1);
EXPECT_THAT(zlib::Decode(absl::Cord(corrupted), &decode_result,
options.use_gzip_header),
MatchesStatus(absl::StatusCode::kInvalidArgument));
}
}
} |
331 | #ifndef TENSORFLOW_COMPILER_JIT_NODE_MATCHERS_H_
#define TENSORFLOW_COMPILER_JIT_NODE_MATCHERS_H_
#include <array>
#include <string>
#include <vector>
#include "absl/algorithm/container.h"
#include "absl/strings/string_view.h"
#include "absl/types/optional.h"
#include "absl/types/span.h"
#include "tensorflow/cc/framework/ops.h"
#include "xla/test.h"
#include "tensorflow/core/graph/graph.h"
namespace tensorflow {
namespace testing {
namespace matchers {
namespace impl {
using OutEdge = std::pair<const Node*, int>;
class NodeMatcherProperties {
public:
using NodeSeqMatcher = std::vector<::testing::Matcher<const Node*>>;
using InputSeqMatcher = std::vector<::testing::Matcher<OutEdge>>;
using AttrKeyValuePair = std::pair<string, std::optional<AttrValue>>;
const std::optional<string>& name() const { return name_; }
const std::optional<string>& op() const { return op_; }
const std::optional<string>& assigned_device() const {
return assigned_device_;
}
const std::optional<Tensor>& constant_value() const {
return constant_value_;
}
const std::optional<InputSeqMatcher>& inputs() const {
return input_matchers_;
}
const std::optional<NodeSeqMatcher>& control_deps() const {
return control_deps_;
}
const std::optional<AttrKeyValuePair>& attr() const { return attr_; }
void set_name(string name) {
DCHECK(IsEmpty());
name_ = std::move(name);
}
void set_op(string op) {
DCHECK(IsEmpty());
op_ = std::move(op);
}
void set_assigned_device(string assigned_device) {
DCHECK(IsEmpty());
assigned_device_ = std::move(assigned_device);
}
void set_constant_value(Tensor constant_value) {
DCHECK(IsEmpty());
constant_value_ = std::move(constant_value);
op_ = "Const";
}
void set_inputs(InputSeqMatcher inputs) {
DCHECK(IsEmpty());
input_matchers_ = std::move(inputs);
}
void set_control_deps(NodeSeqMatcher control_deps) {
DCHECK(IsEmpty());
control_deps_ = std::move(control_deps);
}
void set_attr(AttrKeyValuePair attr) {
DCHECK(IsEmpty());
attr_ = std::move(attr);
}
bool IsEmpty() const {
return !name().has_value() && !op().has_value() && !inputs().has_value() &&
!control_deps().has_value() && !attr().has_value();
}
private:
std::optional<string> name_;
std::optional<string> op_;
std::optional<string> assigned_device_;
std::optional<Tensor> constant_value_;
std::optional<InputSeqMatcher> input_matchers_;
std::optional<NodeSeqMatcher> control_deps_;
std::optional<AttrKeyValuePair> attr_;
};
::testing::Matcher<const Node*> NodeWith(
absl::Span<const NodeMatcherProperties> props);
impl::NodeMatcherProperties Inputs(
absl::Span<const ::testing::Matcher<OutEdge>> inputs);
impl::NodeMatcherProperties CtrlDeps(
absl::Span<const ::testing::Matcher<const Node*>> control_deps);
impl::NodeMatcherProperties Attr(std::pair<string, AttrValue> attrs);
impl::NodeMatcherProperties Attr(string name);
std::pair<string, AttrValue> AttrLiteralHelper(
const std::pair<string, bool>& bool_attr);
std::pair<string, AttrValue> AttrLiteralHelper(
const std::pair<string, absl::Span<const int>>& int_list_attr);
std::pair<string, AttrValue> AttrLiteralHelper(
const std::pair<string, absl::Span<const string>>& string_list_attr);
}
impl::NodeMatcherProperties Name(string name);
impl::NodeMatcherProperties Op(string op);
impl::NodeMatcherProperties AssignedDevice(string assigned_device);
template <typename ValueTy>
impl::NodeMatcherProperties Attr(const string& name, ValueTy value) {
return impl::Attr({impl::AttrLiteralHelper({name, value})});
}
inline impl::NodeMatcherProperties Attr(const string& name) {
return impl::Attr(name);
}
template <typename... Ts>
impl::NodeMatcherProperties Inputs(Ts... inputs) {
return impl::Inputs({inputs...});
}
::testing::Matcher<impl::OutEdge> Out(int oidx,
::testing::Matcher<const Node*> node);
inline ::testing::Matcher<impl::OutEdge> Out(
::testing::Matcher<const Node*> node) {
return Out(0, node);
}
template <typename... Ts>
impl::NodeMatcherProperties CtrlDeps(Ts... control_deps) {
return impl::CtrlDeps({control_deps...});
}
impl::NodeMatcherProperties ConstantValue(
const ::tensorflow::Input::Initializer& val);
template <typename... Ts>
::testing::Matcher<const Node*> NodeWith(Ts... args) {
std::array<impl::NodeMatcherProperties, sizeof...(Ts)> array = {args...};
return impl::NodeWith(array);
}
::testing::Matcher<impl::OutEdge> Const(
const ::tensorflow::Input::Initializer& val);
}
Node* FindNodeByName(Graph* g, absl::string_view name);
}
void PrintTo(const Node* n, ::std::ostream* os);
void PrintTo(Node* n, ::std::ostream* os);
}
#endif
#include "tensorflow/compiler/jit/node_matchers.h"
#include <utility>
#include "absl/algorithm/container.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 "tensorflow/core/framework/attr_value_util.h"
#include "tensorflow/core/framework/node_def.pb.h"
#include "tensorflow/core/framework/tensor.pb.h"
#include "tensorflow/core/graph/graph_node_util.h"
namespace tensorflow {
namespace testing {
namespace matchers {
namespace {
using impl::NodeMatcherProperties;
using impl::OutEdge;
string IndentAllButFirstLine(absl::string_view text) {
std::vector<std::string> lines = absl::StrSplit(text, '\n');
for (int i = 1; i < lines.size(); i++) {
lines[i].insert(0, " ");
}
return absl::StrJoin(lines, "\n");
}
template <typename T>
bool CompareTensor(const Tensor& actual, const Tensor& expected,
::testing::MatchResultListener* listener) {
if (actual.NumElements() != expected.NumElements()) {
if (listener->IsInterested()) {
*listener << "\nwas looking for tensor with " << expected.NumElements()
<< " elements, found tensor with " << actual.NumElements()
<< " elements";
return false;
}
}
for (int64_t i = 0, e = actual.NumElements(); i < e; i++) {
if (actual.flat<T>()(i) != expected.flat<T>()(i)) {
*listener << "\nmismatch in constant tensor at index " << i
<< " expected = " << expected.flat<T>()(i)
<< " actual = " << actual.flat<T>()(i);
return false;
}
}
return true;
}
bool MatchAndExplainTensor(const Tensor& tensor, const Tensor& expected_tensor,
::testing::MatchResultListener* listener) {
if (tensor.dtype() != expected_tensor.dtype()) {
if (listener->IsInterested()) {
*listener << "\nexpected tensor of type "
<< DataType_Name(expected_tensor.dtype())
<< " but found one of type " << DataType_Name(tensor.dtype());
return false;
}
}
switch (tensor.dtype()) {
case DT_HALF:
return CompareTensor<Eigen::half>(tensor, expected_tensor, listener);
case DT_FLOAT:
return CompareTensor<float>(tensor, expected_tensor, listener);
case DT_DOUBLE:
return CompareTensor<double>(tensor, expected_tensor, listener);
case DT_INT8:
return CompareTensor<int8>(tensor, expected_tensor, listener);
case DT_INT16:
return CompareTensor<int16>(tensor, expected_tensor, listener);
case DT_INT32:
return CompareTensor<int32>(tensor, expected_tensor, listener);
case DT_INT64:
return CompareTensor<int64_t>(tensor, expected_tensor, listener);
case DT_UINT8:
return CompareTensor<uint8>(tensor, expected_tensor, listener);
case DT_UINT16:
return CompareTensor<uint16>(tensor, expected_tensor, listener);
case DT_UINT32:
return CompareTensor<uint32>(tensor, expected_tensor, listener);
case DT_UINT64:
return CompareTensor<uint64>(tensor, expected_tensor, listener);
default:
LOG(FATAL) << "Unsupported dtype "
<< DataType_Name(tensor.dtype());
}
}
struct NodeMatcher : public ::testing::MatcherInterface<const Node*> {
bool MatchAndExplain(
const Node* node,
::testing::MatchResultListener* listener) const override {
if (op && node->type_string() != *op) {
if (listener->IsInterested()) {
*listener << "\nexpected op " << *op << " but found "
<< node->type_string();
}
return false;
}
if (assigned_device && node->assigned_device_name() != *assigned_device) {
if (listener->IsInterested()) {
*listener << "\nexpected assigned_device " << *assigned_device
<< " but found \"" << node->assigned_device_name() << "\"";
}
return false;
}
if (name && node->name() != *name) {
if (listener->IsInterested()) {
*listener << "\nexpected name " << *name << " but found "
<< node->name();
}
return false;
}
if (constant_value) {
const TensorProto* proto = nullptr;
if (!TryGetNodeAttr(node->def(), "value", &proto)) {
if (listener->IsInterested()) {
*listener << "\ncould not find \"value\" attribute in node";
}
return false;
}
Tensor tensor(proto->dtype());
if (!tensor.FromProto(*proto)) {
if (listener->IsInterested()) {
*listener << "\ncould not convert TensorProto in \"value\" attribute "
"to Tensor";
}
return false;
}
if (!MatchAndExplainTensor(tensor,
*constant_value,
listener)) {
return false;
}
}
if (input_matchers) {
if (input_matchers->size() != node->num_inputs()) {
if (listener->IsInterested()) {
*listener << "\nexpected " << input_matchers->size()
<< " inputs but node has " << node->num_inputs();
}
return false;
}
for (int input_idx = 0, e = input_matchers->size(); input_idx < e;
input_idx++) {
if (!MatchAndExplainInput(node, input_idx, listener)) {
return false;
}
}
}
std::vector<const Node*> control_deps;
for (const Edge* e : node->in_edges()) {
if (e->IsControlEdge()) {
control_deps.push_back(e->src());
}
}
::testing::StringMatchResultListener inner_listener;
if (control_dep_set &&
!control_dep_set->MatchAndExplain(control_deps, &inner_listener)) {
if (listener->IsInterested()) {
string explanation = inner_listener.str();
if (!explanation.empty()) {
explanation = absl::StrCat(", ", explanation, ",");
}
*listener << "ctrl_deps" << explanation << " does not match expected: ";
control_dep_set->DescribeTo(listener->stream());
}
return false;
}
const AttrValueMap attr_value_map = node->def().attr();
for (const auto& attr_kv_pair : attrs) {
auto it = attr_value_map.find(attr_kv_pair.first);
if (it == attr_value_map.end()) {
if (listener->IsInterested()) {
*listener << "did not find attribute named \"" << attr_kv_pair.first
<< "\" in node";
}
return false;
}
if (attr_kv_pair.second &&
!AreAttrValuesEqual(it->second, *attr_kv_pair.second)) {
if (listener->IsInterested()) {
*listener << "attribute named " << attr_kv_pair.first
<< " does not match value; expected: \""
<< SummarizeAttrValue(*attr_kv_pair.second)
<< "\", found: \"" << SummarizeAttrValue(it->second)
<< "\"";
}
return false;
}
}
return true;
}
void DescribeTo(::std::ostream* os) const override {
std::vector<string> predicates;
if (name) {
predicates.push_back(absl::StrCat("name: ", *name));
}
if (op) {
predicates.push_back(absl::StrCat("op: ", *op));
}
if (assigned_device) {
predicates.push_back(absl::StrCat("assigned device: ", *assigned_device));
}
bool printed_something = !predicates.empty();
*os << absl::StrJoin(predicates, ", ");
if (constant_value) {
printed_something = true;
*os << "constant value: " << constant_value->DebugString();
}
if (input_matchers) {
if (!input_matchers->empty()) {
printed_something = true;
*os << " with " << (input_matchers->size() == 1 ? "only " : "")
<< "input" << (input_matchers->size() == 1 ? "" : "s") << " ";
}
if (input_matchers->size() == 1) {
::std::stringstream ss;
input_matchers->front().DescribeTo(&ss);
printed_something = true;
*os << "matching " << ss.str();
} else {
int edge_idx = 0;
for (const ::testing::Matcher<OutEdge>& matcher : (*input_matchers)) {
*os << "\n [" << edge_idx << "] matching (";
::std::stringstream ss;
matcher.DescribeTo(&ss);
printed_something = true;
*os << IndentAllButFirstLine(ss.str());
*os << ")";
edge_idx++;
}
}
}
if (control_dep_set) {
printed_something = true;
*os << " and control deps ";
control_dep_set->DescribeTo(os);
}
if (!attrs.empty()) {
printed_something = true;
std::vector<string> attrs_str;
absl::c_transform(
attrs, std::back_inserter(attrs_str),
[](const std::pair<string, std::optional<AttrValue>>& attr_kv_pair) {
return absl::StrCat(attr_kv_pair.first, "->",
attr_kv_pair.second
? SummarizeAttrValue(*attr_kv_pair.second)
: "*");
});
*os << " and attr values matching [" << absl::StrJoin(attrs_str, ", ")
<< "]";
}
if (!printed_something) {
*os << "is any node";
}
}
bool MatchAndExplainInput(const Node* node, int input_idx,
::testing::MatchResultListener* listener) const {
const Edge* edge;
if (!node->input_edge(input_idx, &edge).ok()) {
if (listener->IsInterested()) {
*listener << "\ncould not find incoming edge for input " << input_idx;
}
return false;
}
::testing::StringMatchResultListener inner_listener;
OutEdge input = {edge->src(), edge->src_output()};
if ((*input_matchers)[input_idx].MatchAndExplain(input, &inner_listener)) {
return true;
}
if (listener->IsInterested()) {
*listener << "\ninput " << input_idx << " does not match expected:\n";
(*input_matchers)[input_idx].DescribeTo(listener->stream());
string explanation = inner_listener.str();
if (!explanation.empty()) {
*listener << ", " << explanation;
}
}
return false;
}
std::optional<string> op;
std::optional<string> name;
std::optional<string> assigned_device;
std::optional<Tensor> constant_value;
std::optional<std::vector<::testing::Matcher<OutEdge>>> input_matchers;
std::optional<::testing::Matcher<absl::Span<const Node* const>>>
control_dep_set;
std::map<string, std::optional<AttrValue>> attrs;
};
class OutEdgeMatcher : public ::testing::MatcherInterface<OutEdge> {
public:
OutEdgeMatcher(::testing::Matcher<const Node*> src_matcher, int src_oidx)
: src_matcher_(std::move(src_matcher)), src_oidx_(src_oidx) {}
bool MatchAndExplain(
OutEdge out_edge,
::testing::MatchResultListener* listener) const override {
::testing::StringMatchResultListener inner_listener;
if (!src_matcher_.MatchAndExplain(out_edge.first, &inner_listener)) {
if (listener->IsInterested()) {
*listener << "\nsource does not match expected ";
src_matcher_.DescribeTo(listener->stream());
string explanation = inner_listener.str();
if (!explanation.empty()) {
*listener << "\n\t" << explanation;
}
}
return false;
}
if (out_edge.second != src_oidx_) {
if (listener->IsInterested()) {
*listener << "\nexpected output slot to be " << src_oidx_
<< " but found " << out_edge.second;
}
return false;
}
return true;
}
void DescribeTo(::std::ostream* os) const override {
if (src_oidx_) {
*os << "output slot: " << src_oidx_ << ", source: (";
}
src_matcher_.DescribeTo(os);
if (src_oidx_) {
*os << ")";
}
}
private:
::testing::Matcher<const Node*> src_matcher_;
int src_oidx_;
};
}
::testing::Matcher<const Node*> impl::NodeWith(
absl::Span<const NodeMatcherProperties> props) {
NodeMatcher* matcher = new NodeMatcher();
for (const NodeMatcherProperties& prop : props) {
if (prop.name()) {
DCHECK(!matcher->name);
matcher->name = prop.name();
}
if (prop.op()) {
DCHECK(!matcher->op);
matcher->op = prop.op();
}
if (prop.constant_value()) {
DCHECK(!matcher->constant_value);
matcher->constant_value = prop.constant_value();
}
if (prop.assigned_device()) {
DCHECK(!matcher->assigned_device);
matcher->assigned_device = prop.assigned_device();
}
if (prop.inputs()) {
DCHECK(!matcher->input_matchers);
matcher->input_matchers = *prop.inputs();
}
if (prop.control_deps()) {
DCHECK(!matcher->control_dep_set);
matcher->control_dep_set =
::testing::UnorderedElementsAreArray(*prop.control_deps());
}
if (prop.attr()) {
auto insert_result = matcher->attrs.insert(*prop.attr());
DCHECK(insert_result.second);
}
}
return ::testing::MakeMatcher(matcher);
}
impl::NodeMatcherProperties Name(string name) {
impl::NodeMatcherProperties props;
props.set_name(std::move(name));
return props;
}
impl::NodeMatcherProperties Op(string op) {
impl::NodeMatcherProperties props;
props.set_op(std::move(op));
return props;
}
impl::NodeMatcherProperties AssignedDevice(string assigned_device) {
impl::NodeMatcherProperties props;
props.set_assigned_device(std::move(assigned_device));
return props;
}
impl::NodeMatcherProperties impl::Inputs(
absl::Span<const ::testing::Matcher<OutEdge>> inputs) {
std::vector<::testing::Matcher<OutEdge>> inputs_vector;
absl::c_copy(inputs, std::back_inserter(inputs_vector));
impl::NodeMatcherProperties props;
props.set_inputs(std::move(inputs_vector));
return props;
}
impl::NodeMatcherProperties impl::CtrlDeps(
absl::Span<const ::testing::Matcher<const Node*>> control_deps) {
std::vector<::testing::Matcher<const Node*>> control_deps_vector;
absl::c_copy(control_deps, std::back_inserter(control_deps_vector));
impl::NodeMatcherProperties props;
props.set_control_deps(std::move(control_deps_vector));
return props;
}
std::pair<string, AttrValue> impl::AttrLiteralHelper(
const std::pair<string, bool>& bool_attr) {
AttrValue attr_value;
attr_value.set_b(bool_attr.second);
return {bool_attr.first, attr_value};
}
std::pair<string, AttrValue> impl::AttrLiteralHelper(
const std::pair<string, absl::Span<const int>>& int_list_attr) {
AttrValue attr_value;
AttrValue::ListValue* list = attr_value.mutable_list();
for (int i : int_list_attr.second) {
list->add_i(i);
}
return {int_list_attr.first, attr_value};
}
std::pair<string, AttrValue> impl::AttrLiteralHelper(
const std::pair<string, absl::Span<const string>>& string_list_attr) {
AttrValue attr_value;
AttrValue::ListValue* list = attr_value.mutable_list();
for (const string& s : string_list_attr.second) {
list->add_s(s);
}
return {string_list_attr.first, attr_value};
}
impl::NodeMatcherProperties impl::Attr(std::pair<string, AttrValue> attr) {
impl::NodeMatcherProperties props;
props.set_attr(std::move(attr));
return props;
}
impl::NodeMatcherProperties impl::Attr(string name) {
impl::NodeMatcherProperties props;
props.set_attr({std::move(name), std::nullopt});
return props;
}
NodeMatcherProperties ConstantValue(
const ::tensorflow::Input::Initializer& val) {
TF_CHECK_OK(val.status);
NodeMatcherProperties props;
props.set_constant_value(val.tensor);
return props;
}
::testing::Matcher<impl::OutEdge> Const(
const ::tensorflow::Input::Initializer& val) {
return Out(NodeWith(ConstantValue(val)));
}
::testing::Matcher<impl::OutEdge> Out(
int oidx, ::testing::Matcher<const Node*> node_matcher) {
return ::testing::MakeMatcher(new OutEdgeMatcher(node_matcher, oidx));
}
}
Node* FindNodeByName(Graph* g, absl::string_view name) {
for (Node* n : g->nodes()) {
if (n->name() == name) {
return n;
}
}
return nullptr;
}
}
void PrintTo(const Node* n, ::std::ostream* os) { *os << SummarizeNode(*n); }
void PrintTo(Node* n, ::std::ostream* os) { *os << SummarizeNode(*n); }
} | #include "tensorflow/compiler/jit/node_matchers.h"
#include <string>
#include "tensorflow/cc/framework/ops.h"
#include "tensorflow/cc/ops/array_ops.h"
#include "tensorflow/cc/ops/const_op.h"
#include "tensorflow/cc/ops/control_flow_ops.h"
#include "tensorflow/cc/ops/control_flow_ops_internal.h"
#include "tensorflow/cc/ops/math_ops.h"
namespace tensorflow {
namespace testing {
namespace {
using ::testing::_;
using testing::matchers::AssignedDevice;
using testing::matchers::Attr;
using testing::matchers::ConstantValue;
using testing::matchers::CtrlDeps;
using testing::matchers::Inputs;
using testing::matchers::Name;
using testing::matchers::NodeWith;
using testing::matchers::Op;
using testing::matchers::Out;
template <typename M, typename T>
string Explain(const T& t, const M& m) {
::testing::StringMatchResultListener listener;
EXPECT_THAT(t, ::testing::Not(m));
EXPECT_FALSE(m.MatchAndExplain(t, &listener));
return listener.str();
}
TEST(NodeMatchers, CheckAgainstConstant) {
Scope root = Scope::NewRootScope().ExitOnError();
Output placeholder =
ops::Placeholder(root.WithOpName("placeholder"), DT_FLOAT);
EXPECT_THAT(placeholder.node(), NodeWith(Op("Placeholder")));
EXPECT_THAT(placeholder.node(), NodeWith(Name("placeholder")));
EXPECT_THAT(placeholder.node(),
NodeWith(Op("Placeholder"), Name("placeholder")));
EXPECT_THAT(placeholder.node(),
NodeWith(Name("placeholder"), Op("Placeholder")));
EXPECT_THAT(placeholder.node(), NodeWith(Inputs()));
EXPECT_THAT(placeholder.node(),
NodeWith(Op("Placeholder"), Name("placeholder"), Inputs()));
EXPECT_EQ(Explain(placeholder.node(), NodeWith(Op("Add"))),
"\nexpected op Add but found Placeholder");
EXPECT_EQ(Explain(placeholder.node(), NodeWith(Name("add"))),
"\nexpected name add but found placeholder");
EXPECT_EQ(Explain(placeholder.node(), NodeWith(Inputs(Out(NodeWith())))),
"\nexpected 1 inputs but node has 0");
}
TEST(NodeMatchers, CheckAgainstBinary) {
Scope root = Scope::NewRootScope().ExitOnError();
Output placeholder_a =
ops::Placeholder(root.WithOpName("placeholder_a"), DT_FLOAT);
Output placeholder_b =
ops::Placeholder(root.WithOpName("placeholder_b"), DT_FLOAT);
Output add = ops::Add(root.WithOpName("add"), placeholder_a, placeholder_b);
EXPECT_THAT(add.node(),
NodeWith(Op("Add"), Name("add"),
Inputs(Out(NodeWith(Name("placeholder_a"))),
Out(NodeWith(Name("placeholder_b"))))));
EXPECT_EQ(Explain(add.node(), NodeWith(Inputs())),
"\nexpected 0 inputs but node has 2");
EXPECT_EQ(
Explain(add.node(), NodeWith(Inputs(Out(NodeWith(Name("blah"))), _))),
"\ninput 0 does not match expected:\nname: blah, \nsource does not match "
"expected name: blah\n\t\nexpected name blah but found placeholder_a");
EXPECT_EQ(
Explain(add.node(), NodeWith(Inputs(_, Out(NodeWith(Name("blah")))))),
"\ninput 1 does not match expected:\nname: blah, \nsource does not match "
"expected name: blah\n\t\nexpected name blah but found placeholder_b");
}
TEST(NodeMatchers, CheckControlDependence) {
Scope root = Scope::NewRootScope().ExitOnError();
Output placeholder_a =
ops::Placeholder(root.WithOpName("placeholder_a"), DT_FLOAT);
Output placeholder_b =
ops::Placeholder(root.WithOpName("placeholder_b"), DT_FLOAT);
Output placeholder_c =
ops::Placeholder(root.WithOpName("placeholder_c"), DT_FLOAT);
Output placeholder_d =
ops::Placeholder(root.WithOpName("placeholder_d"), DT_FLOAT);
root.graph()->AddControlEdge(placeholder_a.node(), placeholder_c.node());
root.graph()->AddControlEdge(placeholder_b.node(), placeholder_c.node());
EXPECT_THAT(placeholder_c.node(),
NodeWith(Name("placeholder_c"),
CtrlDeps(NodeWith(Name("placeholder_a")),
NodeWith(Name("placeholder_b")))));
EXPECT_THAT(placeholder_d.node(),
NodeWith(Name("placeholder_d"), CtrlDeps()));
{
const std::string explanation =
Explain(placeholder_c.node(), NodeWith(CtrlDeps()));
EXPECT_NE(explanation.find("ctrl_deps, which has 2 elements"),
std::string::npos);
EXPECT_NE(explanation.find("does not match expected: is empty"),
std::string::npos);
}
{
const std::string explanation =
Explain(placeholder_d.node(), NodeWith(CtrlDeps(NodeWith())));
EXPECT_NE(explanation.find("ctrl_deps"), std::string::npos);
EXPECT_NE(explanation.find("does not match expected: has 1 element and "
"that element is any node"),
std::string::npos);
}
}
TEST(NodeMatchers, ConstValue) {
Scope root = Scope::NewRootScope().ExitOnError();
Output placeholder =
ops::Placeholder(root.WithOpName("placeholder"), DT_FLOAT);
Output const_0d = ops::Const(root.WithOpName("const_0d"), 42);
Output const_2d = ops::Const(root.WithOpName("const_2d"), {{1, 2}, {4, 3}});
EXPECT_THAT(const_0d.node(), NodeWith(ConstantValue(42)));
EXPECT_THAT(const_0d.node(), NodeWith(ConstantValue(42), Name("const_0d")));
EXPECT_THAT(const_2d.node(), NodeWith(ConstantValue({{1, 2}, {4, 3}})));
EXPECT_EQ(Explain(placeholder.node(), NodeWith(ConstantValue(42))),
"\nexpected op Const but found Placeholder");
EXPECT_EQ(
Explain(const_0d.node(), NodeWith(ConstantValue(43))),
"\nmismatch in constant tensor at index 0 expected = 43 actual = 42");
EXPECT_EQ(
Explain(const_0d.node(), NodeWith(ConstantValue({{1, 2}, {4, 3}}))),
"\nwas looking for tensor with 4 elements, found tensor with 1 elements");
EXPECT_EQ(
Explain(const_2d.node(), NodeWith(ConstantValue(42))),
"\nwas looking for tensor with 1 elements, found tensor with 4 elements");
}
TEST(NodeMatchers, AssignedDevice) {
Scope root = Scope::NewRootScope().ExitOnError();
Output placeholder_a =
ops::Placeholder(root.WithOpName("placeholder_a"), DT_FLOAT);
Output placeholder_b =
ops::Placeholder(root.WithOpName("placeholder_b"), DT_FLOAT);
Output assigned_add =
ops::Add(root.WithOpName("assigned_add"), placeholder_a, placeholder_b);
assigned_add.node()->set_assigned_device_name(
"/job:localhost/replica:0/task:0/device:CPU:0");
Output unassigned_add =
ops::Add(root.WithOpName("unassigned_add"), placeholder_a, placeholder_b);
EXPECT_THAT(
assigned_add.node(),
NodeWith(AssignedDevice("/job:localhost/replica:0/task:0/device:CPU:0")));
EXPECT_THAT(unassigned_add.node(), NodeWith(AssignedDevice("")));
EXPECT_EQ(Explain(unassigned_add.node(),
NodeWith(AssignedDevice(
"/job:localhost/replica:0/task:0/device:CPU:0"))),
"\nexpected assigned_device "
"/job:localhost/replica:0/task:0/device:CPU:0 but found \"\"");
}
TEST(NodeMatchers, OutputIndices) {
Scope root = Scope::NewRootScope().ExitOnError();
Output pred = ops::Placeholder(root.WithOpName("pred"), DT_BOOL);
Output data = ops::Placeholder(root.WithOpName("data"), DT_FLOAT);
ops::Switch sw(root.WithOpName("switch"), data, pred);
Output add = ops::Add(root.WithOpName("add"), sw.output_true,
ops::Placeholder(root.WithOpName("addend"), DT_FLOAT));
EXPECT_THAT(add.node(), NodeWith(Inputs(Out(1, NodeWith(Op("Switch"))), _)));
EXPECT_EQ(
Explain(add.node(), NodeWith(Inputs(Out(0, NodeWith(Op("Switch"))), _))),
"\ninput 0 does not match expected:\nop: Switch, \nexpected output slot "
"to be 0 but found 1");
}
TEST(NodeMatchers, Attrs) {
Scope root = Scope::NewRootScope().ExitOnError();
Output enter = ops::internal::Enter(
root.WithOpName("enter"),
ops::Placeholder(root.WithOpName("data"), DT_FLOAT), "frame_name",
ops::internal::Enter::Attrs{}.IsConstant(true));
EXPECT_THAT(enter.node(), NodeWith(Attr("is_constant", true)));
EXPECT_EQ(Explain(enter.node(), NodeWith(Attr("is_constant", false))),
"attribute named is_constant does not match value; expected: "
"\"false\", found: \"true\"");
EXPECT_EQ(Explain(enter.node(), NodeWith(Attr("missing_attr", false))),
"did not find attribute named \"missing_attr\" in node");
}
}
}
} |
332 | #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());
}
} |
333 | #ifndef XLA_SERVICE_GPU_FUSIONS_LOOP_MLIR_H_
#define XLA_SERVICE_GPU_FUSIONS_LOOP_MLIR_H_
#include <cstdint>
#include <optional>
#include "absl/status/status.h"
#include "mlir/Dialect/Func/IR/FuncOps.h"
#include "mlir/IR/MLIRContext.h"
#include "xla/hlo/ir/hlo_instructions.h"
#include "xla/service/gpu/fusions/loop.h"
#include "xla/service/gpu/fusions/mlir/computation_partitioner.h"
#include "xla/service/gpu/fusions/mlir/mlir_fusion_emitter.h"
#include "xla/service/gpu/hlo_fusion_analysis.h"
#include "xla/service/gpu/launch_dimensions.h"
#include "xla/service/gpu/model/indexing_map.h"
namespace xla {
namespace gpu {
class MlirLoopFusion : public MlirFusionEmitterBase {
public:
explicit MlirLoopFusion(const HloFusionAnalysis& analysis)
: analysis_(analysis), config_(ComputeLoopFusionConfig(analysis)) {}
LaunchDimensions launch_dimensions() const override;
std::optional<IndexingMap> ComputeThreadIdToOutputIndexing(
int64_t root_index, mlir::MLIRContext* ctx) const override;
std::optional<IndexingMap> ComputeThreadIdToInputIndexing(
int64_t root_index, int64_t hero_operand_index,
mlir::MLIRContext* ctx) const override;
protected:
absl::Status EmitEntryFunction(
const mlir_converter::PartitionedComputations& computations,
const mlir_converter::CallTargetProvider& call_targets,
mlir::func::FuncOp entry_function,
const HloFusionInstruction& fusion) const override;
private:
const HloFusionAnalysis& analysis_;
LaunchDimensionsConfig config_;
};
}
}
#endif
#include "xla/service/gpu/fusions/loop_mlir.h"
#include <iterator>
#include <optional>
#include <vector>
#include "absl/algorithm/container.h"
#include "absl/log/check.h"
#include "absl/log/log.h"
#include "absl/status/status.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallVector.h"
#include "mlir/Dialect/Func/IR/FuncOps.h"
#include "mlir/Dialect/Tensor/IR/Tensor.h"
#include "mlir/IR/AffineExpr.h"
#include "mlir/IR/AffineMap.h"
#include "mlir/IR/ImplicitLocOpBuilder.h"
#include "mlir/IR/MLIRContext.h"
#include "mlir/IR/Value.h"
#include "mlir/IR/ValueRange.h"
#include "xla/hlo/ir/hlo_computation.h"
#include "xla/hlo/ir/hlo_instruction.h"
#include "xla/hlo/ir/hlo_instructions.h"
#include "xla/service/gpu/fusions/mlir/computation_partitioner.h"
#include "xla/service/gpu/fusions/mlir/elemental_hlo_to_mlir.h"
#include "xla/service/gpu/fusions/mlir/ir/xla_gpu_ops.h"
#include "xla/service/gpu/hlo_fusion_analysis.h"
#include "xla/service/gpu/launch_dimensions.h"
#include "xla/service/gpu/model/indexing_analysis.h"
#include "xla/service/gpu/model/indexing_map.h"
#include "xla/shape.h"
#include "xla/status_macros.h"
#include "xla/xla_data.pb.h"
namespace xla {
namespace gpu {
namespace {
using llvm::SmallVector;
using mlir::Value;
using mlir::ValueRange;
const Shape& GetIndexShape(const Shape& shape) {
return shape.IsTuple() ? shape.tuple_shapes(0) : shape;
}
}
std::optional<IndexingMap> MlirLoopFusion::ComputeThreadIdToOutputIndexing(
int64_t root_index, mlir::MLIRContext* ctx) const {
auto launch_dims = launch_dimensions();
return GetDefaultThreadIdIndexingMap(
launch_dims, config_.unroll_factor,
GetIndexShape(analysis_.fusion_root(root_index).shape()), ctx);
}
std::optional<IndexingMap> MlirLoopFusion::ComputeThreadIdToInputIndexing(
int64_t root_index, int64_t hero_operand_index,
mlir::MLIRContext* ctx) const {
std::optional<IndexingMap> thread_id_to_output_indexing =
ComputeThreadIdToOutputIndexing(root_index, ctx);
if (!thread_id_to_output_indexing.has_value()) {
return std::nullopt;
}
const HloInstruction* fusion_root =
&analysis_.fusion_root(root_index).instruction();
auto output_to_input_indexing =
ComputeOutputToInputIndexing(fusion_root, 0, ctx);
IndexingMapSet output_to_input_indexing_set =
output_to_input_indexing.indexing_maps[hero_operand_index];
CHECK_EQ(output_to_input_indexing_set.size(), 1);
IndexingMap thread_id_to_input_indexing_map = ComposeIndexingMaps(
*thread_id_to_output_indexing, *output_to_input_indexing_set.begin());
thread_id_to_input_indexing_map.Simplify();
return thread_id_to_input_indexing_map;
}
LaunchDimensions MlirLoopFusion::launch_dimensions() const {
return CalculateLaunchDimensions(
GetIndexShape(analysis_.fusion_root(0).shape()), analysis_.device_info(),
config_);
}
absl::Status MlirLoopFusion::EmitEntryFunction(
const mlir_converter::PartitionedComputations& computations,
const mlir_converter::CallTargetProvider& call_targets,
mlir::func::FuncOp entry_function,
const HloFusionInstruction& fusion) const {
mlir::ImplicitLocOpBuilder builder(entry_function.getLoc(), entry_function);
builder.setInsertionPointToStart(entry_function.addEntryBlock());
auto indexing =
ComputeThreadIdToOutputIndexing(0, entry_function.getContext());
TF_RET_CHECK(indexing) << "Indexing is never nullopt";
int num_inputs = fusion.fused_instructions_computation()->num_parameters();
auto output_tensor_args =
entry_function.getArguments().drop_front(num_inputs);
llvm::SmallVector<const Shape*> result_shapes;
for (const HloInstructionAdaptor& root : analysis_.fusion_roots()) {
if (root.shape().IsTuple()) {
for (const auto& shape : root.shape().tuple_shapes()) {
result_shapes.push_back(&shape);
}
} else {
result_shapes.push_back(&root.shape());
}
}
auto body_builder = [&](ValueRange output_tensors, ValueRange dim_values,
ValueRange symbol_values) -> SmallVector<Value> {
llvm::SmallVector<Value> first_output_indices =
mlir_converter::ApplyIndexing(*indexing, dim_values, symbol_values,
builder);
auto root_fn = call_targets(
fusion.fused_instructions_computation()->root_instruction());
SmallVector<Value> operands(
entry_function.getArguments().take_front(num_inputs));
absl::c_copy(first_output_indices, std::back_inserter(operands));
auto result_scalars =
builder.create<PureCallOp>(root_fn, operands).getResults();
SmallVector<Value> result_tensors;
result_tensors.reserve(output_tensor_args.size());
for (auto [root_shape, tensor, value] :
llvm::zip(result_shapes, output_tensors, result_scalars)) {
llvm::SmallVector<Value> output_indices = mlir_converter::ApplyIndexing(
GetBitcastMap(*result_shapes.front(), *root_shape,
builder.getContext()),
first_output_indices, {}, builder);
result_tensors.push_back(builder.create<mlir::tensor::InsertOp>(
value, tensor, output_indices));
}
return result_tensors;
};
builder.create<mlir::func::ReturnOp>(
EmitThreadLoopNest(builder, output_tensor_args, *indexing, body_builder));
return absl::OkStatus();
}
}
} | #include "xla/service/gpu/fusions/loop_mlir.h"
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "xla/error_spec.h"
#include "xla/service/gpu/fusions/mlir_emitter_test_base.h"
#include "xla/service/gpu/hlo_fusion_analysis.h"
#include "xla/service/gpu/model/indexing_test_utils.h"
#include "tsl/lib/core/status_test_util.h"
#include "tsl/platform/statusor.h"
namespace xla {
namespace gpu {
namespace {
using MlirLoopFusionTest = MlirEmitterTestBase<MlirLoopFusion>;
TEST_F(MlirLoopFusionTest, ThreadId_IndexingUnrolled) {
TF_ASSERT_OK_AND_ASSIGN(auto module, ParseAndReturnVerifiedModule(R"(
HloModule module
neg {
%input = f32[100,200,300] parameter(0)
ROOT neg = f32[100,200,300] negate(%input)
}
ENTRY entry {
%input = f32[100,200,300] parameter(0)
ROOT %fusion = f32[100,200,300] fusion(%input), kind=kLoop, calls=neg
}
)"));
thread_id_printer_.SetSymbolName(0, "chunk_id");
thread_id_printer_.SetSymbolName(1, "unroll_id");
auto* root = module->entry_computation()->root_instruction();
auto analysis = AnalyzeFusion(*root, device_info_);
MlirLoopFusion fusion(analysis);
auto thread_id_to_output_indexing =
fusion.ComputeThreadIdToOutputIndexing(0, &mlir_context_);
EXPECT_THAT(thread_id_to_output_indexing->ToString(thread_id_printer_),
MatchIndexingString(R"(
(th_x, th_y, th_z, bl_x, bl_y, bl_z)[chunk_id, unroll_id] -> (
((bl_x * 128 + chunk_id * 129024 + th_x) floordiv 15000) mod 100,
((bl_x * 128 + chunk_id * 129024 + th_x) floordiv 75) mod 200,
(th_x * 4 + bl_x * 512 + chunk_id * 516096) mod 300 + unroll_id
)
domain:
th_x in [0, 128)
th_y in [0, 1)
th_z in [0, 1)
bl_x in [0, 1008)
bl_y in [0, 1)
bl_z in [0, 1)
chunk_id in [0, 12)
unroll_id in [0, 4)
(th_x + bl_x * 128) * 4 + chunk_id * 516096 in [0, 5999997)
)"));
}
TEST_F(MlirLoopFusionTest, ThreadId_IndexingNotUnrolled) {
TF_ASSERT_OK_AND_ASSIGN(auto module, ParseAndReturnVerifiedModule(R"(
HloModule module
neg {
%input = f32[20] parameter(0)
ROOT neg = f32[20] negate(%input)
}
ENTRY entry {
%input = f32[20] parameter(0)
ROOT %fusion = f32[20] fusion(%input), kind=kLoop, calls=neg
}
)"));
thread_id_printer_.SetSymbolName(0, "chunk_id");
thread_id_printer_.SetSymbolName(1, "unroll_id");
auto* root = module->entry_computation()->root_instruction();
auto analysis = AnalyzeFusion(*root, device_info_);
MlirLoopFusion fusion(analysis);
auto thread_id_to_output_indexing =
fusion.ComputeThreadIdToOutputIndexing(0, &mlir_context_);
EXPECT_THAT(thread_id_to_output_indexing->ToString(thread_id_printer_),
MatchIndexingString(R"(
(th_x, th_y, th_z, bl_x, bl_y, bl_z)[chunk_id, unroll_id] -> (th_x)
domain:
th_x in [0, 20)
th_y in [0, 1)
th_z in [0, 1)
bl_x in [0, 1)
bl_y in [0, 1)
bl_z in [0, 1)
chunk_id in [0, 1)
unroll_id in [0, 1)
)"));
auto thread_id_to_input_indexing = fusion.ComputeThreadIdToInputIndexing(
0, 0, &mlir_context_);
EXPECT_THAT(thread_id_to_input_indexing->ToString(thread_id_printer_),
MatchIndexingString(R"(
(th_x, th_y, th_z, bl_x, bl_y, bl_z)[chunk_id, unroll_id] -> (th_x)
domain:
th_x in [0, 20)
th_y in [0, 1)
th_z in [0, 1)
bl_x in [0, 1)
bl_y in [0, 1)
bl_z in [0, 1)
chunk_id in [0, 1)
unroll_id in [0, 1)
)"));
}
TEST_F(MlirLoopFusionTest, ThreadId_Broadcast) {
TF_ASSERT_OK_AND_ASSIGN(auto module, ParseAndReturnVerifiedModule(R"(
HloModule module
bcast {
%input = f32[20] parameter(0)
ROOT bcast = f32[10, 20, 30] broadcast(%input), dimensions={1}
}
ENTRY entry {
%input = f32[20] parameter(0)
ROOT %fusion = f32[10, 20, 30] fusion(%input), kind=kLoop, calls=bcast
}
)"));
thread_id_printer_.SetSymbolName(0, "chunk_id");
thread_id_printer_.SetSymbolName(1, "unroll_id");
auto* root = module->entry_computation()->root_instruction();
auto analysis = AnalyzeFusion(*root, device_info_);
MlirLoopFusion fusion(analysis);
auto thread_id_to_output_indexing =
fusion.ComputeThreadIdToOutputIndexing(0, &mlir_context_);
EXPECT_THAT(thread_id_to_output_indexing->ToString(thread_id_printer_),
MatchIndexingString(R"(
(th_x, th_y, th_z, bl_x, bl_y, bl_z)[chunk_id, unroll_id] -> (
((bl_x * 128 + th_x) floordiv 600) mod 10,
((bl_x * 128 + th_x) floordiv 30) mod 20,
(bl_x * 128 + th_x) mod 30
)
domain:
th_x in [0, 128)
th_y in [0, 1)
th_z in [0, 1)
bl_x in [0, 47)
bl_y in [0, 1)
bl_z in [0, 1)
chunk_id in [0, 1)
unroll_id in [0, 1)
th_x + bl_x * 128 in [0, 6000)
)"));
auto thread_id_to_input_indexing = fusion.ComputeThreadIdToInputIndexing(
0, 0, &mlir_context_);
EXPECT_THAT(thread_id_to_input_indexing->ToString(thread_id_printer_),
MatchIndexingString(R"(
(th_x, th_y, th_z, bl_x, bl_y, bl_z)[chunk_id, unroll_id] ->
(((bl_x * 128 + th_x) floordiv 30) mod 20)
domain:
th_x in [0, 128)
th_y in [0, 1)
th_z in [0, 1)
bl_x in [0, 47)
bl_y in [0, 1)
bl_z in [0, 1)
chunk_id in [0, 1)
unroll_id in [0, 1)
th_x + bl_x * 128 in [0, 6000)
)"));
}
TEST_F(MlirLoopFusionTest, Constant_Broadcast) {
auto kHloString = R"(
HloModule module
bcast {
zero = bf16[] constant(0)
ROOT broadcast = bf16[2,16,48]{2,1,0} broadcast(zero), dimensions={}
}
ENTRY entry {
ROOT %fusion = bf16[2,16,48]{2,1,0} fusion(), kind=kLoop, calls=bcast
}
)";
TF_ASSERT_OK(EmitAndCheckIR(kHloString, R"(
)"));
EXPECT_TRUE(RunAndCompareNoHloPasses(kHloString, ErrorSpec{0}));
}
TEST_F(MlirLoopFusionTest, NoCodeDuplication) {
auto kHloString = R"(
HloModule test_module
%fused_computation (param: f32[6]) -> f32[2] {
%param = f32[6]{0} parameter(0)
%slice0.1 = f32[5]{0} slice(f32[6]{0} %param), slice={[0:5]}
%slice0.2 = f32[5]{0} slice(f32[6]{0} %param), slice={[1:6]}
%add0 = f32[5]{0} add(f32[5]{0} %slice0.1, f32[5]{0} %slice0.2)
%slice1.1 = f32[4]{0} slice(f32[5]{0} %add0), slice={[0:4]}
%slice1.2 = f32[4]{0} slice(f32[5]{0} %add0), slice={[1:5]}
%add1 = f32[4]{0} add(f32[4]{0} %slice1.1, f32[4]{0} %slice1.2)
%slice2.1 = f32[3]{0} slice(f32[4]{0} %add1), slice={[0:3]}
%slice2.2 = f32[3]{0} slice(f32[4]{0} %add1), slice={[1:4]}
%add2 = f32[3]{0} add(f32[3]{0} %slice2.1, f32[3]{0} %slice2.2)
%slice3.1 = f32[2]{0} slice(f32[3]{0} %add2), slice={[0:2]}
%slice3.2 = f32[2]{0} slice(f32[3]{0} %add2), slice={[1:3]}
ROOT %add3 = f32[2]{0} add(f32[2]{0} %slice3.1, f32[2]{0} %slice3.2)
}
ENTRY entry_computation {
p0 = f32[] parameter(0)
add = f32[] add(p0, p0)
broadcast = f32[6]{0} broadcast(add), dimensions={}
ROOT %fusion = f32[2]{0} fusion(broadcast), kind=kLoop, calls=%fused_computation
}
)";
TF_ASSERT_OK(EmitAndCheckIR(kHloString, R"(
)"));
EXPECT_TRUE(RunAndCompareNoHloPasses(kHloString, ErrorSpec{1e-3}));
}
TEST_F(MlirLoopFusionTest, TwoUsersConsistentIndexing) {
auto kHloString = R"(
HloModule test_module
%fused_computation (param: f32[6]) -> f32[2] {
%p0 = f32[2]{0} parameter(0)
%p1 = f32[2]{0} parameter(1)
%add = f32[2] add(%p0, %p1)
%sub = f32[2] subtract(%p0, %p1)
%mul = f32[2] multiply(%add, %sub)
%div = f32[2] divide(%add, %sub)
ROOT %atan2 = f32[2] atan2(%mul, %div)
}
ENTRY entry_computation {
p0 = f32[2] parameter(0)
p1 = f32[2] parameter(1)
ROOT %fusion = f32[2] fusion(p0, p1), kind=kLoop, calls=%fused_computation
}
)";
TF_ASSERT_OK(EmitAndCheckIR(kHloString, R"(
)"));
EXPECT_TRUE(RunAndCompareNoHloPasses(kHloString, ErrorSpec{1e-3}));
}
TEST_F(MlirLoopFusionTest, ComplexOps) {
auto kHloString = R"(
HloModule test_module
%fused_computation {
%p0 = f32[2]{0} parameter(0)
%p1 = f32[2]{0} parameter(1)
%p2 = c64[2]{0} parameter(2)
%complex = c64[2] complex(%p0, %p1)
%add = c64[2] add(%complex, %p2)
%cst = c64[2]{0} constant({(2.0, 0.0), (0.0, 2.0)})
ROOT %mul = c64[2] multiply(%add, %cst)
}
ENTRY entry_computation {
p0 = f32[2] parameter(0)
p1 = f32[2] parameter(1)
p2 = c64[2] parameter(2)
ROOT %fusion = c64[2] fusion(p0, p1, p2), kind=kLoop, calls=%fused_computation
}
)";
TF_ASSERT_OK(EmitAndCheckIR(kHloString, R"(
)"));
EXPECT_TRUE(RunAndCompareNoHloPasses(kHloString, ErrorSpec{1e-3}));
}
TEST_F(MlirLoopFusionTest, IotaCopyBitcastBroadcastReshapeReverseTranspose) {
auto kHloString = R"(
HloModule test_module
%fused_computation {
%iota = f32[10,20,30] iota(), iota_dimension=2
%copy = f32[10,20,30] copy(%iota)
%bitcast = s32[10,20,30] bitcast-convert(%copy)
%broadcast = s32[2,10,3,20,5,30,7] broadcast(%bitcast),
dimensions={1,3,5}
%reshape = s32[20,60,150,7] reshape(%broadcast)
%reverse = s32[20,60,150,7] reverse(%reshape), dimensions={2,3}
ROOT %transpose = s32[60,20,7,150] transpose(%reverse),
dimensions={1,0,3,2}
}
ENTRY entry_computation {
ROOT %fusion = s32[60,20,7,150] fusion(),
kind=kLoop, calls=%fused_computation
}
)";
TF_ASSERT_OK(EmitAndCheckIR(kHloString, R"(
)"));
EXPECT_TRUE(RunAndCompareNoHloPasses(kHloString, ErrorSpec{1e-3}));
}
TEST_F(MlirLoopFusionTest, VariadicReduce) {
auto kHloString = R"(
HloModule Test, is_scheduled=true
Add {
scalar_lhs.0 = f32[] parameter(0)
scalar_lhs.1 = f32[] parameter(1)
scalar_rhs.0 = f32[] parameter(2)
scalar_rhs.1 = f32[] parameter(3)
add = f32[] add(scalar_lhs.0, scalar_rhs.0)
mul = f32[] multiply(scalar_lhs.1, scalar_rhs.1)
ROOT t = (f32[], f32[]) tuple(add, mul)
}
fused_computation {
param_0 = f32[3,4,5]{2,1,0} parameter(0)
param_1 = f32[3,4,5]{2,1,0} parameter(1)
param_2 = f32[] parameter(2)
ROOT d.1 = (f32[4], f32[4]) reduce(f32[3,4,5]{2,1,0} param_0,
f32[3,4,5]{2,1,0} %param_1, f32[] param_2, f32[] param_2),
dimensions={0,2}, to_apply=Add
}
ENTRY main {
a = f32[3,4,5]{2,1,0} parameter(0)
b = f32[3,4,5]{2,1,0} parameter(1)
c = f32[] constant(0)
ROOT fusion = (f32[4]{0}, f32[4]{0}) fusion(a, b, c),
kind=kLoop, calls=fused_computation
}
)";
TF_ASSERT_OK(EmitAndCheckIR(kHloString, R"(
)"));
EXPECT_TRUE(RunAndCompareNoHloPasses(kHloString, ErrorSpec{1e-3}));
}
TEST_F(MlirLoopFusionTest, MinimumMaximum) {
auto kHloString = R"(
HloModule Test
fused_computation {
param0 = f64[] parameter(0)
param1 = f64[] parameter(1)
minimum = f64[] minimum(f64[] param0, f64[] param1)
maximum = f64[] maximum(f64[] param0, f64[] param1)
ROOT tuple = (f64[], f64[]) tuple(minimum, maximum)
}
ENTRY main {
param0 = f64[] parameter(0)
param1 = f64[] parameter(1)
ROOT fusion = (f64[], f64[]) fusion(f64[] param0, f64[] param1), kind=kLoop, calls=fused_computation
}
)";
TF_ASSERT_OK(EmitAndCheckIR(kHloString, R"(
)"));
EXPECT_TRUE(RunAndCompareNoHloPasses(kHloString, ErrorSpec{1e-3}));
}
TEST_F(MlirLoopFusionTest, TupleBitcast) {
auto kHloString = R"(
HloModule Test
fused_computation {
param0 = f64[8] parameter(0)
param1 = f64[8] parameter(1)
minimum = f64[8] minimum(param0, param1)
maximum = f64[8] maximum(param0, param1)
bc = f64[2, 4] bitcast(maximum)
ROOT tuple = (f64[8], f64[2,4]) tuple(minimum, bc)
}
ENTRY main {
param0 = f64[8] parameter(0)
param1 = f64[8] parameter(1)
ROOT fusion = (f64[8], f64[2,4]) fusion(param0, param1),
kind=kLoop, calls=fused_computation
}
)";
EXPECT_TRUE(RunAndCompareNoHloPasses(kHloString, ErrorSpec{1e-3}));
}
TEST_F(MlirLoopFusionTest, NestedTuple) {
auto kHloString = R"(
add {
scalar_lhs.0 = f32[] parameter(0)
scalar_lhs.1 = f32[] parameter(1)
scalar_rhs.0 = f32[] parameter(2)
scalar_rhs.1 = f32[] parameter(3)
add = f32[] add(scalar_lhs.0, scalar_rhs.0)
mul = f32[] multiply(scalar_lhs.1, scalar_rhs.1)
ROOT t = (f32[], f32[]) tuple(add, mul)
}
fused_computation {
param_0 = f32[3,4,5]{2,1,0} parameter(0)
param_1 = f32[3,4,5]{2,1,0} parameter(1)
param_2 = f32[] parameter(2)
param_3 = f32[4] parameter(3)
reduce = (f32[4], f32[4]) reduce(f32[3,4,5]{2,1,0} param_0,
f32[3,4,5]{2,1,0} %param_1, f32[] param_2, f32[] param_2),
dimensions={0,2}, to_apply=add
log = f32[4] log(param_3)
ROOT tuple = ((f32[4], f32[4]), f32[4]) tuple(reduce, log)
}
ENTRY main {
a = f32[3,4,5]{2,1,0} parameter(0)
b = f32[3,4,5]{2,1,0} parameter(1)
c = f32[] constant(0)
d = f32[4] parameter(2)
ROOT fusion = ((f32[4], f32[4]), f32[4]) fusion(a, b, c, d),
kind=kLoop, calls=fused_computation
}
)";
EXPECT_TRUE(RunAndCompareNoHloPasses(kHloString, ErrorSpec{1e-3}));
}
TEST_F(MlirLoopFusionTest, DynamicSliceWith64BitInput) {
constexpr auto kHloString = R"(
%fused_computation {
%p0 = s64[] parameter(0)
%p1 = f64[5] parameter(1)
ROOT slice = f64[4] dynamic-slice(%p1, %p0), dynamic_slice_sizes={4}
}
ENTRY main {
%c = s64[] constant(-1000000000000)
%p0 = f64[5] parameter(0)
ROOT %fusion = f64[4]{0} fusion(%c, %p0), kind=kInput, calls=%fused_computation
})";
TF_ASSERT_OK(EmitAndCheckIR(kHloString, R"(
)"));
EXPECT_TRUE(RunAndCompareNoHloPasses(kHloString, ErrorSpec{1e-3}));
}
}
}
} |
334 | #ifndef QUICHE_QUIC_QBONE_QBONE_PACKET_EXCHANGER_H_
#define QUICHE_QUIC_QBONE_QBONE_PACKET_EXCHANGER_H_
#include "quiche/quic/core/quic_packets.h"
#include "quiche/quic/qbone/qbone_client_interface.h"
#include "quiche/quic/qbone/qbone_packet_writer.h"
namespace quic {
class QbonePacketExchanger : public QbonePacketWriter {
public:
class Visitor {
public:
virtual ~Visitor() {}
virtual void OnReadError(const std::string& error) {}
virtual void OnWriteError(const std::string& error) {}
};
QbonePacketExchanger(Visitor* visitor, size_t max_pending_packets)
: visitor_(visitor), max_pending_packets_(max_pending_packets) {}
QbonePacketExchanger(const QbonePacketExchanger&) = delete;
QbonePacketExchanger& operator=(const QbonePacketExchanger&) = delete;
QbonePacketExchanger(QbonePacketExchanger&&) = delete;
QbonePacketExchanger& operator=(QbonePacketExchanger&&) = delete;
~QbonePacketExchanger() = default;
bool ReadAndDeliverPacket(QboneClientInterface* qbone_client);
void WritePacketToNetwork(const char* packet, size_t size) override;
void SetWritable();
private:
virtual std::unique_ptr<QuicData> ReadPacket(bool* blocked,
std::string* error) = 0;
virtual bool WritePacket(const char* packet, size_t size, bool* blocked,
std::string* error) = 0;
std::list<std::unique_ptr<QuicData>> packet_queue_;
Visitor* visitor_;
size_t max_pending_packets_;
bool write_blocked_ = false;
};
}
#endif
#include "quiche/quic/qbone/qbone_packet_exchanger.h"
#include <memory>
#include <string>
#include <utility>
namespace quic {
bool QbonePacketExchanger::ReadAndDeliverPacket(
QboneClientInterface* qbone_client) {
bool blocked = false;
std::string error;
std::unique_ptr<QuicData> packet = ReadPacket(&blocked, &error);
if (packet == nullptr) {
if (!blocked && visitor_) {
visitor_->OnReadError(error);
}
return false;
}
qbone_client->ProcessPacketFromNetwork(packet->AsStringPiece());
return true;
}
void QbonePacketExchanger::WritePacketToNetwork(const char* packet,
size_t size) {
bool blocked = false;
std::string error;
if (packet_queue_.empty() && !write_blocked_) {
if (WritePacket(packet, size, &blocked, &error)) {
return;
}
if (blocked) {
write_blocked_ = true;
} else {
QUIC_LOG_EVERY_N_SEC(ERROR, 60) << "Packet write failed: " << error;
if (visitor_) {
visitor_->OnWriteError(error);
}
}
}
if (packet_queue_.size() >= max_pending_packets_) {
return;
}
auto data_copy = new char[size];
memcpy(data_copy, packet, size);
packet_queue_.push_back(
std::make_unique<QuicData>(data_copy, size, true));
}
void QbonePacketExchanger::SetWritable() {
write_blocked_ = false;
while (!packet_queue_.empty()) {
bool blocked = false;
std::string error;
if (WritePacket(packet_queue_.front()->data(),
packet_queue_.front()->length(), &blocked, &error)) {
packet_queue_.pop_front();
} else {
if (!blocked && visitor_) {
visitor_->OnWriteError(error);
}
write_blocked_ = blocked;
return;
}
}
}
} | #include "quiche/quic/qbone/qbone_packet_exchanger.h"
#include <list>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "quiche/quic/platform/api/quic_test.h"
#include "quiche/quic/qbone/mock_qbone_client.h"
namespace quic {
namespace {
using ::testing::StrEq;
using ::testing::StrictMock;
const size_t kMaxPendingPackets = 2;
class MockVisitor : public QbonePacketExchanger::Visitor {
public:
MOCK_METHOD(void, OnReadError, (const std::string&), (override));
MOCK_METHOD(void, OnWriteError, (const std::string&), (override));
};
class FakeQbonePacketExchanger : public QbonePacketExchanger {
public:
using QbonePacketExchanger::QbonePacketExchanger;
void AddPacketToBeRead(std::unique_ptr<QuicData> packet) {
packets_to_be_read_.push_back(std::move(packet));
}
void SetReadError(const std::string& error) { read_error_ = error; }
void ForceWriteFailure(bool blocked, const std::string& error) {
write_blocked_ = blocked;
write_error_ = error;
}
const std::vector<std::string>& packets_written() const {
return packets_written_;
}
private:
std::unique_ptr<QuicData> ReadPacket(bool* blocked,
std::string* error) override {
*blocked = false;
if (packets_to_be_read_.empty()) {
*blocked = read_error_.empty();
*error = read_error_;
return nullptr;
}
std::unique_ptr<QuicData> packet = std::move(packets_to_be_read_.front());
packets_to_be_read_.pop_front();
return packet;
}
bool WritePacket(const char* packet, size_t size, bool* blocked,
std::string* error) override {
*blocked = false;
if (write_blocked_ || !write_error_.empty()) {
*blocked = write_blocked_;
*error = write_error_;
return false;
}
packets_written_.push_back(std::string(packet, size));
return true;
}
std::string read_error_;
std::list<std::unique_ptr<QuicData>> packets_to_be_read_;
std::string write_error_;
bool write_blocked_ = false;
std::vector<std::string> packets_written_;
};
TEST(QbonePacketExchangerTest,
ReadAndDeliverPacketDeliversPacketToQboneClient) {
StrictMock<MockVisitor> visitor;
FakeQbonePacketExchanger exchanger(&visitor, kMaxPendingPackets);
StrictMock<MockQboneClient> client;
std::string packet = "data";
exchanger.AddPacketToBeRead(
std::make_unique<QuicData>(packet.data(), packet.length()));
EXPECT_CALL(client, ProcessPacketFromNetwork(StrEq("data")));
EXPECT_TRUE(exchanger.ReadAndDeliverPacket(&client));
}
TEST(QbonePacketExchangerTest,
ReadAndDeliverPacketNotifiesVisitorOnReadFailure) {
MockVisitor visitor;
FakeQbonePacketExchanger exchanger(&visitor, kMaxPendingPackets);
MockQboneClient client;
std::string io_error = "I/O error";
exchanger.SetReadError(io_error);
EXPECT_CALL(visitor, OnReadError(StrEq(io_error))).Times(1);
EXPECT_FALSE(exchanger.ReadAndDeliverPacket(&client));
}
TEST(QbonePacketExchangerTest,
ReadAndDeliverPacketDoesNotNotifyVisitorOnBlockedIO) {
MockVisitor visitor;
FakeQbonePacketExchanger exchanger(&visitor, kMaxPendingPackets);
MockQboneClient client;
EXPECT_FALSE(exchanger.ReadAndDeliverPacket(&client));
}
TEST(QbonePacketExchangerTest,
WritePacketToNetworkWritesDirectlyToNetworkWhenNotBlocked) {
MockVisitor visitor;
FakeQbonePacketExchanger exchanger(&visitor, kMaxPendingPackets);
MockQboneClient client;
std::string packet = "data";
exchanger.WritePacketToNetwork(packet.data(), packet.length());
ASSERT_EQ(exchanger.packets_written().size(), 1);
EXPECT_THAT(exchanger.packets_written()[0], StrEq(packet));
}
TEST(QbonePacketExchangerTest,
WritePacketToNetworkQueuesPacketsAndProcessThemLater) {
MockVisitor visitor;
FakeQbonePacketExchanger exchanger(&visitor, kMaxPendingPackets);
MockQboneClient client;
exchanger.ForceWriteFailure(true, "");
std::vector<std::string> packets = {"packet0", "packet1"};
for (int i = 0; i < packets.size(); i++) {
exchanger.WritePacketToNetwork(packets[i].data(), packets[i].length());
}
ASSERT_TRUE(exchanger.packets_written().empty());
exchanger.ForceWriteFailure(false, "");
exchanger.SetWritable();
ASSERT_EQ(exchanger.packets_written().size(), 2);
for (int i = 0; i < packets.size(); i++) {
EXPECT_THAT(exchanger.packets_written()[i], StrEq(packets[i]));
}
}
TEST(QbonePacketExchangerTest,
SetWritableContinuesProcessingPacketIfPreviousCallBlocked) {
MockVisitor visitor;
FakeQbonePacketExchanger exchanger(&visitor, kMaxPendingPackets);
MockQboneClient client;
exchanger.ForceWriteFailure(true, "");
std::vector<std::string> packets = {"packet0", "packet1"};
for (int i = 0; i < packets.size(); i++) {
exchanger.WritePacketToNetwork(packets[i].data(), packets[i].length());
}
ASSERT_TRUE(exchanger.packets_written().empty());
exchanger.SetWritable();
ASSERT_TRUE(exchanger.packets_written().empty());
exchanger.ForceWriteFailure(false, "");
exchanger.SetWritable();
ASSERT_EQ(exchanger.packets_written().size(), 2);
for (int i = 0; i < packets.size(); i++) {
EXPECT_THAT(exchanger.packets_written()[i], StrEq(packets[i]));
}
}
TEST(QbonePacketExchangerTest, WritePacketToNetworkDropsPacketIfQueueIfFull) {
std::vector<std::string> packets = {"packet0", "packet1", "packet2"};
size_t queue_size = packets.size() - 1;
MockVisitor visitor;
FakeQbonePacketExchanger exchanger(&visitor, queue_size);
MockQboneClient client;
exchanger.ForceWriteFailure(true, "");
for (int i = 0; i < packets.size(); i++) {
exchanger.WritePacketToNetwork(packets[i].data(), packets[i].length());
}
ASSERT_TRUE(exchanger.packets_written().empty());
exchanger.ForceWriteFailure(false, "");
exchanger.SetWritable();
ASSERT_EQ(exchanger.packets_written().size(), queue_size);
for (int i = 0; i < queue_size; i++) {
EXPECT_THAT(exchanger.packets_written()[i], StrEq(packets[i]));
}
}
TEST(QbonePacketExchangerTest, WriteErrorsGetNotified) {
MockVisitor visitor;
FakeQbonePacketExchanger exchanger(&visitor, kMaxPendingPackets);
MockQboneClient client;
std::string packet = "data";
std::string io_error = "I/O error";
exchanger.ForceWriteFailure(false, io_error);
EXPECT_CALL(visitor, OnWriteError(StrEq(io_error))).Times(1);
exchanger.WritePacketToNetwork(packet.data(), packet.length());
ASSERT_TRUE(exchanger.packets_written().empty());
exchanger.ForceWriteFailure(true, "");
exchanger.WritePacketToNetwork(packet.data(), packet.length());
std::string sys_error = "sys error";
exchanger.ForceWriteFailure(false, sys_error);
EXPECT_CALL(visitor, OnWriteError(StrEq(sys_error))).Times(1);
exchanger.SetWritable();
ASSERT_TRUE(exchanger.packets_written().empty());
}
TEST(QbonePacketExchangerTest, NullVisitorDoesntCrash) {
FakeQbonePacketExchanger exchanger(nullptr, kMaxPendingPackets);
MockQboneClient client;
std::string packet = "data";
std::string io_error = "I/O error";
exchanger.SetReadError(io_error);
EXPECT_FALSE(exchanger.ReadAndDeliverPacket(&client));
exchanger.ForceWriteFailure(false, io_error);
exchanger.WritePacketToNetwork(packet.data(), packet.length());
EXPECT_TRUE(exchanger.packets_written().empty());
}
}
} |
335 | #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);
}
} |
336 | #ifndef TENSORFLOW_LITE_TOCO_TOCO_CONVERT_H_
#define TENSORFLOW_LITE_TOCO_TOCO_CONVERT_H_
#include <string>
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/lite/toco/args.h"
#include "tensorflow/lite/toco/model_flags.pb.h"
#include "tensorflow/lite/toco/toco_flags.pb.h"
namespace toco {
tensorflow::Status Convert(const std::string& graph_def_contents,
const TocoFlags& toco_flags,
const ModelFlags& model_flags,
std::string* output_file_contents,
int64_t* arithmetic_ops_count = nullptr);
tensorflow::Status Convert(const ParsedTocoFlags& parsed_toco_flags,
const ParsedModelFlags& parsed_model_flags);
}
#endif
#include <cstdio>
#include <memory>
#include <string>
#include "absl/strings/string_view.h"
#include "tensorflow/lite/toco/model.h"
#include "tensorflow/lite/toco/model_cmdline_flags.h"
#include "tensorflow/lite/toco/model_flags.pb.h"
#include "tensorflow/lite/toco/toco_cmdline_flags.h"
#include "tensorflow/lite/toco/toco_flags.pb.h"
#include "tensorflow/lite/toco/toco_port.h"
#include "tensorflow/lite/toco/toco_tooling.h"
#include "tensorflow/lite/toco/toco_types.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/platform/logging.h"
namespace toco {
namespace {
void CheckOutputFilePermissions(const Arg<std::string>& output_file) {
QCHECK(output_file.specified()) << "Missing required flag --output_file.\n";
QCHECK(port::file::Writable(output_file.value()).ok())
<< "Specified output_file is not writable: " << output_file.value()
<< ".\n";
}
void CheckFrozenModelPermissions(const Arg<std::string>& input_file) {
QCHECK(input_file.specified()) << "Missing required flag --input_file.\n";
QCHECK(port::file::Exists(input_file.value(), port::file::Defaults()).ok())
<< "Specified input_file does not exist: " << input_file.value() << ".\n";
QCHECK(port::file::Readable(input_file.value(), port::file::Defaults()).ok())
<< "Specified input_file exists, but is not readable: "
<< input_file.value() << ".\n";
}
void ReadInputData(const ParsedTocoFlags& parsed_toco_flags,
const ParsedModelFlags& parsed_model_flags,
std::string* graph_def_contents) {
port::CheckInitGoogleIsDone("InitGoogle is not done yet.\n");
QCHECK(!parsed_toco_flags.savedmodel_directory.specified())
<< "Use `tensorflow/lite/python/tflite_convert` script with "
<< "SavedModel directories.\n";
CheckFrozenModelPermissions(parsed_toco_flags.input_file);
CHECK(port::file::GetContents(parsed_toco_flags.input_file.value(),
graph_def_contents, port::file::Defaults())
.ok());
}
}
tensorflow::Status Convert(const std::string& graph_def_contents,
const TocoFlags& toco_flags,
const ModelFlags& model_flags,
std::string* output_file_contents,
int64_t* arithmetic_ops_count = nullptr) {
std::unique_ptr<Model> model =
Import(toco_flags, model_flags, graph_def_contents);
TF_RETURN_IF_ERROR(TransformWithStatus(toco_flags, model.get()));
TF_RETURN_IF_ERROR(Export(toco_flags, *model, toco_flags.allow_custom_ops(),
output_file_contents));
if (arithmetic_ops_count != nullptr) {
*arithmetic_ops_count = model->ArithmeticOpsCount();
}
return absl::OkStatus();
}
tensorflow::Status Convert(const ParsedTocoFlags& parsed_toco_flags,
const ParsedModelFlags& parsed_model_flags) {
ModelFlags model_flags;
ReadModelFlagsFromCommandLineFlags(parsed_model_flags, &model_flags);
TocoFlags toco_flags;
ReadTocoFlagsFromCommandLineFlags(parsed_toco_flags, &toco_flags);
std::string graph_def_contents;
ReadInputData(parsed_toco_flags, parsed_model_flags, &graph_def_contents);
CheckOutputFilePermissions(parsed_toco_flags.output_file);
std::string output_file_contents;
TF_RETURN_IF_ERROR(Convert(graph_def_contents, toco_flags, model_flags,
&output_file_contents));
TF_RETURN_IF_ERROR(
port::file::SetContents(parsed_toco_flags.output_file.value(),
output_file_contents, port::file::Defaults()));
return tensorflow::Status();
}
} | #include "tensorflow/lite/toco/toco_convert.h"
#include <string>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "tensorflow/lite/testing/util.h"
#include "tensorflow/lite/toco/toco_port.h"
namespace toco {
namespace {
TEST(TocoTest, MissingInputFile) {
ParsedTocoFlags toco_flags;
ParsedModelFlags model_flags;
EXPECT_DEATH(EXPECT_TRUE(Convert(toco_flags, model_flags).ok()),
"Missing required flag --input_file");
}
TEST(TocoTest, BadInputFormat) {
TocoFlags toco_flags;
ModelFlags model_flags;
std::string input;
std::string output;
EXPECT_DEATH(
EXPECT_TRUE(Convert(input, toco_flags, model_flags, &output).ok()),
"Unhandled input_format='FILE_FORMAT_UNKNOWN'");
}
TEST(TocoTest, MissingOutputArrays) {
TocoFlags toco_flags;
ModelFlags model_flags;
toco_flags.set_input_format(TENSORFLOW_GRAPHDEF);
std::string input;
std::string output;
EXPECT_DEATH(
EXPECT_TRUE(Convert(input, toco_flags, model_flags, &output).ok()),
"This model does not define output arrays, so a --output_arrays "
"flag must be given on the command-line");
}
TEST(TocoTest, BadOutputArray) {
TocoFlags toco_flags;
ModelFlags model_flags;
toco_flags.set_input_format(TENSORFLOW_GRAPHDEF);
model_flags.add_output_arrays("output1");
std::string input;
std::string output;
EXPECT_DEATH(
EXPECT_TRUE(Convert(input, toco_flags, model_flags, &output).ok()),
"Specified output array .output1. is not produced by any op "
"in this graph. Is it a typo");
}
TEST(TocoTest, BadOutputFormat) {
TocoFlags toco_flags;
ModelFlags model_flags;
toco_flags.set_input_format(TENSORFLOW_GRAPHDEF);
model_flags.add_output_arrays("output1");
std::string input = R"GraphDef(
node {
name: "output1"
input: "input1"
input: "input2"
op: "Sub"
attr { key: "T" value { type: DT_FLOAT } }
}
)GraphDef";
std::string output;
EXPECT_DEATH(
EXPECT_TRUE(Convert(input, toco_flags, model_flags, &output).ok()),
"Unhandled output_format='FILE_FORMAT_UNKNOWN'");
}
TEST(TocoTest, SimpleFloatModel) {
TocoFlags toco_flags;
ModelFlags model_flags;
toco_flags.set_input_format(TENSORFLOW_GRAPHDEF);
toco_flags.set_output_format(TENSORFLOW_GRAPHDEF);
model_flags.add_output_arrays("output1");
std::string input = R"GraphDef(
node {
name: "input1"
op: "Placeholder"
attr { key: "dtype" value { type: DT_INT64 } }
}
node {
name: "input2"
op: "Placeholder"
attr { key: "dtype" value { type: DT_INT64 } }
}
node {
name: "output1"
input: "input1"
input: "input2"
op: "Sub"
attr { key: "T" value { type: DT_FLOAT } }
}
)GraphDef";
std::string output;
EXPECT_TRUE(Convert(input, toco_flags, model_flags, &output).ok());
EXPECT_TRUE(!output.empty());
}
TEST(TocoTest, TransientStringTensors) {
TocoFlags toco_flags;
ModelFlags model_flags;
toco_flags.set_input_format(TENSORFLOW_GRAPHDEF);
toco_flags.set_output_format(TFLITE);
toco::InputArray* input_1 = model_flags.add_input_arrays();
input_1->set_name("input1");
toco::InputArray* indices_1 = model_flags.add_input_arrays();
indices_1->set_name("indices1");
model_flags.add_output_arrays("output1");
std::string input = R"GraphDef(
node {
name: "input1"
op: "Placeholder"
attr { key: "dtype" value { type: DT_STRING } }
attr { key: "shape" value { shape { dim { size:1 }}}}
}
node {
name: "indices1"
op: "Placeholder"
attr { key: "dtype" value { type: DT_INT64 } }
}
node {
name: "intermediate1"
op: "Gather"
input: "input1"
input: "indices1"
attr { key: "Tparams" value { type: DT_STRING } }
attr { key: "Tindices" value { type: DT_INT64 } }
}
node {
name: "output1"
op: "Gather"
input: "intermediate1"
input: "indices2"
attr { key: "Tparams" value { type: DT_STRING } }
attr { key: "Tindices" value { type: DT_INT64 } }
}
)GraphDef";
std::string output;
EXPECT_TRUE(Convert(input, toco_flags, model_flags, &output).ok());
EXPECT_TRUE(!output.empty());
}
}
}
int main(int argc, char** argv) {
::tflite::LogToStderr();
::testing::InitGoogleTest(&argc, argv);
::toco::port::InitGoogleWasDoneElsewhere();
return RUN_ALL_TESTS();
} |
337 | #ifndef THIRD_PARTY_CEL_CPP_COMMON_VALUES_STRING_VALUE_H_
#define THIRD_PARTY_CEL_CPP_COMMON_VALUES_STRING_VALUE_H_
#include <cstddef>
#include <ostream>
#include <string>
#include <type_traits>
#include <utility>
#include "absl/base/attributes.h"
#include "absl/meta/type_traits.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/cord.h"
#include "absl/strings/string_view.h"
#include "common/any.h"
#include "common/internal/arena_string.h"
#include "common/internal/shared_byte_string.h"
#include "common/json.h"
#include "common/type.h"
#include "common/type_manager.h"
#include "common/value_kind.h"
#include "common/values/values.h"
namespace cel {
class Value;
class ValueView;
class ValueManager;
class StringValue;
class StringValueView;
class TypeManager;
class StringValue final {
public:
using view_alternative_type = StringValueView;
static constexpr ValueKind kKind = ValueKind::kString;
static StringValue Concat(ValueManager&, StringValueView lhs,
StringValueView rhs);
explicit StringValue(absl::Cord value) noexcept : value_(std::move(value)) {}
explicit StringValue(absl::string_view value) noexcept
: value_(absl::Cord(value)) {}
explicit StringValue(common_internal::ArenaString value) noexcept
: value_(value) {}
explicit StringValue(common_internal::SharedByteString value) noexcept
: value_(std::move(value)) {}
template <typename T, typename = std::enable_if_t<std::is_same_v<
absl::remove_cvref_t<T>, std::string>>>
explicit StringValue(T&& data) : value_(absl::Cord(std::forward<T>(data))) {}
#if ABSL_HAVE_ATTRIBUTE(enable_if)
template <size_t N>
explicit StringValue(const char (&data)[N])
__attribute__((enable_if(::cel::common_internal::IsStringLiteral(data),
"chosen when 'data' is a string literal")))
: value_(absl::string_view(data)) {}
#endif
explicit StringValue(StringValueView value) noexcept;
StringValue() = default;
StringValue(const StringValue&) = default;
StringValue(StringValue&&) = default;
StringValue& operator=(const StringValue&) = default;
StringValue& operator=(StringValue&&) = default;
constexpr ValueKind kind() const { return kKind; }
StringType GetType(TypeManager&) const { return StringType(); }
absl::string_view GetTypeName() const { return StringType::kName; }
std::string DebugString() const;
absl::StatusOr<size_t> GetSerializedSize(AnyToJsonConverter&) const;
absl::Status SerializeTo(AnyToJsonConverter&, absl::Cord& value) const;
absl::StatusOr<absl::Cord> Serialize(AnyToJsonConverter&) const;
absl::StatusOr<std::string> GetTypeUrl(
absl::string_view prefix = kTypeGoogleApisComPrefix) const;
absl::StatusOr<Any> ConvertToAny(
AnyToJsonConverter&,
absl::string_view prefix = kTypeGoogleApisComPrefix) const;
absl::StatusOr<Json> ConvertToJson(AnyToJsonConverter&) const;
absl::Status Equal(ValueManager& value_manager, ValueView other,
Value& result) const;
absl::StatusOr<Value> Equal(ValueManager& value_manager,
ValueView other) const;
bool IsZeroValue() const {
return NativeValue([](const auto& value) -> bool { return value.empty(); });
}
std::string NativeString() const { return value_.ToString(); }
absl::string_view NativeString(
std::string& scratch
ABSL_ATTRIBUTE_LIFETIME_BOUND) const ABSL_ATTRIBUTE_LIFETIME_BOUND {
return value_.ToString(scratch);
}
absl::Cord NativeCord() const { return value_.ToCord(); }
template <typename Visitor>
std::common_type_t<std::invoke_result_t<Visitor, absl::string_view>,
std::invoke_result_t<Visitor, const absl::Cord&>>
NativeValue(Visitor&& visitor) const {
return value_.Visit(std::forward<Visitor>(visitor));
}
void swap(StringValue& other) noexcept {
using std::swap;
swap(value_, other.value_);
}
size_t Size() const;
bool IsEmpty() const;
bool Equals(absl::string_view string) const;
bool Equals(const absl::Cord& string) const;
bool Equals(StringValueView string) const;
int Compare(absl::string_view string) const;
int Compare(const absl::Cord& string) const;
int Compare(StringValueView string) const;
std::string ToString() const { return NativeString(); }
absl::Cord ToCord() const { return NativeCord(); }
template <typename H>
friend H AbslHashValue(H state, const StringValue& string) {
return H::combine(std::move(state), string.value_);
}
friend bool operator==(const StringValue& lhs, const StringValue& rhs) {
return lhs.value_ == rhs.value_;
}
friend bool operator<(const StringValue& lhs, const StringValue& rhs) {
return lhs.value_ < rhs.value_;
}
private:
friend class StringValueView;
friend const common_internal::SharedByteString&
common_internal::AsSharedByteString(const StringValue& value);
common_internal::SharedByteString value_;
};
inline void swap(StringValue& lhs, StringValue& rhs) noexcept { lhs.swap(rhs); }
inline bool operator==(const StringValue& lhs, absl::string_view rhs) {
return lhs.Equals(rhs);
}
inline bool operator==(absl::string_view lhs, const StringValue& rhs) {
return rhs == lhs;
}
inline bool operator!=(const StringValue& lhs, absl::string_view rhs) {
return !operator==(lhs, rhs);
}
inline bool operator!=(absl::string_view lhs, const StringValue& rhs) {
return !operator==(lhs, rhs);
}
inline bool operator!=(const StringValue& lhs, const StringValue& rhs) {
return !operator==(lhs, rhs);
}
inline std::ostream& operator<<(std::ostream& out, const StringValue& value) {
return out << value.DebugString();
}
class StringValueView final {
public:
using alternative_type = StringValue;
static constexpr ValueKind kKind = StringValue::kKind;
explicit StringValueView(
const absl::Cord& value ABSL_ATTRIBUTE_LIFETIME_BOUND) noexcept
: value_(value) {}
explicit StringValueView(absl::string_view value) noexcept : value_(value) {}
explicit StringValueView(common_internal::ArenaString value) noexcept
: value_(value) {}
explicit StringValueView(common_internal::SharedByteStringView value) noexcept
: value_(value) {}
StringValueView(
const StringValue& value ABSL_ATTRIBUTE_LIFETIME_BOUND) noexcept
: value_(value.value_) {}
StringValueView& operator=(
const StringValue& value ABSL_ATTRIBUTE_LIFETIME_BOUND) {
value_ = value.value_;
return *this;
}
StringValueView& operator=(StringValue&&) = delete;
StringValueView() = default;
StringValueView(const StringValueView&) = default;
StringValueView(StringValueView&&) = default;
StringValueView& operator=(const StringValueView&) = default;
StringValueView& operator=(StringValueView&&) = default;
constexpr ValueKind kind() const { return kKind; }
StringType GetType(TypeManager&) const { return StringType(); }
absl::string_view GetTypeName() const { return StringType::kName; }
std::string DebugString() const;
absl::StatusOr<size_t> GetSerializedSize(AnyToJsonConverter&) const;
absl::Status SerializeTo(AnyToJsonConverter&, absl::Cord& value) const;
absl::StatusOr<absl::Cord> Serialize(AnyToJsonConverter&) const;
absl::StatusOr<std::string> GetTypeUrl(
absl::string_view prefix = kTypeGoogleApisComPrefix) const;
absl::StatusOr<Any> ConvertToAny(
AnyToJsonConverter&,
absl::string_view prefix = kTypeGoogleApisComPrefix) const;
absl::StatusOr<Json> ConvertToJson(AnyToJsonConverter&) const;
absl::Status Equal(ValueManager& value_manager, ValueView other,
Value& result) const;
absl::StatusOr<Value> Equal(ValueManager& value_manager,
ValueView other) const;
bool IsZeroValue() const {
return NativeValue([](const auto& value) -> bool { return value.empty(); });
}
std::string NativeString() const { return value_.ToString(); }
absl::string_view NativeString(
std::string& scratch
ABSL_ATTRIBUTE_LIFETIME_BOUND) const ABSL_ATTRIBUTE_LIFETIME_BOUND {
return value_.ToString(scratch);
}
absl::Cord NativeCord() const { return value_.ToCord(); }
template <typename Visitor>
std::common_type_t<std::invoke_result_t<Visitor, absl::string_view>,
std::invoke_result_t<Visitor, const absl::Cord&>>
NativeValue(Visitor&& visitor) const {
return value_.Visit(std::forward<Visitor>(visitor));
}
void swap(StringValueView& other) noexcept {
using std::swap;
swap(value_, other.value_);
}
size_t Size() const;
bool IsEmpty() const;
bool Equals(absl::string_view string) const;
bool Equals(const absl::Cord& string) const;
bool Equals(StringValueView string) const;
int Compare(absl::string_view string) const;
int Compare(const absl::Cord& string) const;
int Compare(StringValueView string) const;
std::string ToString() const { return NativeString(); }
absl::Cord ToCord() const { return NativeCord(); }
template <typename H>
friend H AbslHashValue(H state, StringValueView string) {
return H::combine(std::move(state), string.value_);
}
friend bool operator==(StringValueView lhs, StringValueView rhs) {
return lhs.value_ == rhs.value_;
}
friend bool operator<(StringValueView lhs, StringValueView rhs) {
return lhs.value_ < rhs.value_;
}
private:
friend class StringValue;
friend common_internal::SharedByteStringView
common_internal::AsSharedByteStringView(StringValueView value);
common_internal::SharedByteStringView value_;
};
inline void swap(StringValueView& lhs, StringValueView& rhs) noexcept {
lhs.swap(rhs);
}
inline bool operator==(StringValueView lhs, absl::string_view rhs) {
return lhs == StringValueView(rhs);
}
inline bool operator==(absl::string_view lhs, StringValueView rhs) {
return StringValueView(lhs) == rhs;
}
inline bool operator==(StringValueView lhs, const absl::Cord& rhs) {
return lhs == StringValueView(rhs);
}
inline bool operator==(const absl::Cord& lhs, StringValueView rhs) {
return StringValueView(lhs) == rhs;
}
inline bool operator!=(StringValueView lhs, StringValueView rhs) {
return !operator==(lhs, rhs);
}
inline bool operator!=(StringValueView lhs, absl::string_view rhs) {
return !operator==(lhs, rhs);
}
inline bool operator!=(absl::string_view lhs, StringValueView rhs) {
return !operator==(lhs, rhs);
}
inline bool operator!=(StringValueView lhs, const absl::Cord& rhs) {
return !operator==(lhs, rhs);
}
inline bool operator!=(const absl::Cord& lhs, StringValueView rhs) {
return !operator==(lhs, rhs);
}
inline bool operator<(StringValueView lhs, absl::string_view rhs) {
return lhs < StringValueView(rhs);
}
inline bool operator<(absl::string_view lhs, StringValueView rhs) {
return StringValueView(lhs) < rhs;
}
inline bool operator<(StringValueView lhs, const absl::Cord& rhs) {
return lhs < StringValueView(rhs);
}
inline bool operator<(const absl::Cord& lhs, StringValueView rhs) {
return StringValueView(lhs) < rhs;
}
inline std::ostream& operator<<(std::ostream& out, StringValueView value) {
return out << value.DebugString();
}
inline StringValue::StringValue(StringValueView value) noexcept
: value_(value.value_) {}
inline StringValue StringValue::Concat(ValueManager&, StringValueView lhs,
StringValueView rhs) {
absl::Cord result;
result.Append(lhs.ToCord());
result.Append(rhs.ToCord());
return StringValue(std::move(result));
}
namespace common_internal {
inline const SharedByteString& AsSharedByteString(const StringValue& value) {
return value.value_;
}
inline SharedByteStringView AsSharedByteStringView(StringValueView value) {
return value.value_;
}
}
}
#endif
#include <cstddef>
#include <string>
#include <utility>
#include "absl/functional/overload.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/cord.h"
#include "absl/strings/string_view.h"
#include "common/any.h"
#include "common/casting.h"
#include "common/json.h"
#include "common/value.h"
#include "internal/serialize.h"
#include "internal/status_macros.h"
#include "internal/strings.h"
#include "internal/utf8.h"
namespace cel {
namespace {
template <typename Bytes>
std::string StringDebugString(const Bytes& value) {
return value.NativeValue(absl::Overload(
[](absl::string_view string) -> std::string {
return internal::FormatStringLiteral(string);
},
[](const absl::Cord& cord) -> std::string {
if (auto flat = cord.TryFlat(); flat.has_value()) {
return internal::FormatStringLiteral(*flat);
}
return internal::FormatStringLiteral(static_cast<std::string>(cord));
}));
}
}
std::string StringValue::DebugString() const {
return StringDebugString(*this);
}
absl::StatusOr<size_t> StringValue::GetSerializedSize(
AnyToJsonConverter&) const {
return NativeValue([](const auto& bytes) -> size_t {
return internal::SerializedStringValueSize(bytes);
});
}
absl::Status StringValue::SerializeTo(AnyToJsonConverter&,
absl::Cord& value) const {
return NativeValue([&value](const auto& bytes) -> absl::Status {
return internal::SerializeStringValue(bytes, value);
});
}
absl::StatusOr<absl::Cord> StringValue::Serialize(
AnyToJsonConverter& value_manager) const {
absl::Cord value;
CEL_RETURN_IF_ERROR(SerializeTo(value_manager, value));
return value;
}
absl::StatusOr<std::string> StringValue::GetTypeUrl(
absl::string_view prefix) const {
return MakeTypeUrlWithPrefix(prefix, "google.protobuf.StringValue");
}
absl::StatusOr<Any> StringValue::ConvertToAny(AnyToJsonConverter& value_manager,
absl::string_view prefix) const {
CEL_ASSIGN_OR_RETURN(auto value, Serialize(value_manager));
CEL_ASSIGN_OR_RETURN(auto type_url, GetTypeUrl(prefix));
return MakeAny(std::move(type_url), std::move(value));
}
absl::StatusOr<Json> StringValue::ConvertToJson(AnyToJsonConverter&) const {
return NativeCord();
}
absl::Status StringValue::Equal(ValueManager&, ValueView other,
Value& result) const {
if (auto other_value = As<StringValueView>(other); other_value.has_value()) {
result = NativeValue([other_value](const auto& value) -> BoolValue {
return other_value->NativeValue(
[&value](const auto& other_value) -> BoolValue {
return BoolValue{value == other_value};
});
});
return absl::OkStatus();
}
result = BoolValueView{false};
return absl::OkStatus();
}
size_t StringValue::Size() const {
return NativeValue([](const auto& alternative) -> size_t {
return internal::Utf8CodePointCount(alternative);
});
}
bool StringValue::IsEmpty() const {
return NativeValue(
[](const auto& alternative) -> bool { return alternative.empty(); });
}
bool StringValue::Equals(absl::string_view string) const {
return NativeValue([string](const auto& alternative) -> bool {
return alternative == string;
});
}
bool StringValue::Equals(const absl::Cord& string) const {
return NativeValue([&string](const auto& alternative) -> bool {
return alternative == string;
});
}
bool StringValue::Equals(StringValueView string) const {
return string.NativeValue(
[this](const auto& alternative) -> bool { return Equals(alternative); });
}
namespace {
int CompareImpl(absl::string_view lhs, absl::string_view rhs) {
return lhs.compare(rhs);
}
int CompareImpl(absl::string_view lhs, const absl::Cord& rhs) {
return -rhs.Compare(lhs);
}
int CompareImpl(const absl::Cord& lhs, absl::string_view rhs) {
return lhs.Compare(rhs);
}
int CompareImpl(const absl::Cord& lhs, const absl::Cord& rhs) {
return lhs.Compare(rhs);
}
}
int StringValue::Compare(absl::string_view string) const {
return NativeValue([string](const auto& alternative) -> int {
return CompareImpl(alternative, string);
});
}
int StringValue::Compare(const absl::Cord& string) const {
return NativeValue([&string](const auto& alternative) -> int {
return CompareImpl(alternative, string);
});
}
int StringValue::Compare(StringValueView string) const {
return string.NativeValue(
[this](const auto& alternative) -> int { return Compare(alternative); });
}
std::string StringValueView::DebugString() const {
return StringDebugString(*this);
}
absl::StatusOr<size_t> StringValueView::GetSerializedSize(
AnyToJsonConverter&) const {
return NativeValue([](const auto& bytes) -> size_t {
return internal::SerializedStringValueSize(bytes);
});
}
absl::Status StringValueView::SerializeTo(AnyToJsonConverter&,
absl::Cord& value) const {
return NativeValue([&value](const auto& bytes) -> absl::Status {
return internal::SerializeStringValue(bytes, value);
});
}
absl::StatusOr<absl::Cord> StringValueView::Serialize(
AnyToJsonConverter& value_manager) const {
absl::Cord value;
CEL_RETURN_IF_ERROR(SerializeTo(value_manager, value));
return value;
}
absl::StatusOr<std::string> StringValueView::GetTypeUrl(
absl::string_view prefix) const {
return MakeTypeUrlWithPrefix(prefix, "google.protobuf.StringValue");
}
absl::StatusOr<Any> StringValueView::ConvertToAny(
AnyToJsonConverter& value_manager, absl::string_view prefix) const {
CEL_ASSIGN_OR_RETURN(auto value, Serialize(value_manager));
CEL_ASSIGN_OR_RETURN(auto type_url, GetTypeUrl(prefix));
return MakeAny(std::move(type_url), std::move(value));
}
absl::StatusOr<Json> StringValueView::ConvertToJson(AnyToJsonConverter&) const {
return NativeCord();
}
absl::Status StringValueView::Equal(ValueManager&, ValueView other,
Value& result) const {
if (auto other_value = As<StringValueView>(other); other_value.has_value()) {
result = NativeValue([other_value](const auto& value) -> BoolValue {
return other_value->NativeValue(
[&value](const auto& other_value) -> BoolValue {
return BoolValue{value == other_value};
});
});
return absl::OkStatus();
}
result = BoolValueView{false};
return absl::OkStatus();
}
size_t StringValueView::Size() const {
return NativeValue([](const auto& alternative) -> size_t {
return internal::Utf8CodePointCount(alternative);
});
}
bool StringValueView::IsEmpty() const {
return NativeValue(
[](const auto& alternative) -> bool { return alternative.empty(); });
}
bool StringValueView::Equals(absl::string_view string) const {
return NativeValue([string](const auto& alternative) -> bool {
return alternative == string;
});
}
bool StringValueView::Equals(const absl::Cord& string) const {
return NativeValue([&string](const auto& alternative) -> bool {
return alternative == string;
});
}
bool StringValueView::Equals(StringValueView string) const {
return string.NativeValue(
[this](const auto& alternative) -> bool { return Equals(alternative); });
}
int StringValueView::Compare(absl::string_view string) const {
return NativeValue([string](const auto& alternative) -> int {
return CompareImpl(alternative, string);
});
}
int StringValueView::Compare(const absl::Cord& string) const {
return NativeValue([&string](const auto& alternative) -> int {
return CompareImpl(alternative, string);
});
}
int StringValueView::Compare(StringValueView string) const {
return string.NativeValue(
[this](const auto& alternative) -> int { return Compare(alternative); });
}
} | #include <sstream>
#include <string>
#include "absl/hash/hash.h"
#include "absl/strings/cord.h"
#include "absl/strings/cord_test_helpers.h"
#include "absl/strings/string_view.h"
#include "absl/types/optional.h"
#include "common/any.h"
#include "common/casting.h"
#include "common/json.h"
#include "common/native_type.h"
#include "common/type.h"
#include "common/value.h"
#include "common/value_testing.h"
#include "internal/testing.h"
namespace cel {
namespace {
using testing::An;
using testing::Ne;
using cel::internal::IsOkAndHolds;
using StringValueTest = common_internal::ThreadCompatibleValueTest<>;
TEST_P(StringValueTest, Kind) {
EXPECT_EQ(StringValue("foo").kind(), StringValue::kKind);
EXPECT_EQ(Value(StringValue(absl::Cord("foo"))).kind(), StringValue::kKind);
}
TEST_P(StringValueTest, DebugString) {
{
std::ostringstream out;
out << StringValue("foo");
EXPECT_EQ(out.str(), "\"foo\"");
}
{
std::ostringstream out;
out << StringValue(absl::MakeFragmentedCord({"f", "o", "o"}));
EXPECT_EQ(out.str(), "\"foo\"");
}
{
std::ostringstream out;
out << Value(StringValue(absl::Cord("foo")));
EXPECT_EQ(out.str(), "\"foo\"");
}
}
TEST_P(StringValueTest, GetSerializedSize) {
EXPECT_THAT(StringValue().GetSerializedSize(value_manager()),
IsOkAndHolds(0));
}
TEST_P(StringValueTest, ConvertToAny) {
EXPECT_THAT(StringValue().ConvertToAny(value_manager()),
IsOkAndHolds(MakeAny(MakeTypeUrl("google.protobuf.StringValue"),
absl::Cord())));
}
TEST_P(StringValueTest, ConvertToJson) {
EXPECT_THAT(StringValue("foo").ConvertToJson(value_manager()),
IsOkAndHolds(Json(JsonString("foo"))));
}
TEST_P(StringValueTest, NativeValue) {
std::string scratch;
EXPECT_EQ(StringValue("foo").NativeString(), "foo");
EXPECT_EQ(StringValue("foo").NativeString(scratch), "foo");
EXPECT_EQ(StringValue("foo").NativeCord(), "foo");
}
TEST_P(StringValueTest, NativeTypeId) {
EXPECT_EQ(NativeTypeId::Of(StringValue("foo")),
NativeTypeId::For<StringValue>());
EXPECT_EQ(NativeTypeId::Of(Value(StringValue(absl::Cord("foo")))),
NativeTypeId::For<StringValue>());
}
TEST_P(StringValueTest, InstanceOf) {
EXPECT_TRUE(InstanceOf<StringValue>(StringValue("foo")));
EXPECT_TRUE(InstanceOf<StringValue>(Value(StringValue(absl::Cord("foo")))));
}
TEST_P(StringValueTest, Cast) {
EXPECT_THAT(Cast<StringValue>(StringValue("foo")), An<StringValue>());
EXPECT_THAT(Cast<StringValue>(Value(StringValue(absl::Cord("foo")))),
An<StringValue>());
}
TEST_P(StringValueTest, As) {
EXPECT_THAT(As<StringValue>(StringValue("foo")), Ne(absl::nullopt));
EXPECT_THAT(As<StringValue>(Value(StringValue(absl::Cord("foo")))),
Ne(absl::nullopt));
}
TEST_P(StringValueTest, HashValue) {
EXPECT_EQ(absl::HashOf(StringValue("foo")),
absl::HashOf(absl::string_view("foo")));
EXPECT_EQ(absl::HashOf(StringValue(absl::string_view("foo"))),
absl::HashOf(absl::string_view("foo")));
EXPECT_EQ(absl::HashOf(StringValue(absl::Cord("foo"))),
absl::HashOf(absl::string_view("foo")));
}
TEST_P(StringValueTest, Equality) {
EXPECT_NE(StringValue("foo"), "bar");
EXPECT_NE("bar", StringValue("foo"));
EXPECT_NE(StringValue("foo"), StringValue("bar"));
EXPECT_NE(StringValue("foo"), absl::Cord("bar"));
EXPECT_NE(absl::Cord("bar"), StringValue("foo"));
}
TEST_P(StringValueTest, LessThan) {
EXPECT_LT(StringValue("bar"), "foo");
EXPECT_LT("bar", StringValue("foo"));
EXPECT_LT(StringValue("bar"), StringValue("foo"));
EXPECT_LT(StringValue("bar"), absl::Cord("foo"));
EXPECT_LT(absl::Cord("bar"), StringValue("foo"));
}
INSTANTIATE_TEST_SUITE_P(
StringValueTest, StringValueTest,
::testing::Combine(::testing::Values(MemoryManagement::kPooling,
MemoryManagement::kReferenceCounting)),
StringValueTest::ToString);
using StringValueViewTest = common_internal::ThreadCompatibleValueTest<>;
TEST_P(StringValueViewTest, Kind) {
EXPECT_EQ(StringValueView("foo").kind(), StringValueView::kKind);
EXPECT_EQ(ValueView(StringValueView("foo")).kind(), StringValueView::kKind);
}
TEST_P(StringValueViewTest, DebugString) {
{
std::ostringstream out;
out << StringValueView("foo");
EXPECT_EQ(out.str(), "\"foo\"");
}
{
std::ostringstream out;
out << ValueView(StringValueView("foo"));
EXPECT_EQ(out.str(), "\"foo\"");
}
}
TEST_P(StringValueViewTest, GetSerializedSize) {
EXPECT_THAT(StringValueView().GetSerializedSize(value_manager()),
IsOkAndHolds(0));
}
TEST_P(StringValueViewTest, ConvertToAny) {
EXPECT_THAT(StringValueView().ConvertToAny(value_manager()),
IsOkAndHolds(MakeAny(MakeTypeUrl("google.protobuf.StringValue"),
absl::Cord())));
}
TEST_P(StringValueViewTest, ConvertToJson) {
EXPECT_THAT(StringValueView("foo").ConvertToJson(value_manager()),
IsOkAndHolds(Json(JsonString("foo"))));
}
TEST_P(StringValueViewTest, NativeValue) {
std::string scratch;
EXPECT_EQ(StringValueView(StringValue("foo")).NativeString(), "foo");
EXPECT_EQ(StringValueView(StringValue("foo")).NativeString(scratch), "foo");
EXPECT_EQ(StringValueView(StringValue("foo")).NativeCord(), "foo");
}
TEST_P(StringValueViewTest, NativeTypeId) {
EXPECT_EQ(NativeTypeId::Of(StringValueView("foo")),
NativeTypeId::For<StringValueView>());
EXPECT_EQ(NativeTypeId::Of(ValueView(StringValueView("foo"))),
NativeTypeId::For<StringValueView>());
}
TEST_P(StringValueViewTest, InstanceOf) {
EXPECT_TRUE(InstanceOf<StringValueView>(StringValueView("foo")));
EXPECT_TRUE(InstanceOf<StringValueView>(ValueView(StringValueView("foo"))));
}
TEST_P(StringValueViewTest, Cast) {
EXPECT_THAT(Cast<StringValueView>(StringValueView("foo")),
An<StringValueView>());
EXPECT_THAT(Cast<StringValueView>(ValueView(StringValueView("foo"))),
An<StringValueView>());
}
TEST_P(StringValueViewTest, As) {
EXPECT_THAT(As<StringValueView>(StringValueView("foo")), Ne(absl::nullopt));
EXPECT_THAT(As<StringValueView>(ValueView(StringValueView("foo"))),
Ne(absl::nullopt));
}
TEST_P(StringValueViewTest, HashValue) {
EXPECT_EQ(absl::HashOf(StringValueView("foo")),
absl::HashOf(absl::string_view("foo")));
EXPECT_EQ(absl::HashOf(StringValueView(absl::string_view("foo"))),
absl::HashOf(absl::string_view("foo")));
EXPECT_EQ(absl::HashOf(StringValueView(absl::Cord("foo"))),
absl::HashOf(absl::string_view("foo")));
}
TEST_P(StringValueViewTest, Equality) {
EXPECT_NE(StringValueView("foo"), "bar");
EXPECT_NE("bar", StringValueView("foo"));
EXPECT_NE(StringValueView("foo"), StringValueView("bar"));
EXPECT_NE(StringValueView("foo"), absl::Cord("bar"));
EXPECT_NE(absl::Cord("bar"), StringValueView("foo"));
EXPECT_NE(StringValueView("foo"), StringValue("bar"));
EXPECT_NE(StringValue("bar"), StringValueView("foo"));
}
TEST_P(StringValueViewTest, LessThan) {
EXPECT_LT(StringValueView("bar"), "foo");
EXPECT_LT("bar", StringValueView("foo"));
EXPECT_LT(StringValueView("bar"), StringValueView("foo"));
EXPECT_LT(StringValueView("bar"), absl::Cord("foo"));
EXPECT_LT(absl::Cord("bar"), StringValueView("foo"));
EXPECT_LT(StringValueView("bar"), StringValue("foo"));
EXPECT_LT(StringValue("bar"), StringValueView("foo"));
}
INSTANTIATE_TEST_SUITE_P(
StringValueViewTest, StringValueViewTest,
::testing::Combine(::testing::Values(MemoryManagement::kPooling,
MemoryManagement::kReferenceCounting)),
StringValueViewTest::ToString);
}
} |
338 | #ifndef THIRD_PARTY_CEL_CPP_RUNTIME_STANDARD_REGEX_FUNCTIONS_H_
#define THIRD_PARTY_CEL_CPP_RUNTIME_STANDARD_REGEX_FUNCTIONS_H_
#include "absl/status/status.h"
#include "runtime/function_registry.h"
#include "runtime/runtime_options.h"
namespace cel {
absl::Status RegisterRegexFunctions(FunctionRegistry& registry,
const RuntimeOptions& options);
}
#endif
#include "runtime/standard/regex_functions.h"
#include "absl/status/status.h"
#include "absl/strings/string_view.h"
#include "base/builtins.h"
#include "base/function_adapter.h"
#include "common/value.h"
#include "common/value_manager.h"
#include "internal/status_macros.h"
#include "re2/re2.h"
namespace cel {
namespace {}
absl::Status RegisterRegexFunctions(FunctionRegistry& registry,
const RuntimeOptions& options) {
if (options.enable_regex) {
auto regex_matches = [max_size = options.regex_max_program_size](
ValueManager& value_factory,
const StringValue& target,
const StringValue& regex) -> Value {
RE2 re2(regex.ToString());
if (max_size > 0 && re2.ProgramSize() > max_size) {
return value_factory.CreateErrorValue(
absl::InvalidArgumentError("exceeded RE2 max program size"));
}
if (!re2.ok()) {
return value_factory.CreateErrorValue(
absl::InvalidArgumentError("invalid regex for match"));
}
return value_factory.CreateBoolValue(
RE2::PartialMatch(target.ToString(), re2));
};
for (bool receiver_style : {true, false}) {
using MatchFnAdapter =
BinaryFunctionAdapter<Value, const StringValue&, const StringValue&>;
CEL_RETURN_IF_ERROR(
registry.Register(MatchFnAdapter::CreateDescriptor(
cel::builtin::kRegexMatch, receiver_style),
MatchFnAdapter::WrapFunction(regex_matches)));
}
}
return absl::OkStatus();
}
} | #include "runtime/standard/regex_functions.h"
#include <vector>
#include "base/builtins.h"
#include "base/function_descriptor.h"
#include "internal/testing.h"
namespace cel {
namespace {
using testing::IsEmpty;
using testing::UnorderedElementsAre;
enum class CallStyle { kFree, kReceiver };
MATCHER_P2(MatchesDescriptor, name, call_style, "") {
bool receiver_style;
switch (call_style) {
case CallStyle::kReceiver:
receiver_style = true;
break;
case CallStyle::kFree:
receiver_style = false;
break;
}
const FunctionDescriptor& descriptor = *arg;
std::vector<Kind> types{Kind::kString, Kind::kString};
return descriptor.name() == name &&
descriptor.receiver_style() == receiver_style &&
descriptor.types() == types;
}
TEST(RegisterRegexFunctions, Registered) {
FunctionRegistry registry;
RuntimeOptions options;
ASSERT_OK(RegisterRegexFunctions(registry, options));
auto overloads = registry.ListFunctions();
EXPECT_THAT(overloads[builtin::kRegexMatch],
UnorderedElementsAre(
MatchesDescriptor(builtin::kRegexMatch, CallStyle::kReceiver),
MatchesDescriptor(builtin::kRegexMatch, CallStyle::kFree)));
}
TEST(RegisterRegexFunctions, NotRegisteredIfDisabled) {
FunctionRegistry registry;
RuntimeOptions options;
options.enable_regex = false;
ASSERT_OK(RegisterRegexFunctions(registry, options));
auto overloads = registry.ListFunctions();
EXPECT_THAT(overloads[builtin::kRegexMatch], IsEmpty());
}
}
} |
339 | #ifndef QUICHE_QUIC_CORE_QUIC_TIME_H_
#define QUICHE_QUIC_CORE_QUIC_TIME_H_
#include <cmath>
#include <cstdint>
#include <limits>
#include <ostream>
#include <string>
#include "absl/time/time.h"
#include "quiche/quic/platform/api/quic_export.h"
namespace quic {
class QuicClock;
class QuicTime;
class QUICHE_EXPORT QuicTimeDelta {
public:
explicit QuicTimeDelta(absl::Duration duration)
: time_offset_((duration == absl::InfiniteDuration())
? kInfiniteTimeUs
: absl::ToInt64Microseconds(duration)) {}
static constexpr QuicTimeDelta Zero() { return QuicTimeDelta(0); }
static constexpr QuicTimeDelta Infinite() {
return QuicTimeDelta(kInfiniteTimeUs);
}
static constexpr QuicTimeDelta FromSeconds(int64_t secs) {
return QuicTimeDelta(secs * 1000 * 1000);
}
static constexpr QuicTimeDelta FromMilliseconds(int64_t ms) {
return QuicTimeDelta(ms * 1000);
}
static constexpr QuicTimeDelta FromMicroseconds(int64_t us) {
return QuicTimeDelta(us);
}
constexpr int64_t ToSeconds() const { return time_offset_ / 1000 / 1000; }
constexpr int64_t ToMilliseconds() const { return time_offset_ / 1000; }
constexpr int64_t ToMicroseconds() const { return time_offset_; }
constexpr absl::Duration ToAbsl() {
if (ABSL_PREDICT_FALSE(IsInfinite())) {
return absl::InfiniteDuration();
}
return absl::Microseconds(time_offset_);
}
constexpr bool IsZero() const { return time_offset_ == 0; }
constexpr bool IsInfinite() const { return time_offset_ == kInfiniteTimeUs; }
std::string ToDebuggingValue() const;
private:
friend inline bool operator==(QuicTimeDelta lhs, QuicTimeDelta rhs);
friend inline bool operator<(QuicTimeDelta lhs, QuicTimeDelta rhs);
friend inline QuicTimeDelta operator<<(QuicTimeDelta lhs, size_t rhs);
friend inline QuicTimeDelta operator>>(QuicTimeDelta lhs, size_t rhs);
friend inline constexpr QuicTimeDelta operator+(QuicTimeDelta lhs,
QuicTimeDelta rhs);
friend inline constexpr QuicTimeDelta operator-(QuicTimeDelta lhs,
QuicTimeDelta rhs);
friend inline constexpr QuicTimeDelta operator*(QuicTimeDelta lhs, int rhs);
friend inline QuicTimeDelta operator*(QuicTimeDelta lhs, double rhs);
friend inline QuicTime operator+(QuicTime lhs, QuicTimeDelta rhs);
friend inline QuicTime operator-(QuicTime lhs, QuicTimeDelta rhs);
friend inline QuicTimeDelta operator-(QuicTime lhs, QuicTime rhs);
static constexpr int64_t kInfiniteTimeUs =
std::numeric_limits<int64_t>::max();
explicit constexpr QuicTimeDelta(int64_t time_offset)
: time_offset_(time_offset) {}
int64_t time_offset_;
friend class QuicTime;
};
class QUICHE_EXPORT QuicTime {
public:
using Delta = QuicTimeDelta;
static constexpr QuicTime Zero() { return QuicTime(0); }
static constexpr QuicTime Infinite() {
return QuicTime(Delta::kInfiniteTimeUs);
}
QuicTime(const QuicTime& other) = default;
QuicTime& operator=(const QuicTime& other) {
time_ = other.time_;
return *this;
}
int64_t ToDebuggingValue() const { return time_; }
bool IsInitialized() const { return 0 != time_; }
private:
friend class QuicClock;
friend inline bool operator==(QuicTime lhs, QuicTime rhs);
friend inline bool operator<(QuicTime lhs, QuicTime rhs);
friend inline QuicTime operator+(QuicTime lhs, QuicTimeDelta rhs);
friend inline QuicTime operator-(QuicTime lhs, QuicTimeDelta rhs);
friend inline QuicTimeDelta operator-(QuicTime lhs, QuicTime rhs);
explicit constexpr QuicTime(int64_t time) : time_(time) {}
int64_t time_;
};
class QUICHE_EXPORT QuicWallTime {
public:
static constexpr QuicWallTime FromUNIXSeconds(uint64_t seconds) {
return QuicWallTime(seconds * 1000000);
}
static constexpr QuicWallTime FromUNIXMicroseconds(uint64_t microseconds) {
return QuicWallTime(microseconds);
}
static constexpr QuicWallTime Zero() { return QuicWallTime(0); }
uint64_t ToUNIXSeconds() const;
uint64_t ToUNIXMicroseconds() const;
bool IsAfter(QuicWallTime other) const;
bool IsBefore(QuicWallTime other) const;
bool IsZero() const;
QuicTimeDelta AbsoluteDifference(QuicWallTime other) const;
[[nodiscard]] QuicWallTime Add(QuicTimeDelta delta) const;
[[nodiscard]] QuicWallTime Subtract(QuicTimeDelta delta) const;
bool operator==(const QuicWallTime& other) const {
return microseconds_ == other.microseconds_;
}
QuicTimeDelta operator-(const QuicWallTime& rhs) const {
return QuicTimeDelta::FromMicroseconds(microseconds_ - rhs.microseconds_);
}
private:
explicit constexpr QuicWallTime(uint64_t microseconds)
: microseconds_(microseconds) {}
uint64_t microseconds_;
};
inline bool operator==(QuicTimeDelta lhs, QuicTimeDelta rhs) {
return lhs.time_offset_ == rhs.time_offset_;
}
inline bool operator!=(QuicTimeDelta lhs, QuicTimeDelta rhs) {
return !(lhs == rhs);
}
inline bool operator<(QuicTimeDelta lhs, QuicTimeDelta rhs) {
return lhs.time_offset_ < rhs.time_offset_;
}
inline bool operator>(QuicTimeDelta lhs, QuicTimeDelta rhs) {
return rhs < lhs;
}
inline bool operator<=(QuicTimeDelta lhs, QuicTimeDelta rhs) {
return !(rhs < lhs);
}
inline bool operator>=(QuicTimeDelta lhs, QuicTimeDelta rhs) {
return !(lhs < rhs);
}
inline QuicTimeDelta operator<<(QuicTimeDelta lhs, size_t rhs) {
return QuicTimeDelta(lhs.time_offset_ << rhs);
}
inline QuicTimeDelta operator>>(QuicTimeDelta lhs, size_t rhs) {
return QuicTimeDelta(lhs.time_offset_ >> rhs);
}
inline bool operator==(QuicTime lhs, QuicTime rhs) {
return lhs.time_ == rhs.time_;
}
inline bool operator!=(QuicTime lhs, QuicTime rhs) { return !(lhs == rhs); }
inline bool operator<(QuicTime lhs, QuicTime rhs) {
return lhs.time_ < rhs.time_;
}
inline bool operator>(QuicTime lhs, QuicTime rhs) { return rhs < lhs; }
inline bool operator<=(QuicTime lhs, QuicTime rhs) { return !(rhs < lhs); }
inline bool operator>=(QuicTime lhs, QuicTime rhs) { return !(lhs < rhs); }
inline std::ostream& operator<<(std::ostream& output, const QuicTime t) {
output << t.ToDebuggingValue();
return output;
}
inline constexpr QuicTimeDelta operator+(QuicTimeDelta lhs, QuicTimeDelta rhs) {
return QuicTimeDelta(lhs.time_offset_ + rhs.time_offset_);
}
inline constexpr QuicTimeDelta operator-(QuicTimeDelta lhs, QuicTimeDelta rhs) {
return QuicTimeDelta(lhs.time_offset_ - rhs.time_offset_);
}
inline constexpr QuicTimeDelta operator*(QuicTimeDelta lhs, int rhs) {
return QuicTimeDelta(lhs.time_offset_ * rhs);
}
inline QuicTimeDelta operator*(QuicTimeDelta lhs, double rhs) {
return QuicTimeDelta(static_cast<int64_t>(
std::llround(static_cast<double>(lhs.time_offset_) * rhs)));
}
inline QuicTimeDelta operator*(int lhs, QuicTimeDelta rhs) { return rhs * lhs; }
inline QuicTimeDelta operator*(double lhs, QuicTimeDelta rhs) {
return rhs * lhs;
}
inline QuicTime operator+(QuicTime lhs, QuicTimeDelta rhs) {
return QuicTime(lhs.time_ + rhs.time_offset_);
}
inline QuicTime operator-(QuicTime lhs, QuicTimeDelta rhs) {
return QuicTime(lhs.time_ - rhs.time_offset_);
}
inline QuicTimeDelta operator-(QuicTime lhs, QuicTime rhs) {
return QuicTimeDelta(lhs.time_ - rhs.time_);
}
inline std::ostream& operator<<(std::ostream& output,
const QuicTimeDelta delta) {
output << delta.ToDebuggingValue();
return output;
}
}
#endif
#include "quiche/quic/core/quic_time.h"
#include <cinttypes>
#include <cstdlib>
#include <limits>
#include <string>
#include "absl/strings/str_cat.h"
namespace quic {
std::string QuicTime::Delta::ToDebuggingValue() const {
constexpr int64_t kMillisecondInMicroseconds = 1000;
constexpr int64_t kSecondInMicroseconds = 1000 * kMillisecondInMicroseconds;
int64_t absolute_value = std::abs(time_offset_);
if (absolute_value >= kSecondInMicroseconds &&
absolute_value % kSecondInMicroseconds == 0) {
return absl::StrCat(time_offset_ / kSecondInMicroseconds, "s");
}
if (absolute_value >= kMillisecondInMicroseconds &&
absolute_value % kMillisecondInMicroseconds == 0) {
return absl::StrCat(time_offset_ / kMillisecondInMicroseconds, "ms");
}
return absl::StrCat(time_offset_, "us");
}
uint64_t QuicWallTime::ToUNIXSeconds() const { return microseconds_ / 1000000; }
uint64_t QuicWallTime::ToUNIXMicroseconds() const { return microseconds_; }
bool QuicWallTime::IsAfter(QuicWallTime other) const {
return microseconds_ > other.microseconds_;
}
bool QuicWallTime::IsBefore(QuicWallTime other) const {
return microseconds_ < other.microseconds_;
}
bool QuicWallTime::IsZero() const { return microseconds_ == 0; }
QuicTime::Delta QuicWallTime::AbsoluteDifference(QuicWallTime other) const {
uint64_t d;
if (microseconds_ > other.microseconds_) {
d = microseconds_ - other.microseconds_;
} else {
d = other.microseconds_ - microseconds_;
}
if (d > static_cast<uint64_t>(std::numeric_limits<int64_t>::max())) {
d = std::numeric_limits<int64_t>::max();
}
return QuicTime::Delta::FromMicroseconds(d);
}
QuicWallTime QuicWallTime::Add(QuicTime::Delta delta) const {
uint64_t microseconds = microseconds_ + delta.ToMicroseconds();
if (microseconds < microseconds_) {
microseconds = std::numeric_limits<uint64_t>::max();
}
return QuicWallTime(microseconds);
}
QuicWallTime QuicWallTime::Subtract(QuicTime::Delta delta) const {
uint64_t microseconds = microseconds_ - delta.ToMicroseconds();
if (microseconds > microseconds_) {
microseconds = 0;
}
return QuicWallTime(microseconds);
}
} | #include "quiche/quic/core/quic_time.h"
#include "quiche/quic/platform/api/quic_test.h"
#include "quiche/quic/test_tools/mock_clock.h"
namespace quic {
namespace test {
class QuicTimeDeltaTest : public QuicTest {};
TEST_F(QuicTimeDeltaTest, Zero) {
EXPECT_TRUE(QuicTime::Delta::Zero().IsZero());
EXPECT_FALSE(QuicTime::Delta::Zero().IsInfinite());
EXPECT_FALSE(QuicTime::Delta::FromMilliseconds(1).IsZero());
}
TEST_F(QuicTimeDeltaTest, Infinite) {
EXPECT_TRUE(QuicTime::Delta::Infinite().IsInfinite());
EXPECT_FALSE(QuicTime::Delta::Zero().IsInfinite());
EXPECT_FALSE(QuicTime::Delta::FromMilliseconds(1).IsInfinite());
}
TEST_F(QuicTimeDeltaTest, FromTo) {
EXPECT_EQ(QuicTime::Delta::FromMilliseconds(1),
QuicTime::Delta::FromMicroseconds(1000));
EXPECT_EQ(QuicTime::Delta::FromSeconds(1),
QuicTime::Delta::FromMilliseconds(1000));
EXPECT_EQ(QuicTime::Delta::FromSeconds(1),
QuicTime::Delta::FromMicroseconds(1000000));
EXPECT_EQ(1, QuicTime::Delta::FromMicroseconds(1000).ToMilliseconds());
EXPECT_EQ(2, QuicTime::Delta::FromMilliseconds(2000).ToSeconds());
EXPECT_EQ(1000, QuicTime::Delta::FromMilliseconds(1).ToMicroseconds());
EXPECT_EQ(1, QuicTime::Delta::FromMicroseconds(1000).ToMilliseconds());
EXPECT_EQ(QuicTime::Delta::FromMilliseconds(2000).ToMicroseconds(),
QuicTime::Delta::FromSeconds(2).ToMicroseconds());
}
TEST_F(QuicTimeDeltaTest, Add) {
EXPECT_EQ(QuicTime::Delta::FromMicroseconds(2000),
QuicTime::Delta::Zero() + QuicTime::Delta::FromMilliseconds(2));
}
TEST_F(QuicTimeDeltaTest, Subtract) {
EXPECT_EQ(QuicTime::Delta::FromMicroseconds(1000),
QuicTime::Delta::FromMilliseconds(2) -
QuicTime::Delta::FromMilliseconds(1));
}
TEST_F(QuicTimeDeltaTest, Multiply) {
int i = 2;
EXPECT_EQ(QuicTime::Delta::FromMicroseconds(4000),
QuicTime::Delta::FromMilliseconds(2) * i);
EXPECT_EQ(QuicTime::Delta::FromMicroseconds(4000),
i * QuicTime::Delta::FromMilliseconds(2));
double d = 2;
EXPECT_EQ(QuicTime::Delta::FromMicroseconds(4000),
QuicTime::Delta::FromMilliseconds(2) * d);
EXPECT_EQ(QuicTime::Delta::FromMicroseconds(4000),
d * QuicTime::Delta::FromMilliseconds(2));
EXPECT_EQ(QuicTime::Delta::FromMicroseconds(5),
QuicTime::Delta::FromMicroseconds(9) * 0.5);
EXPECT_EQ(QuicTime::Delta::FromMicroseconds(2),
QuicTime::Delta::FromMicroseconds(12) * 0.2);
}
TEST_F(QuicTimeDeltaTest, Max) {
EXPECT_EQ(QuicTime::Delta::FromMicroseconds(2000),
std::max(QuicTime::Delta::FromMicroseconds(1000),
QuicTime::Delta::FromMicroseconds(2000)));
}
TEST_F(QuicTimeDeltaTest, NotEqual) {
EXPECT_TRUE(QuicTime::Delta::FromSeconds(0) !=
QuicTime::Delta::FromSeconds(1));
EXPECT_FALSE(QuicTime::Delta::FromSeconds(0) !=
QuicTime::Delta::FromSeconds(0));
}
TEST_F(QuicTimeDeltaTest, DebuggingValue) {
const QuicTime::Delta one_us = QuicTime::Delta::FromMicroseconds(1);
const QuicTime::Delta one_ms = QuicTime::Delta::FromMilliseconds(1);
const QuicTime::Delta one_s = QuicTime::Delta::FromSeconds(1);
EXPECT_EQ("1s", one_s.ToDebuggingValue());
EXPECT_EQ("3s", (3 * one_s).ToDebuggingValue());
EXPECT_EQ("1ms", one_ms.ToDebuggingValue());
EXPECT_EQ("3ms", (3 * one_ms).ToDebuggingValue());
EXPECT_EQ("1us", one_us.ToDebuggingValue());
EXPECT_EQ("3us", (3 * one_us).ToDebuggingValue());
EXPECT_EQ("3001us", (3 * one_ms + one_us).ToDebuggingValue());
EXPECT_EQ("3001ms", (3 * one_s + one_ms).ToDebuggingValue());
EXPECT_EQ("3000001us", (3 * one_s + one_us).ToDebuggingValue());
}
class QuicTimeTest : public QuicTest {
protected:
MockClock clock_;
};
TEST_F(QuicTimeTest, Initialized) {
EXPECT_FALSE(QuicTime::Zero().IsInitialized());
EXPECT_TRUE((QuicTime::Zero() + QuicTime::Delta::FromMicroseconds(1))
.IsInitialized());
}
TEST_F(QuicTimeTest, CopyConstruct) {
QuicTime time_1 = QuicTime::Zero() + QuicTime::Delta::FromMilliseconds(1234);
EXPECT_NE(time_1, QuicTime(QuicTime::Zero()));
EXPECT_EQ(time_1, QuicTime(time_1));
}
TEST_F(QuicTimeTest, CopyAssignment) {
QuicTime time_1 = QuicTime::Zero() + QuicTime::Delta::FromMilliseconds(1234);
QuicTime time_2 = QuicTime::Zero();
EXPECT_NE(time_1, time_2);
time_2 = time_1;
EXPECT_EQ(time_1, time_2);
}
TEST_F(QuicTimeTest, Add) {
QuicTime time_1 = QuicTime::Zero() + QuicTime::Delta::FromMilliseconds(1);
QuicTime time_2 = QuicTime::Zero() + QuicTime::Delta::FromMilliseconds(2);
QuicTime::Delta diff = time_2 - time_1;
EXPECT_EQ(QuicTime::Delta::FromMilliseconds(1), diff);
EXPECT_EQ(1000, diff.ToMicroseconds());
EXPECT_EQ(1, diff.ToMilliseconds());
}
TEST_F(QuicTimeTest, Subtract) {
QuicTime time_1 = QuicTime::Zero() + QuicTime::Delta::FromMilliseconds(1);
QuicTime time_2 = QuicTime::Zero() + QuicTime::Delta::FromMilliseconds(2);
EXPECT_EQ(QuicTime::Delta::FromMilliseconds(1), time_2 - time_1);
}
TEST_F(QuicTimeTest, SubtractDelta) {
QuicTime time = QuicTime::Zero() + QuicTime::Delta::FromMilliseconds(2);
EXPECT_EQ(QuicTime::Zero() + QuicTime::Delta::FromMilliseconds(1),
time - QuicTime::Delta::FromMilliseconds(1));
}
TEST_F(QuicTimeTest, Max) {
QuicTime time_1 = QuicTime::Zero() + QuicTime::Delta::FromMilliseconds(1);
QuicTime time_2 = QuicTime::Zero() + QuicTime::Delta::FromMilliseconds(2);
EXPECT_EQ(time_2, std::max(time_1, time_2));
}
TEST_F(QuicTimeTest, MockClock) {
clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(1));
QuicTime now = clock_.ApproximateNow();
QuicTime time = QuicTime::Zero() + QuicTime::Delta::FromMicroseconds(1000);
EXPECT_EQ(now, time);
clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(1));
now = clock_.ApproximateNow();
EXPECT_NE(now, time);
time = time + QuicTime::Delta::FromMilliseconds(1);
EXPECT_EQ(now, time);
}
TEST_F(QuicTimeTest, LE) {
const QuicTime zero = QuicTime::Zero();
const QuicTime one = zero + QuicTime::Delta::FromSeconds(1);
EXPECT_TRUE(zero <= zero);
EXPECT_TRUE(zero <= one);
EXPECT_TRUE(one <= one);
EXPECT_FALSE(one <= zero);
}
}
} |
340 | #ifndef QUICHE_BLIND_SIGN_AUTH_BLIND_SIGN_AUTH_H_
#define QUICHE_BLIND_SIGN_AUTH_BLIND_SIGN_AUTH_H_
#include <memory>
#include <optional>
#include <string>
#include "absl/status/statusor.h"
#include "absl/time/time.h"
#include "anonymous_tokens/cpp/privacy_pass/rsa_bssa_public_metadata_client.h"
#include "anonymous_tokens/cpp/privacy_pass/token_encodings.h"
#include "quiche/blind_sign_auth/blind_sign_auth_interface.h"
#include "quiche/blind_sign_auth/blind_sign_auth_protos.h"
#include "quiche/blind_sign_auth/blind_sign_message_interface.h"
#include "quiche/blind_sign_auth/blind_sign_message_response.h"
#include "quiche/common/platform/api/quiche_export.h"
namespace quiche {
class QUICHE_EXPORT BlindSignAuth : public BlindSignAuthInterface {
public:
explicit BlindSignAuth(BlindSignMessageInterface* fetcher,
privacy::ppn::BlindSignAuthOptions auth_options)
: fetcher_(fetcher), auth_options_(std::move(auth_options)) {}
void GetTokens(std::optional<std::string> oauth_token, int num_tokens,
ProxyLayer proxy_layer, BlindSignAuthServiceType service_type,
SignedTokenCallback callback) override;
private:
void GetInitialDataCallback(
std::optional<std::string> oauth_token, int num_tokens,
ProxyLayer proxy_layer, BlindSignAuthServiceType service_type,
SignedTokenCallback callback,
absl::StatusOr<BlindSignMessageResponse> response);
void GeneratePrivacyPassTokens(
privacy::ppn::GetInitialDataResponse initial_data_response,
std::optional<std::string> oauth_token, int num_tokens,
ProxyLayer proxy_layer, BlindSignAuthServiceType service_type,
SignedTokenCallback callback);
void PrivacyPassAuthAndSignCallback(
std::string encoded_extensions, absl::Time public_key_expiry_time,
anonymous_tokens::GeoHint geo_hint,
anonymous_tokens::AnonymousTokensUseCase use_case,
std::vector<std::unique_ptr<anonymous_tokens::
PrivacyPassRsaBssaPublicMetadataClient>>
privacy_pass_clients,
SignedTokenCallback callback,
absl::StatusOr<BlindSignMessageResponse> response);
privacy::ppn::ProxyLayer QuicheProxyLayerToPpnProxyLayer(
quiche::ProxyLayer proxy_layer);
BlindSignMessageInterface* fetcher_ = nullptr;
privacy::ppn::BlindSignAuthOptions auth_options_;
};
std::string BlindSignAuthServiceTypeToString(
quiche::BlindSignAuthServiceType service_type);
}
#endif
#include "quiche/blind_sign_auth/blind_sign_auth.h"
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <memory>
#include <optional>
#include <string>
#include <utility>
#include <vector>
#include "absl/functional/bind_front.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/escaping.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/string_view.h"
#include "absl/time/clock.h"
#include "absl/time/time.h"
#include "absl/types/span.h"
#include "anonymous_tokens/cpp/crypto/crypto_utils.h"
#include "anonymous_tokens/cpp/privacy_pass/rsa_bssa_public_metadata_client.h"
#include "anonymous_tokens/cpp/privacy_pass/token_encodings.h"
#include "anonymous_tokens/cpp/shared/proto_utils.h"
#include "quiche/blind_sign_auth/blind_sign_auth_interface.h"
#include "quiche/blind_sign_auth/blind_sign_auth_protos.h"
#include "quiche/blind_sign_auth/blind_sign_message_interface.h"
#include "quiche/blind_sign_auth/blind_sign_message_response.h"
#include "quiche/common/platform/api/quiche_logging.h"
#include "quiche/common/quiche_random.h"
namespace quiche {
namespace {
template <typename T>
std::string OmitDefault(T value) {
return value == 0 ? "" : absl::StrCat(value);
}
constexpr absl::string_view kIssuerHostname =
"https:
}
void BlindSignAuth::GetTokens(std::optional<std::string> oauth_token,
int num_tokens, ProxyLayer proxy_layer,
BlindSignAuthServiceType service_type,
SignedTokenCallback callback) {
privacy::ppn::GetInitialDataRequest request;
request.set_use_attestation(false);
request.set_service_type(BlindSignAuthServiceTypeToString(service_type));
request.set_location_granularity(
privacy::ppn::GetInitialDataRequest_LocationGranularity_CITY_GEOS);
request.set_validation_version(2);
request.set_proxy_layer(QuicheProxyLayerToPpnProxyLayer(proxy_layer));
std::string body = request.SerializeAsString();
BlindSignMessageCallback initial_data_callback = absl::bind_front(
&BlindSignAuth::GetInitialDataCallback, this, oauth_token, num_tokens,
proxy_layer, service_type, std::move(callback));
fetcher_->DoRequest(BlindSignMessageRequestType::kGetInitialData, oauth_token,
body, std::move(initial_data_callback));
}
void BlindSignAuth::GetInitialDataCallback(
std::optional<std::string> oauth_token, int num_tokens,
ProxyLayer proxy_layer, BlindSignAuthServiceType service_type,
SignedTokenCallback callback,
absl::StatusOr<BlindSignMessageResponse> response) {
if (!response.ok()) {
QUICHE_LOG(WARNING) << "GetInitialDataRequest failed: "
<< response.status();
std::move(callback)(response.status());
return;
}
absl::StatusCode code = response->status_code();
if (code != absl::StatusCode::kOk) {
std::string message =
absl::StrCat("GetInitialDataRequest failed with code: ", code);
QUICHE_LOG(WARNING) << message;
std::move(callback)(absl::Status(code, message));
return;
}
privacy::ppn::GetInitialDataResponse initial_data_response;
if (!initial_data_response.ParseFromString(response->body())) {
QUICHE_LOG(WARNING) << "Failed to parse GetInitialDataResponse";
std::move(callback)(
absl::InternalError("Failed to parse GetInitialDataResponse"));
return;
}
bool use_privacy_pass_client =
initial_data_response.has_privacy_pass_data() &&
auth_options_.enable_privacy_pass();
if (use_privacy_pass_client) {
QUICHE_DVLOG(1) << "Using Privacy Pass client";
GeneratePrivacyPassTokens(initial_data_response, std::move(oauth_token),
num_tokens, proxy_layer, service_type,
std::move(callback));
} else {
QUICHE_LOG(ERROR) << "Non-Privacy Pass tokens are no longer supported";
std::move(callback)(absl::UnimplementedError(
"Non-Privacy Pass tokens are no longer supported"));
}
}
void BlindSignAuth::GeneratePrivacyPassTokens(
privacy::ppn::GetInitialDataResponse initial_data_response,
std::optional<std::string> oauth_token, int num_tokens,
ProxyLayer proxy_layer, BlindSignAuthServiceType service_type,
SignedTokenCallback callback) {
anonymous_tokens::RSAPublicKey public_key_proto;
if (!public_key_proto.ParseFromString(
initial_data_response.at_public_metadata_public_key()
.serialized_public_key())) {
std::move(callback)(
absl::InvalidArgumentError("Failed to parse Privacy Pass public key"));
return;
}
absl::StatusOr<bssl::UniquePtr<RSA>> bssl_rsa_key =
anonymous_tokens::CreatePublicKeyRSA(
public_key_proto.n(), public_key_proto.e());
if (!bssl_rsa_key.ok()) {
std::move(callback)(bssl_rsa_key.status());
return;
}
absl::StatusOr<anonymous_tokens::Extensions> extensions =
anonymous_tokens::DecodeExtensions(
initial_data_response.privacy_pass_data()
.public_metadata_extensions());
if (!extensions.ok()) {
QUICHE_LOG(WARNING) << "Failed to decode extensions: "
<< extensions.status();
std::move(callback)(extensions.status());
return;
}
std::vector<uint16_t> kExpectedExtensionTypes = {
0x0001, 0x0002,
0xF001, 0xF002, 0xF003};
absl::Status result =
anonymous_tokens::ValidateExtensionsOrderAndValues(
*extensions, absl::MakeSpan(kExpectedExtensionTypes), absl::Now());
if (!result.ok()) {
QUICHE_LOG(WARNING) << "Failed to validate extensions: " << result;
std::move(callback)(result);
return;
}
absl::StatusOr<anonymous_tokens::ExpirationTimestamp>
expiration_timestamp = anonymous_tokens::
ExpirationTimestamp::FromExtension(extensions->extensions.at(0));
if (!expiration_timestamp.ok()) {
QUICHE_LOG(WARNING) << "Failed to parse expiration timestamp: "
<< expiration_timestamp.status();
std::move(callback)(expiration_timestamp.status());
return;
}
absl::Time public_metadata_expiry_time =
absl::FromUnixSeconds(expiration_timestamp->timestamp);
absl::StatusOr<anonymous_tokens::GeoHint> geo_hint =
anonymous_tokens::GeoHint::FromExtension(
extensions->extensions.at(1));
QUICHE_CHECK(geo_hint.ok());
anonymous_tokens::TokenChallenge challenge;
challenge.issuer_name = kIssuerHostname;
absl::StatusOr<std::string> token_challenge =
anonymous_tokens::MarshalTokenChallenge(challenge);
if (!token_challenge.ok()) {
QUICHE_LOG(WARNING) << "Failed to marshal token challenge: "
<< token_challenge.status();
std::move(callback)(token_challenge.status());
return;
}
QuicheRandom* random = QuicheRandom::GetInstance();
std::vector<anonymous_tokens::ExtendedTokenRequest>
extended_token_requests;
std::vector<std::unique_ptr<anonymous_tokens::
PrivacyPassRsaBssaPublicMetadataClient>>
privacy_pass_clients;
std::vector<std::string> privacy_pass_blinded_tokens;
for (int i = 0; i < num_tokens; i++) {
auto client = anonymous_tokens::
PrivacyPassRsaBssaPublicMetadataClient::Create(*bssl_rsa_key.value());
if (!client.ok()) {
QUICHE_LOG(WARNING) << "Failed to create Privacy Pass client: "
<< client.status();
std::move(callback)(client.status());
return;
}
std::string nonce_rand(32, '\0');
random->RandBytes(nonce_rand.data(), nonce_rand.size());
absl::StatusOr<anonymous_tokens::ExtendedTokenRequest>
extended_token_request = client.value()->CreateTokenRequest(
*token_challenge, nonce_rand,
initial_data_response.privacy_pass_data().token_key_id(),
*extensions);
if (!extended_token_request.ok()) {
QUICHE_LOG(WARNING) << "Failed to create ExtendedTokenRequest: "
<< extended_token_request.status();
std::move(callback)(extended_token_request.status());
return;
}
privacy_pass_clients.push_back(*std::move(client));
extended_token_requests.push_back(*extended_token_request);
privacy_pass_blinded_tokens.push_back(absl::Base64Escape(
extended_token_request->request.blinded_token_request));
}
privacy::ppn::AuthAndSignRequest sign_request;
sign_request.set_service_type(BlindSignAuthServiceTypeToString(service_type));
sign_request.set_key_type(privacy::ppn::AT_PUBLIC_METADATA_KEY_TYPE);
sign_request.set_key_version(
initial_data_response.at_public_metadata_public_key().key_version());
sign_request.mutable_blinded_token()->Assign(
privacy_pass_blinded_tokens.begin(), privacy_pass_blinded_tokens.end());
sign_request.mutable_public_metadata_extensions()->assign(
initial_data_response.privacy_pass_data().public_metadata_extensions());
sign_request.set_do_not_use_rsa_public_exponent(true);
sign_request.set_proxy_layer(QuicheProxyLayerToPpnProxyLayer(proxy_layer));
absl::StatusOr<anonymous_tokens::AnonymousTokensUseCase>
use_case = anonymous_tokens::ParseUseCase(
initial_data_response.at_public_metadata_public_key().use_case());
if (!use_case.ok()) {
QUICHE_LOG(WARNING) << "Failed to parse use case: " << use_case.status();
std::move(callback)(use_case.status());
return;
}
BlindSignMessageCallback auth_and_sign_callback =
absl::bind_front(&BlindSignAuth::PrivacyPassAuthAndSignCallback, this,
std::move(initial_data_response.privacy_pass_data()
.public_metadata_extensions()),
public_metadata_expiry_time, *geo_hint, *use_case,
std::move(privacy_pass_clients), std::move(callback));
fetcher_->DoRequest(BlindSignMessageRequestType::kAuthAndSign, oauth_token,
sign_request.SerializeAsString(),
std::move(auth_and_sign_callback));
}
void BlindSignAuth::PrivacyPassAuthAndSignCallback(
std::string encoded_extensions, absl::Time public_key_expiry_time,
anonymous_tokens::GeoHint geo_hint,
anonymous_tokens::AnonymousTokensUseCase use_case,
std::vector<std::unique_ptr<anonymous_tokens::
PrivacyPassRsaBssaPublicMetadataClient>>
privacy_pass_clients,
SignedTokenCallback callback,
absl::StatusOr<BlindSignMessageResponse> response) {
if (!response.ok()) {
QUICHE_LOG(WARNING) << "AuthAndSign failed: " << response.status();
std::move(callback)(response.status());
return;
}
absl::StatusCode code = response->status_code();
if (code != absl::StatusCode::kOk) {
std::string message = absl::StrCat("AuthAndSign failed with code: ", code);
QUICHE_LOG(WARNING) << message;
std::move(callback)(absl::Status(code, message));
return;
}
privacy::ppn::AuthAndSignResponse sign_response;
if (!sign_response.ParseFromString(response->body())) {
QUICHE_LOG(WARNING) << "Failed to parse AuthAndSignResponse";
std::move(callback)(
absl::InternalError("Failed to parse AuthAndSignResponse"));
return;
}
if (static_cast<size_t>(sign_response.blinded_token_signature_size()) !=
privacy_pass_clients.size()) {
QUICHE_LOG(WARNING) << "Number of signatures does not equal number of "
"Privacy Pass tokens sent";
std::move(callback)(
absl::InternalError("Number of signatures does not equal number of "
"Privacy Pass tokens sent"));
return;
}
std::vector<BlindSignToken> tokens_vec;
for (int i = 0; i < sign_response.blinded_token_signature_size(); i++) {
std::string unescaped_blinded_sig;
if (!absl::Base64Unescape(sign_response.blinded_token_signature()[i],
&unescaped_blinded_sig)) {
QUICHE_LOG(WARNING) << "Failed to unescape blinded signature";
std::move(callback)(
absl::InternalError("Failed to unescape blinded signature"));
return;
}
absl::StatusOr<anonymous_tokens::Token> token =
privacy_pass_clients[i]->FinalizeToken(unescaped_blinded_sig);
if (!token.ok()) {
QUICHE_LOG(WARNING) << "Failed to finalize token: " << token.status();
std::move(callback)(token.status());
return;
}
absl::StatusOr<std::string> marshaled_token =
anonymous_tokens::MarshalToken(*token);
if (!marshaled_token.ok()) {
QUICHE_LOG(WARNING) << "Failed to marshal token: "
<< marshaled_token.status();
std::move(callback)(marshaled_token.status());
return;
}
privacy::ppn::PrivacyPassTokenData privacy_pass_token_data;
privacy_pass_token_data.mutable_token()->assign(
absl::WebSafeBase64Escape(*marshaled_token));
privacy_pass_token_data.mutable_encoded_extensions()->assign(
absl::WebSafeBase64Escape(encoded_extensions));
privacy_pass_token_data.set_use_case_override(use_case);
tokens_vec.push_back(
BlindSignToken{privacy_pass_token_data.SerializeAsString(),
public_key_expiry_time, geo_hint});
}
std::move(callback)(absl::Span<BlindSignToken>(tokens_vec));
}
privacy::ppn::ProxyLayer BlindSignAuth::QuicheProxyLayerToPpnProxyLayer(
quiche::ProxyLayer proxy_layer) {
switch (proxy_layer) {
case ProxyLayer::kProxyA: {
return privacy::ppn::ProxyLayer::PROXY_A;
}
case ProxyLayer::kProxyB: {
return privacy::ppn::ProxyLayer::PROXY_B;
}
}
}
std::string BlindSignAuthServiceTypeToString(
quiche::BlindSignAuthServiceType service_type) {
switch (service_type) {
case BlindSignAuthServiceType::kChromeIpBlinding: {
return "chromeipblinding";
}
case BlindSignAuthServiceType::kCronetIpBlinding: {
return "cronetipblinding";
}
case BlindSignAuthServiceType::kWebviewIpBlinding: {
return "chromeipblinding";
}
}
}
} | #include "quiche/blind_sign_auth/blind_sign_auth.h"
#include <cstdint>
#include <memory>
#include <string>
#include <utility>
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/escaping.h"
#include "absl/strings/string_view.h"
#include "absl/time/clock.h"
#include "absl/time/time.h"
#include "absl/types/span.h"
#include "anonymous_tokens/cpp/crypto/crypto_utils.h"
#include "anonymous_tokens/cpp/privacy_pass/token_encodings.h"
#include "anonymous_tokens/cpp/testing/utils.h"
#include "openssl/base.h"
#include "openssl/digest.h"
#include "quiche/blind_sign_auth/blind_sign_auth_interface.h"
#include "quiche/blind_sign_auth/blind_sign_auth_protos.h"
#include "quiche/blind_sign_auth/blind_sign_message_interface.h"
#include "quiche/blind_sign_auth/blind_sign_message_response.h"
#include "quiche/blind_sign_auth/test_tools/mock_blind_sign_message_interface.h"
#include "quiche/common/platform/api/quiche_mutex.h"
#include "quiche/common/platform/api/quiche_test.h"
#include "quiche/common/test_tools/quiche_test_utils.h"
namespace quiche {
namespace test {
namespace {
using ::testing::_;
using ::testing::Eq;
using ::testing::InSequence;
using ::testing::Invoke;
using ::testing::StartsWith;
using ::testing::Unused;
class BlindSignAuthTest : public QuicheTest {
protected:
void SetUp() override {
auto [test_rsa_public_key, test_rsa_private_key] =
anonymous_tokens::GetStrongTestRsaKeyPair2048();
ANON_TOKENS_ASSERT_OK_AND_ASSIGN(
rsa_public_key_,
anonymous_tokens::CreatePublicKeyRSA(
test_rsa_public_key.n, test_rsa_public_key.e));
ANON_TOKENS_ASSERT_OK_AND_ASSIGN(
rsa_private_key_,
anonymous_tokens::CreatePrivateKeyRSA(
test_rsa_private_key.n, test_rsa_private_key.e,
test_rsa_private_key.d, test_rsa_private_key.p,
test_rsa_private_key.q, test_rsa_private_key.dp,
test_rsa_private_key.dq, test_rsa_private_key.crt));
anonymous_tokens::RSAPublicKey public_key;
public_key.set_n(test_rsa_public_key.n);
public_key.set_e(test_rsa_public_key.e);
public_key_proto_.set_key_version(1);
public_key_proto_.set_use_case("TEST_USE_CASE");
public_key_proto_.set_serialized_public_key(public_key.SerializeAsString());
public_key_proto_.set_sig_hash_type(
anonymous_tokens::AT_HASH_TYPE_SHA384);
public_key_proto_.set_mask_gen_function(
anonymous_tokens::AT_MGF_SHA384);
public_key_proto_.set_salt_length(48);
public_key_proto_.set_key_size(256);
public_key_proto_.set_message_mask_type(
anonymous_tokens::AT_MESSAGE_MASK_NO_MASK);
public_key_proto_.set_message_mask_size(0);
expected_get_initial_data_request_.set_use_attestation(false);
expected_get_initial_data_request_.set_service_type("chromeipblinding");
expected_get_initial_data_request_.set_location_granularity(
privacy::ppn::GetInitialDataRequest_LocationGranularity_CITY_GEOS);
expected_get_initial_data_request_.set_validation_version(2);
expected_get_initial_data_request_.set_proxy_layer(privacy::ppn::PROXY_A);
privacy::ppn::GetInitialDataResponse fake_get_initial_data_response;
*fake_get_initial_data_response.mutable_at_public_metadata_public_key() =
public_key_proto_;
fake_get_initial_data_response_ = fake_get_initial_data_response;
privacy::ppn::GetInitialDataResponse::PrivacyPassData privacy_pass_data;
ANON_TOKENS_ASSERT_OK_AND_ASSIGN(
std::string public_key_der,
anonymous_tokens::RsaSsaPssPublicKeyToDerEncoding(
rsa_public_key_.get()));
const EVP_MD* sha256 = EVP_sha256();
ANON_TOKENS_ASSERT_OK_AND_ASSIGN(
token_key_id_, anonymous_tokens::ComputeHash(
public_key_der, *sha256));
anonymous_tokens::ExpirationTimestamp
expiration_timestamp;
int64_t one_hour_away = absl::ToUnixSeconds(absl::Now() + absl::Hours(1));
expiration_timestamp.timestamp = one_hour_away - (one_hour_away % 900);
expiration_timestamp.timestamp_precision = 900;
absl::StatusOr<anonymous_tokens::Extension>
expiration_extension = expiration_timestamp.AsExtension();
QUICHE_EXPECT_OK(expiration_extension);
extensions_.extensions.push_back(*expiration_extension);
anonymous_tokens::GeoHint geo_hint;
geo_hint.geo_hint = "US,US-AL,ALABASTER";
absl::StatusOr<anonymous_tokens::Extension>
geo_hint_extension = geo_hint.AsExtension();
QUICHE_EXPECT_OK(geo_hint_extension);
extensions_.extensions.push_back(*geo_hint_extension);
anonymous_tokens::ServiceType service_type;
service_type.service_type_id =
anonymous_tokens::ServiceType::kChromeIpBlinding;
absl::StatusOr<anonymous_tokens::Extension>
service_type_extension = service_type.AsExtension();
QUICHE_EXPECT_OK(service_type_extension);
extensions_.extensions.push_back(*service_type_extension);
anonymous_tokens::DebugMode debug_mode;
debug_mode.mode = anonymous_tokens::DebugMode::kDebug;
absl::StatusOr<anonymous_tokens::Extension>
debug_mode_extension = debug_mode.AsExtension();
QUICHE_EXPECT_OK(debug_mode_extension);
extensions_.extensions.push_back(*debug_mode_extension);
anonymous_tokens::ProxyLayer proxy_layer;
proxy_layer.layer =
anonymous_tokens::ProxyLayer::kProxyA;
absl::StatusOr<anonymous_tokens::Extension>
proxy_layer_extension = proxy_layer.AsExtension();
QUICHE_EXPECT_OK(proxy_layer_extension);
extensions_.extensions.push_back(*proxy_layer_extension);
absl::StatusOr<std::string> serialized_extensions =
anonymous_tokens::EncodeExtensions(extensions_);
QUICHE_EXPECT_OK(serialized_extensions);
privacy_pass_data.set_token_key_id(token_key_id_);
privacy_pass_data.set_public_metadata_extensions(*serialized_extensions);
*fake_get_initial_data_response.mutable_public_metadata_info() =
public_metadata_info_;
*fake_get_initial_data_response.mutable_privacy_pass_data() =
privacy_pass_data;
fake_get_initial_data_response_ = fake_get_initial_data_response;
privacy::ppn::BlindSignAuthOptions options;
options.set_enable_privacy_pass(true);
blind_sign_auth_ =
std::make_unique<BlindSignAuth>(&mock_message_interface_, options);
}
void TearDown() override { blind_sign_auth_.reset(nullptr); }
public:
void CreateSignResponse(const std::string& body, bool use_privacy_pass) {
privacy::ppn::AuthAndSignRequest request;
ASSERT_TRUE(request.ParseFromString(body));
EXPECT_EQ(request.service_type(), "chromeipblinding");
EXPECT_EQ(request.key_type(), privacy::ppn::AT_PUBLIC_METADATA_KEY_TYPE);
EXPECT_EQ(request.public_key_hash(), "");
EXPECT_EQ(request.key_version(), public_key_proto_.key_version());
EXPECT_EQ(request.do_not_use_rsa_public_exponent(), true);
EXPECT_NE(request.blinded_token().size(), 0);
if (use_privacy_pass) {
EXPECT_EQ(request.public_metadata_extensions(),
fake_get_initial_data_response_.privacy_pass_data()
.public_metadata_extensions());
} else {
EXPECT_EQ(request.public_metadata_info().SerializeAsString(),
public_metadata_info_.SerializeAsString());
}
privacy::ppn::AuthAndSignResponse response;
for (const auto& request_token : request.blinded_token()) {
std::string decoded_blinded_token;
ASSERT_TRUE(absl::Base64Unescape(request_token, &decoded_blinded_token));
if (use_privacy_pass) {
absl::StatusOr<std::string> signature =
anonymous_tokens::TestSignWithPublicMetadata(
decoded_blinded_token, request.public_metadata_extensions(),
*rsa_private_key_, false);
QUICHE_EXPECT_OK(signature);
response.add_blinded_token_signature(absl::Base64Escape(*signature));
} else {
absl::StatusOr<std::string> serialized_token =
anonymous_tokens::TestSign(
decoded_blinded_token, rsa_private_key_.get());
QUICHE_EXPECT_OK(serialized_token);
response.add_blinded_token_signature(
absl::Base64Escape(*serialized_token));
}
}
sign_response_ = response;
}
void ValidateGetTokensOutput(absl::Span<BlindSignToken> tokens) {
for (const auto& token : tokens) {
privacy::ppn::SpendTokenData spend_token_data;
ASSERT_TRUE(spend_token_data.ParseFromString(token.token));
EXPECT_EQ(spend_token_data.public_metadata().SerializeAsString(),
public_metadata_info_.public_metadata().SerializeAsString());
EXPECT_THAT(spend_token_data.unblinded_token(), StartsWith("blind:"));
EXPECT_GE(spend_token_data.unblinded_token_signature().size(),
spend_token_data.unblinded_token().size());
EXPECT_EQ(spend_token_data.signing_key_version(),
public_key_proto_.key_version());
EXPECT_NE(spend_token_data.use_case(),
anonymous_tokens::AnonymousTokensUseCase::
ANONYMOUS_TOKENS_USE_CASE_UNDEFINED);
EXPECT_NE(spend_token_data.message_mask(), "");
}
}
void ValidatePrivacyPassTokensOutput(absl::Span<BlindSignToken> tokens) {
for (const auto& token : tokens) {
privacy::ppn::PrivacyPassTokenData privacy_pass_token_data;
ASSERT_TRUE(privacy_pass_token_data.ParseFromString(token.token));
std::string decoded_token;
ASSERT_TRUE(absl::WebSafeBase64Unescape(privacy_pass_token_data.token(),
&decoded_token));
std::string decoded_extensions;
ASSERT_TRUE(absl::WebSafeBase64Unescape(
privacy_pass_token_data.encoded_extensions(), &decoded_extensions));
EXPECT_EQ(token.geo_hint.geo_hint, "US,US-AL,ALABASTER");
EXPECT_EQ(token.geo_hint.country_code, "US");
EXPECT_EQ(token.geo_hint.region, "US-AL");
EXPECT_EQ(token.geo_hint.city, "ALABASTER");
}
}
MockBlindSignMessageInterface mock_message_interface_;
std::unique_ptr<BlindSignAuth> blind_sign_auth_;
anonymous_tokens::RSABlindSignaturePublicKey
public_key_proto_;
bssl::UniquePtr<RSA> rsa_public_key_;
bssl::UniquePtr<RSA> rsa_private_key_;
std::string token_key_id_;
anonymous_tokens::Extensions extensions_;
privacy::ppn::PublicMetadataInfo public_metadata_info_;
privacy::ppn::AuthAndSignResponse sign_response_;
privacy::ppn::GetInitialDataResponse fake_get_initial_data_response_;
std::string oauth_token_ = "oauth_token";
privacy::ppn::GetInitialDataRequest expected_get_initial_data_request_;
};
TEST_F(BlindSignAuthTest, TestGetTokensFailedNetworkError) {
EXPECT_CALL(mock_message_interface_,
DoRequest(Eq(BlindSignMessageRequestType::kGetInitialData),
Eq(oauth_token_), _, _))
.Times(1)
.WillOnce([=](auto&&, auto&&, auto&&, auto get_initial_data_cb) {
std::move(get_initial_data_cb)(
absl::InternalError("Failed to create socket"));
});
EXPECT_CALL(mock_message_interface_,
DoRequest(Eq(BlindSignMessageRequestType::kAuthAndSign), _, _, _))
.Times(0);
int num_tokens = 1;
QuicheNotification done;
SignedTokenCallback callback =
[&done](absl::StatusOr<absl::Span<BlindSignToken>> tokens) {
EXPECT_THAT(tokens.status().code(), absl::StatusCode::kInternal);
done.Notify();
};
blind_sign_auth_->GetTokens(oauth_token_, num_tokens, ProxyLayer::kProxyA,
BlindSignAuthServiceType::kChromeIpBlinding,
std::move(callback));
done.WaitForNotification();
}
TEST_F(BlindSignAuthTest, TestGetTokensFailedBadGetInitialDataResponse) {
*fake_get_initial_data_response_.mutable_at_public_metadata_public_key()
->mutable_use_case() = "SPAM";
BlindSignMessageResponse fake_public_key_response(
absl::StatusCode::kOk,
fake_get_initial_data_response_.SerializeAsString());
EXPECT_CALL(
mock_message_interface_,
DoRequest(Eq(BlindSignMessageRequestType::kGetInitialData),
Eq(oauth_token_),
Eq(expected_get_initial_data_request_.SerializeAsString()), _))
.Times(1)
.WillOnce([=](auto&&, auto&&, auto&&, auto get_initial_data_cb) {
std::move(get_initial_data_cb)(fake_public_key_response);
});
EXPECT_CALL(mock_message_interface_,
DoRequest(Eq(BlindSignMessageRequestType::kAuthAndSign), _, _, _))
.Times(0);
int num_tokens = 1;
QuicheNotification done;
SignedTokenCallback callback =
[&done](absl::StatusOr<absl::Span<BlindSignToken>> tokens) {
EXPECT_THAT(tokens.status().code(), absl::StatusCode::kInvalidArgument);
done.Notify();
};
blind_sign_auth_->GetTokens(oauth_token_, num_tokens, ProxyLayer::kProxyA,
BlindSignAuthServiceType::kChromeIpBlinding,
std::move(callback));
done.WaitForNotification();
}
TEST_F(BlindSignAuthTest, TestGetTokensFailedBadAuthAndSignResponse) {
BlindSignMessageResponse fake_public_key_response(
absl::StatusCode::kOk,
fake_get_initial_data_response_.SerializeAsString());
{
InSequence seq;
EXPECT_CALL(
mock_message_interface_,
DoRequest(
Eq(BlindSignMessageRequestType::kGetInitialData), Eq(oauth_token_),
Eq(expected_get_initial_data_request_.SerializeAsString()), _))
.Times(1)
.WillOnce([=](auto&&, auto&&, auto&&, auto get_initial_data_cb) {
std::move(get_initial_data_cb)(fake_public_key_response);
});
EXPECT_CALL(mock_message_interface_,
DoRequest(Eq(BlindSignMessageRequestType::kAuthAndSign),
Eq(oauth_token_), _, _))
.Times(1)
.WillOnce(Invoke([this](Unused, Unused, const std::string& body,
BlindSignMessageCallback callback) {
CreateSignResponse(body, false);
sign_response_.add_blinded_token_signature("invalid_signature%");
BlindSignMessageResponse response(absl::StatusCode::kOk,
sign_response_.SerializeAsString());
std::move(callback)(response);
}));
}
int num_tokens = 1;
QuicheNotification done;
SignedTokenCallback callback =
[&done](absl::StatusOr<absl::Span<BlindSignToken>> tokens) {
EXPECT_THAT(tokens.status().code(), absl::StatusCode::kInternal);
done.Notify();
};
blind_sign_auth_->GetTokens(oauth_token_, num_tokens, ProxyLayer::kProxyA,
BlindSignAuthServiceType::kChromeIpBlinding,
std::move(callback));
done.WaitForNotification();
}
TEST_F(BlindSignAuthTest, TestPrivacyPassGetTokensSucceeds) {
BlindSignMessageResponse fake_public_key_response(
absl::StatusCode::kOk,
fake_get_initial_data_response_.SerializeAsString());
{
InSequence seq;
EXPECT_CALL(
mock_message_interface_,
DoRequest(
Eq(BlindSignMessageRequestType::kGetInitialData), Eq(oauth_token_),
Eq(expected_get_initial_data_request_.SerializeAsString()), _))
.Times(1)
.WillOnce([=](auto&&, auto&&, auto&&, auto get_initial_data_cb) {
std::move(get_initial_data_cb)(fake_public_key_response);
});
EXPECT_CALL(mock_message_interface_,
DoRequest(Eq(BlindSignMessageRequestType::kAuthAndSign),
Eq(oauth_token_), _, _))
.Times(1)
.WillOnce(Invoke([this](Unused, Unused, const std::string& body,
BlindSignMessageCallback callback) {
CreateSignResponse(body, true);
BlindSignMessageResponse response(absl::StatusCode::kOk,
sign_response_.SerializeAsString());
std::move(callback)(response);
}));
}
int num_tokens = 1;
QuicheNotification done;
SignedTokenCallback callback =
[this, &done](absl::StatusOr<absl::Span<BlindSignToken>> tokens) {
QUICHE_EXPECT_OK(tokens);
ValidatePrivacyPassTokensOutput(*tokens);
done.Notify();
};
blind_sign_auth_->GetTokens(oauth_token_, num_tokens, ProxyLayer::kProxyA,
BlindSignAuthServiceType::kChromeIpBlinding,
std::move(callback));
done.WaitForNotification();
}
TEST_F(BlindSignAuthTest, TestPrivacyPassGetTokensFailsWithBadExtensions) {
privacy::ppn::BlindSignAuthOptions options;
options.set_enable_privacy_pass(true);
blind_sign_auth_ =
std::make_unique<BlindSignAuth>(&mock_message_interface_, options);
public_key_proto_.set_message_mask_type(
anonymous_tokens::AT_MESSAGE_MASK_NO_MASK);
public_key_proto_.set_message_mask_size(0);
*fake_get_initial_data_response_.mutable_at_public_metadata_public_key() =
public_key_proto_;
fake_get_initial_data_response_.mutable_privacy_pass_data()
->set_public_metadata_extensions("spam");
BlindSignMessageResponse fake_public_key_response(
absl::StatusCode::kOk,
fake_get_initial_data_response_.SerializeAsString());
EXPECT_CALL(
mock_message_interface_,
DoRequest(Eq(BlindSignMessageRequestType::kGetInitialData),
Eq(oauth_token_),
Eq(expected_get_initial_data_request_.SerializeAsString()), _))
.Times(1)
.WillOnce([=](auto&&, auto&&, auto&&, auto get_initial_data_cb) {
std::move(get_initial_data_cb)(fake_public_key_response);
});
int num_tokens = 1;
QuicheNotification done;
SignedTokenCallback callback =
[&done](absl::StatusOr<absl::Span<BlindSignToken>> tokens) {
EXPECT_THAT(tokens.status().code(), absl::StatusCode::kInvalidArgument);
done.Notify();
};
blind_sign_auth_->GetTokens(oauth_token_, num_tokens, ProxyLayer::kProxyA,
BlindSignAuthServiceType::kChromeIpBlinding,
std::move(callback));
done.WaitForNotification();
}
}
}
} |
341 | #ifndef QUICHE_COMMON_QUICHE_SIMPLE_ARENA_H_
#define QUICHE_COMMON_QUICHE_SIMPLE_ARENA_H_
#include <memory>
#include <vector>
#include "quiche/common/platform/api/quiche_export.h"
namespace quiche {
class QUICHE_EXPORT QuicheSimpleArena {
public:
class QUICHE_EXPORT Status {
private:
friend class QuicheSimpleArena;
size_t bytes_allocated_;
public:
Status() : bytes_allocated_(0) {}
size_t bytes_allocated() const { return bytes_allocated_; }
};
explicit QuicheSimpleArena(size_t block_size);
~QuicheSimpleArena();
QuicheSimpleArena() = delete;
QuicheSimpleArena(const QuicheSimpleArena&) = delete;
QuicheSimpleArena& operator=(const QuicheSimpleArena&) = delete;
QuicheSimpleArena(QuicheSimpleArena&& other);
QuicheSimpleArena& operator=(QuicheSimpleArena&& other);
char* Alloc(size_t size);
char* Realloc(char* original, size_t oldsize, size_t newsize);
char* Memdup(const char* data, size_t size);
void Free(char* data, size_t size);
void Reset();
Status status() const { return status_; }
private:
struct QUICHE_EXPORT Block {
std::unique_ptr<char[]> data;
size_t size = 0;
size_t used = 0;
explicit Block(size_t s);
~Block();
Block(Block&& other);
Block& operator=(Block&& other);
};
void Reserve(size_t additional_space);
void AllocBlock(size_t size);
size_t block_size_;
std::vector<Block> blocks_;
Status status_;
};
}
#endif
#include "quiche/common/quiche_simple_arena.h"
#include <algorithm>
#include <cstring>
#include <utility>
#include "quiche/common/platform/api/quiche_logging.h"
namespace quiche {
QuicheSimpleArena::QuicheSimpleArena(size_t block_size)
: block_size_(block_size) {}
QuicheSimpleArena::~QuicheSimpleArena() = default;
QuicheSimpleArena::QuicheSimpleArena(QuicheSimpleArena&& other) = default;
QuicheSimpleArena& QuicheSimpleArena::operator=(QuicheSimpleArena&& other) =
default;
char* QuicheSimpleArena::Alloc(size_t size) {
Reserve(size);
Block& b = blocks_.back();
QUICHE_DCHECK_GE(b.size, b.used + size);
char* out = b.data.get() + b.used;
b.used += size;
return out;
}
char* QuicheSimpleArena::Realloc(char* original, size_t oldsize,
size_t newsize) {
QUICHE_DCHECK(!blocks_.empty());
Block& last = blocks_.back();
if (last.data.get() <= original && original < last.data.get() + last.size) {
QUICHE_DCHECK_GE(last.data.get() + last.used, original + oldsize);
if (original + oldsize == last.data.get() + last.used) {
if (original + newsize < last.data.get() + last.size) {
last.used += newsize - oldsize;
return original;
}
}
}
char* out = Alloc(newsize);
memcpy(out, original, oldsize);
return out;
}
char* QuicheSimpleArena::Memdup(const char* data, size_t size) {
char* out = Alloc(size);
memcpy(out, data, size);
return out;
}
void QuicheSimpleArena::Free(char* data, size_t size) {
if (blocks_.empty()) {
return;
}
Block& b = blocks_.back();
if (size <= b.used && data + size == b.data.get() + b.used) {
b.used -= size;
}
}
void QuicheSimpleArena::Reset() {
blocks_.clear();
status_.bytes_allocated_ = 0;
}
void QuicheSimpleArena::Reserve(size_t additional_space) {
if (blocks_.empty()) {
AllocBlock(std::max(additional_space, block_size_));
} else {
const Block& last = blocks_.back();
if (last.size < last.used + additional_space) {
AllocBlock(std::max(additional_space, block_size_));
}
}
}
void QuicheSimpleArena::AllocBlock(size_t size) {
blocks_.push_back(Block(size));
status_.bytes_allocated_ += size;
}
QuicheSimpleArena::Block::Block(size_t s)
: data(new char[s]), size(s), used(0) {}
QuicheSimpleArena::Block::~Block() = default;
QuicheSimpleArena::Block::Block(QuicheSimpleArena::Block&& other)
: size(other.size), used(other.used) {
data = std::move(other.data);
}
QuicheSimpleArena::Block& QuicheSimpleArena::Block::operator=(
QuicheSimpleArena::Block&& other) {
size = other.size;
used = other.used;
data = std::move(other.data);
return *this;
}
} | #include "quiche/common/quiche_simple_arena.h"
#include <string>
#include <vector>
#include "absl/strings/string_view.h"
#include "quiche/common/platform/api/quiche_test.h"
namespace quiche {
namespace {
size_t kDefaultBlockSize = 2048;
const char kTestString[] = "This is a decently long test string.";
TEST(QuicheSimpleArenaTest, NoAllocationOnConstruction) {
QuicheSimpleArena arena(kDefaultBlockSize);
EXPECT_EQ(0u, arena.status().bytes_allocated());
}
TEST(QuicheSimpleArenaTest, Memdup) {
QuicheSimpleArena arena(kDefaultBlockSize);
const size_t length = strlen(kTestString);
char* c = arena.Memdup(kTestString, length);
EXPECT_NE(nullptr, c);
EXPECT_NE(c, kTestString);
EXPECT_EQ(absl::string_view(c, length), kTestString);
}
TEST(QuicheSimpleArenaTest, MemdupLargeString) {
QuicheSimpleArena arena(10 );
const size_t length = strlen(kTestString);
char* c = arena.Memdup(kTestString, length);
EXPECT_NE(nullptr, c);
EXPECT_NE(c, kTestString);
EXPECT_EQ(absl::string_view(c, length), kTestString);
}
TEST(QuicheSimpleArenaTest, MultipleBlocks) {
QuicheSimpleArena arena(40 );
std::vector<std::string> strings = {
"One decently long string.", "Another string.",
"A third string that will surely go in a different block."};
std::vector<absl::string_view> copies;
for (const std::string& s : strings) {
absl::string_view sp(arena.Memdup(s.data(), s.size()), s.size());
copies.push_back(sp);
}
EXPECT_EQ(strings.size(), copies.size());
for (size_t i = 0; i < strings.size(); ++i) {
EXPECT_EQ(copies[i], strings[i]);
}
}
TEST(QuicheSimpleArenaTest, UseAfterReset) {
QuicheSimpleArena arena(kDefaultBlockSize);
const size_t length = strlen(kTestString);
char* c = arena.Memdup(kTestString, length);
arena.Reset();
c = arena.Memdup(kTestString, length);
EXPECT_NE(nullptr, c);
EXPECT_NE(c, kTestString);
EXPECT_EQ(absl::string_view(c, length), kTestString);
}
TEST(QuicheSimpleArenaTest, Free) {
QuicheSimpleArena arena(kDefaultBlockSize);
const size_t length = strlen(kTestString);
arena.Free(const_cast<char*>(kTestString), length);
char* c1 = arena.Memdup("Foo", 3);
char* c2 = arena.Memdup(kTestString, length);
arena.Free(const_cast<char*>(kTestString), length);
char* c3 = arena.Memdup("Bar", 3);
char* c4 = arena.Memdup(kTestString, length);
EXPECT_NE(c1, c2);
EXPECT_NE(c1, c3);
EXPECT_NE(c1, c4);
EXPECT_NE(c2, c3);
EXPECT_NE(c2, c4);
EXPECT_NE(c3, c4);
arena.Free(c4, length);
arena.Free(c2, length);
char* c5 = arena.Memdup("Baz", 3);
EXPECT_EQ(c4, c5);
}
TEST(QuicheSimpleArenaTest, Alloc) {
QuicheSimpleArena arena(kDefaultBlockSize);
const size_t length = strlen(kTestString);
char* c1 = arena.Alloc(length);
char* c2 = arena.Alloc(2 * length);
char* c3 = arena.Alloc(3 * length);
char* c4 = arena.Memdup(kTestString, length);
EXPECT_EQ(c1 + length, c2);
EXPECT_EQ(c2 + 2 * length, c3);
EXPECT_EQ(c3 + 3 * length, c4);
EXPECT_EQ(absl::string_view(c4, length), kTestString);
}
TEST(QuicheSimpleArenaTest, Realloc) {
QuicheSimpleArena arena(kDefaultBlockSize);
const size_t length = strlen(kTestString);
char* c1 = arena.Memdup(kTestString, length);
char* c2 = arena.Realloc(c1, length, 2 * length);
EXPECT_TRUE(c1);
EXPECT_EQ(c1, c2);
EXPECT_EQ(absl::string_view(c1, length), kTestString);
char* c3 = arena.Memdup(kTestString, length);
EXPECT_EQ(c2 + 2 * length, c3);
EXPECT_EQ(absl::string_view(c3, length), kTestString);
char* c4 = arena.Realloc(c3, length, 2 * length);
EXPECT_EQ(c3, c4);
EXPECT_EQ(absl::string_view(c4, length), kTestString);
char* c5 = arena.Realloc(c4, 2 * length, 3 * length);
EXPECT_EQ(c4, c5);
EXPECT_EQ(absl::string_view(c5, length), kTestString);
char* c6 = arena.Memdup(kTestString, length);
EXPECT_EQ(c5 + 3 * length, c6);
EXPECT_EQ(absl::string_view(c6, length), kTestString);
char* c7 = arena.Realloc(c6, length, kDefaultBlockSize);
EXPECT_EQ(absl::string_view(c7, length), kTestString);
arena.Free(c7, kDefaultBlockSize);
char* c8 = arena.Memdup(kTestString, length);
EXPECT_NE(c6, c7);
EXPECT_EQ(c7, c8);
EXPECT_EQ(absl::string_view(c8, length), kTestString);
}
}
} |
342 | #ifndef TENSORFLOW_COMPILER_MLIR_QUANTIZATION_TENSORFLOW_DEBUGGING_MLIR_DUMP_H_
#define TENSORFLOW_COMPILER_MLIR_QUANTIZATION_TENSORFLOW_DEBUGGING_MLIR_DUMP_H_
#include "absl/status/status.h"
#include "absl/strings/string_view.h"
#include "mlir/Pass/PassManager.h"
namespace tensorflow {
namespace quantization {
void EnableIrPrinting(mlir::PassManager &pm,
absl::string_view file_name_prefix);
absl::Status MaybeEnableIrPrinting(mlir::PassManager &pm,
absl::string_view file_name_prefix);
}
}
#endif
#include "tensorflow/compiler/mlir/quantization/tensorflow/debugging/mlir_dump.h"
#include <cstdint>
#include <cstdlib>
#include <memory>
#include <string>
#include <utility>
#include "absl/log/log.h"
#include "absl/memory/memory.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/match.h"
#include "absl/strings/string_view.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/FormatVariadic.h"
#include "llvm/Support/raw_ostream.h"
#include "mlir/Dialect/Func/IR/FuncOps.h"
#include "mlir/IR/Operation.h"
#include "mlir/IR/OperationSupport.h"
#include "mlir/Pass/Pass.h"
#include "mlir/Pass/PassManager.h"
#include "tsl/platform/env.h"
#include "tsl/platform/errors.h"
#include "tsl/platform/file_system.h"
#include "tsl/platform/path.h"
#include "tsl/platform/status.h"
#include "tsl/platform/statusor.h"
#include "tsl/platform/stringpiece.h"
namespace tensorflow {
namespace quantization {
namespace {
absl::StatusOr<std::string> GetMlirDumpDir() {
auto dump_dir = std::string(
absl::NullSafeStringView(std::getenv("TF_QUANT_MLIR_DUMP_PREFIX")));
if (dump_dir.empty()) {
return absl::FailedPreconditionError(
"Environment variable not set: TF_QUANT_MLIR_DUMP_PREFIX, "
"IR dump file for TF quantization is not created.");
}
if (absl::EqualsIgnoreCase(dump_dir, "sponge")) {
if (!tsl::io::GetTestUndeclaredOutputsDir(&dump_dir)) {
return absl::FailedPreconditionError(
"Environment variable TF_QUANT_MLIR_DUMP_PREFIX=sponge but "
"TEST_UNDECLARED_OUTPUT_DIRS not set.");
}
}
return dump_dir;
}
class WritableFileWrapper : public llvm::raw_ostream {
public:
~WritableFileWrapper() override { flush(); }
static absl::StatusOr<std::unique_ptr<WritableFileWrapper>> Create(
const std::string& filepath) {
std::unique_ptr<tsl::WritableFile> file;
TF_RETURN_IF_ERROR(tsl::Env::Default()->NewWritableFile(filepath, &file));
return absl::WrapUnique(new WritableFileWrapper(std::move(file)));
}
private:
explicit WritableFileWrapper(std::unique_ptr<tsl::WritableFile> file)
: file_(std::move(file)) {
SetBuffered();
}
uint64_t current_pos() const override {
int64_t position;
if (file_->Tell(&position).ok()) {
return position;
} else {
return -1;
}
}
void write_impl(const char* ptr, size_t size) override {
if (file_ && !file_->Append(tsl::StringPiece(ptr, size)).ok()) {
file_ = nullptr;
}
}
std::unique_ptr<tsl::WritableFile> file_;
};
absl::StatusOr<std::unique_ptr<llvm::raw_ostream>> CreateMlirDumpFile(
const absl::string_view dump_file_name) {
const absl::StatusOr<std::string> dump_dir = GetMlirDumpDir();
if (!dump_dir.ok()) {
return dump_dir.status();
}
auto* env = tsl::Env::Default();
TF_RETURN_IF_ERROR(env->RecursivelyCreateDir(*dump_dir));
const std::string dump_file_path =
tsl::io::JoinPath(*dump_dir, dump_file_name);
TF_ASSIGN_OR_RETURN(std::unique_ptr<llvm::raw_ostream> file,
WritableFileWrapper::Create(dump_file_path));
LOG(INFO) << "IR dump file created: " << dump_file_path;
return file;
}
class PrinterConfig : public mlir::PassManager::IRPrinterConfig {
public:
explicit PrinterConfig(
absl::string_view dump_file_prefix, bool print_module_scope = false,
bool print_after_only_on_change = true,
mlir::OpPrintingFlags op_printing_flags = mlir::OpPrintingFlags())
: mlir::PassManager::IRPrinterConfig(
print_module_scope, print_after_only_on_change,
false, op_printing_flags),
mlir_pass_count_(1),
dump_file_prefix_(dump_file_prefix) {}
void printBeforeIfEnabled(mlir::Pass* pass, mlir::Operation* op,
PrintCallbackFn print_callback) override {
Dump(pass, print_callback, true);
}
void printAfterIfEnabled(mlir::Pass* pass, mlir::Operation* op,
PrintCallbackFn print_callback) override {
Dump(pass, print_callback, false);
}
private:
int64_t mlir_pass_count_;
absl::string_view dump_file_prefix_;
llvm::DenseMap<mlir::Pass*, std::unique_ptr<llvm::raw_ostream>>
pass_to_dump_file_before_map_;
llvm::DenseMap<mlir::Pass*, std::unique_ptr<llvm::raw_ostream>>
pass_to_dump_file_after_map_;
llvm::DenseMap<mlir::Pass*, int64_t> pass_to_number_map_;
int64_t GetPassNumber(mlir::Pass* pass) {
if (!pass_to_number_map_.contains(pass)) {
pass_to_number_map_[pass] = mlir_pass_count_++;
}
return pass_to_number_map_[pass];
}
void Dump(mlir::Pass* pass, PrintCallbackFn print_callback, bool is_before) {
auto& pass_to_dump_file_map = is_before ? pass_to_dump_file_before_map_
: pass_to_dump_file_after_map_;
if (!pass_to_dump_file_map.contains(pass)) {
std::string filename = llvm::formatv(
"{0}_{1,0+4}_{2}_{3}.mlir", dump_file_prefix_, GetPassNumber(pass),
pass->getName().str(), is_before ? "before" : "after");
absl::StatusOr<std::unique_ptr<llvm::raw_ostream>> dump_file =
CreateMlirDumpFile(filename);
if (!dump_file.ok()) {
LOG(WARNING) << "Failed to dump MLIR module to " << filename;
return;
}
pass_to_dump_file_map[pass] = std::move(*dump_file);
}
return print_callback(*(pass_to_dump_file_map[pass]));
}
};
}
void EnableIrPrinting(mlir::PassManager& pm,
absl::string_view file_name_prefix) {
mlir::OpPrintingFlags flag{};
flag.useLocalScope().elideLargeElementsAttrs().enableDebugInfo();
if (pm.getContext()->isMultithreadingEnabled()) {
pm.getContext()->disableMultithreading();
}
pm.enableIRPrinting(std::make_unique<PrinterConfig>(
file_name_prefix, false,
true, flag));
}
absl::Status MaybeEnableIrPrinting(mlir::PassManager& pm,
absl::string_view file_name_prefix) {
if (!VLOG_IS_ON(1)) {
LOG(INFO) << "Verbosity level too low to enable IR printing.";
return absl::OkStatus();
}
EnableIrPrinting(pm, file_name_prefix);
LOG(INFO) << "IR dump for TensorFlow quantization pipeline enabled.";
return absl::OkStatus();
}
}
} | #include "tensorflow/compiler/mlir/quantization/tensorflow/debugging/mlir_dump.h"
#include <memory>
#include <string>
#include <vector>
#include "absl/cleanup/cleanup.h"
#include "llvm/ADT/StringRef.h"
#include "mlir/Dialect/Func/IR/FuncOps.h"
#include "mlir/IR/Builders.h"
#include "mlir/IR/BuiltinDialect.h"
#include "mlir/IR/BuiltinOps.h"
#include "mlir/IR/MLIRContext.h"
#include "mlir/Parser/Parser.h"
#include "mlir/Pass/Pass.h"
#include "mlir/Pass/PassManager.h"
#include "mlir/Support/LogicalResult.h"
#include "mlir/Support/TypeID.h"
#include "mlir/Transforms/Passes.h"
#include "stablehlo/dialect/StablehloOps.h"
#include "tsl/lib/core/status_test_util.h"
#include "tsl/platform/env.h"
#include "tsl/platform/path.h"
#include "tsl/platform/test.h"
namespace tensorflow {
namespace quantization {
namespace mlir_dump_test {
class NoOpPass
: public mlir::PassWrapper<NoOpPass, mlir::OperationPass<mlir::ModuleOp>> {
public:
MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(NoOpPass)
NoOpPass() = default;
llvm::StringRef getArgument() const final { return "no-op-pass"; }
void runOnOperation() override {
}
};
std::unique_ptr<mlir::OperationPass<mlir::ModuleOp>> CreateNoOpPass() {
return std::make_unique<NoOpPass>();
}
class ParentPass
: public mlir::PassWrapper<ParentPass,
mlir::OperationPass<mlir::ModuleOp>> {
public:
MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ParentPass)
ParentPass() = default;
llvm::StringRef getArgument() const final { return "parent-pass"; }
void runOnOperation() override {
mlir::MLIRContext* ctx = &getContext();
mlir::ModuleOp module_op = getOperation();
mlir::PassManager pm(ctx);
pm.addPass(CreateNoOpPass());
EnableIrPrinting(pm, "dump2");
if (failed(pm.run(module_op))) {
signalPassFailure();
}
}
};
std::unique_ptr<mlir::OperationPass<mlir::ModuleOp>> CreateParentPass() {
return std::make_unique<ParentPass>();
}
}
namespace {
using namespace tensorflow::quantization::mlir_dump_test;
class EnableIrPrintingTest : public ::testing::Test {
protected:
EnableIrPrintingTest() : env_(tsl::Env::Default()) {
if (!tsl::io::GetTestUndeclaredOutputsDir(&test_dir_)) {
test_dir_ = tsl::testing::TmpDir();
}
}
void SetUp() override {
tsl::setenv("TF_QUANT_MLIR_DUMP_PREFIX", test_dir_.c_str(), 1);
mlir::DialectRegistry dialects;
dialects.insert<mlir::BuiltinDialect, mlir::func::FuncDialect,
mlir::stablehlo::StablehloDialect>();
ctx_ = std::make_unique<mlir::MLIRContext>(dialects);
ctx_->loadAllAvailableDialects();
}
void TearDown() override {
std::vector<std::string> files;
TF_ASSERT_OK(
env_->GetMatchingPaths(tsl::io::JoinPath(test_dir_, "*"), &files));
for (const std::string& file : files) {
TF_ASSERT_OK(env_->DeleteFile(file));
}
}
tsl::Env* env_;
std::string test_dir_;
std::unique_ptr<mlir::MLIRContext> ctx_;
};
TEST_F(EnableIrPrintingTest, PassSuccessfullyRuns) {
mlir::PassManager pm = {ctx_.get()};
pm.addPass(CreateNoOpPass());
pm.addNestedPass<mlir::func::FuncOp>(mlir::createCanonicalizerPass());
pm.addNestedPass<mlir::func::FuncOp>(mlir::createCanonicalizerPass());
EnableIrPrinting(pm, "dump");
constexpr absl::string_view program = R"mlir(
module{
func.func @main(%arg0: tensor<10xf32>) -> tensor<10xf32> {
return %arg0 : tensor<10xf32>
}
func.func @func1(%arg0: tensor<10xf32>, %arg1: tensor<10xf32>) -> tensor<10xf32> {
%0 = stablehlo.add %arg0, %arg1 : tensor<10xf32>
%1 = stablehlo.add %arg0, %arg1 : tensor<10xf32>
return %0 : tensor<10xf32>
}
})mlir";
auto module_op = mlir::parseSourceString<mlir::ModuleOp>(program, ctx_.get());
const mlir::LogicalResult result = pm.run(module_op.get());
EXPECT_FALSE(failed(result));
TF_EXPECT_OK(tsl::Env::Default()->FileExists(
tsl::io::JoinPath(test_dir_,
"dump_0001_tensorflow::quantization::mlir_dump_test"
"::NoOpPass_before.mlir")));
TF_EXPECT_OK(tsl::Env::Default()->FileExists(
tsl::io::JoinPath(test_dir_, "dump_0002_Canonicalizer_before.mlir")));
TF_EXPECT_OK(tsl::Env::Default()->FileExists(
tsl::io::JoinPath(test_dir_, "dump_0002_Canonicalizer_after.mlir")));
TF_EXPECT_OK(tsl::Env::Default()->FileExists(
tsl::io::JoinPath(test_dir_, "dump_0003_Canonicalizer_before.mlir")));
}
TEST_F(EnableIrPrintingTest, NestedPassSuccessfullyRuns) {
mlir::MLIRContext ctx{};
mlir::PassManager pm = {&ctx};
pm.addPass(CreateParentPass());
EnableIrPrinting(pm, "dump");
mlir::OpBuilder builder(&ctx);
auto module_op = builder.create<mlir::ModuleOp>(builder.getUnknownLoc());
const absl::Cleanup module_op_cleanup = [module_op] { module_op->destroy(); };
const mlir::LogicalResult result = pm.run(module_op);
EXPECT_FALSE(failed(result));
TF_EXPECT_OK(tsl::Env::Default()->FileExists(
tsl::io::JoinPath(test_dir_,
"dump_0001_tensorflow::quantization::mlir_dump_test"
"::ParentPass_before.mlir")));
TF_EXPECT_OK(tsl::Env::Default()->FileExists(
tsl::io::JoinPath(test_dir_,
"dump2_0001_tensorflow::quantization::mlir_dump_test"
"::NoOpPass_before.mlir")));
}
}
}
} |
343 | #ifndef XLA_SERVICE_COLLECTIVE_TRANSFORMATION_REORDERER_H_
#define XLA_SERVICE_COLLECTIVE_TRANSFORMATION_REORDERER_H_
#include "absl/container/flat_hash_set.h"
#include "absl/status/statusor.h"
#include "absl/strings/string_view.h"
#include "xla/hlo/ir/hlo_instruction.h"
#include "xla/hlo/ir/hlo_instructions.h"
#include "xla/hlo/ir/hlo_module.h"
#include "xla/service/hlo_pass_interface.h"
namespace xla {
class CollectiveTransformationReorder : public HloModulePass {
public:
CollectiveTransformationReorder() = default;
~CollectiveTransformationReorder() override = default;
absl::string_view name() const override {
return "collective-transformation-reorderer";
}
using HloPassInterface::Run;
absl::StatusOr<bool> Run(
HloModule* module,
const absl::flat_hash_set<absl::string_view>& execution_threads) override;
private:
absl::StatusOr<bool> ReorderAllGatherTransformations(
HloModule* module,
const absl::flat_hash_set<absl::string_view>& execution_threads);
absl::StatusOr<bool> ReorderAllReduceTransformations(
HloModule* module,
const absl::flat_hash_set<absl::string_view>& execution_threads);
};
}
#endif
#include "xla/service/collective_transformation_reorderer.h"
#include <cstdint>
#include <optional>
#include <utility>
#include <vector>
#include "absl/container/flat_hash_map.h"
#include "absl/log/check.h"
#include "xla/hlo/ir/hlo_casting_utils.h"
#include "xla/hlo/ir/hlo_instruction.h"
#include "xla/hlo/ir/hlo_instructions.h"
#include "xla/hlo/ir/hlo_opcode.h"
#include "xla/service/hlo_dce.h"
#include "tsl/platform/statusor.h"
namespace xla {
namespace {
struct CollectiveTransformation {
HloInstruction* hlo;
int64_t transformed_collective_dimension;
};
std::optional<std::vector<CollectiveTransformation>>
GetAllGatherTransformations(HloInstruction* all_gather) {
std::vector<HloInstruction*> transformation_hlos;
{
HloInstruction* transformation_hlo = all_gather;
bool found_unsupported_transformation = false;
while (transformation_hlo->user_count() == 1 &&
!found_unsupported_transformation) {
transformation_hlo = transformation_hlo->users()[0];
switch (transformation_hlo->opcode()) {
case HloOpcode::kReshape: {
transformation_hlos.push_back(transformation_hlo);
break;
}
default:
found_unsupported_transformation = true;
}
}
}
if (transformation_hlos.empty()) {
return std::nullopt;
}
auto get_reshaped_all_gather_dimension =
[](const Shape& all_gather_shape, int64_t all_gather_dimension,
HloInstruction* transformation_hlo) -> std::optional<int64_t> {
int64_t all_gather_num_strides = absl::c_accumulate(
all_gather_shape.dimensions().subspan(0, all_gather_dimension), 1,
[](int64_t product, int64_t dimension_size) {
return product * dimension_size;
});
int64_t reshaped_all_gather_dimension = 0;
int64_t reshaped_num_strides = 1;
while (reshaped_all_gather_dimension <
transformation_hlo->shape().dimensions_size() &&
reshaped_num_strides < all_gather_num_strides) {
reshaped_num_strides *=
transformation_hlo->shape().dimensions(reshaped_all_gather_dimension);
++reshaped_all_gather_dimension;
}
if (reshaped_num_strides != all_gather_num_strides) {
return std::nullopt;
}
if (transformation_hlo->shape().dimensions(reshaped_all_gather_dimension) !=
all_gather_shape.dimensions(all_gather_dimension)) {
return std::nullopt;
}
return reshaped_all_gather_dimension;
};
std::vector<CollectiveTransformation> transformations;
HloAllGatherInstruction* all_gather_instruction =
DynCast<HloAllGatherInstruction>(all_gather);
Shape all_gather_shape = all_gather_instruction->shape();
int64_t all_gather_dimension = all_gather_instruction->all_gather_dimension();
CHECK(all_gather_instruction != nullptr);
for (HloInstruction* transformation_hlo : transformation_hlos) {
bool found_unsupported_transformation = false;
switch (transformation_hlo->opcode()) {
case HloOpcode::kReshape: {
std::optional<int64_t> reshaped_all_gather_dimension =
get_reshaped_all_gather_dimension(
all_gather_shape, all_gather_dimension, transformation_hlo);
if (reshaped_all_gather_dimension.has_value()) {
transformations.push_back(
{transformation_hlo, *reshaped_all_gather_dimension});
all_gather_shape = transformation_hlo->shape();
all_gather_dimension = *reshaped_all_gather_dimension;
} else {
found_unsupported_transformation = true;
}
break;
}
default:
return std::nullopt;
}
if (found_unsupported_transformation) {
break;
}
}
if (transformations.empty()) {
return std::nullopt;
}
return transformations;
}
std::vector<HloInstruction*> GetAllReduceTransformations(
HloInstruction* all_reduce) {
HloAllReduceInstruction* all_reduce_instruction =
DynCast<HloAllReduceInstruction>(all_reduce);
CHECK_NE(all_reduce_instruction, nullptr);
if (all_reduce_instruction->constrain_layout()) {
return {};
}
std::vector<HloInstruction*> transformation_hlos;
HloInstruction* transformation_hlo = all_reduce->mutable_operand(0);
while (transformation_hlo->opcode() == HloOpcode::kReshape &&
transformation_hlo->user_count() == 1) {
transformation_hlos.push_back(transformation_hlo);
transformation_hlo = transformation_hlo->mutable_operand(0);
}
return transformation_hlos;
}
}
absl::StatusOr<bool>
CollectiveTransformationReorder::ReorderAllGatherTransformations(
HloModule* module,
const absl::flat_hash_set<absl::string_view>& execution_threads) {
HloInstructionMap<std::vector<CollectiveTransformation>>
all_gather_to_transformations;
for (HloComputation* computation :
module->MakeComputationPostOrder(execution_threads)) {
for (HloInstruction* instruction :
computation->MakeInstructionPostOrder()) {
if (instruction->opcode() == HloOpcode::kAllGather) {
if (instruction->operand_count() != 1) {
continue;
}
std::optional<std::vector<CollectiveTransformation>>
all_gather_transformations =
GetAllGatherTransformations(instruction);
if (all_gather_transformations.has_value()) {
all_gather_to_transformations[instruction] =
*std::move(all_gather_transformations);
}
}
}
}
if (all_gather_to_transformations.empty()) {
return false;
}
auto reshape_all_gather_operand =
[](HloInstruction* all_gather_operand,
int64_t original_all_gather_dimension,
const CollectiveTransformation& transformation) {
Shape reshaped_all_gather_operand_shape = transformation.hlo->shape();
int64_t operand_all_gather_dimension_size =
all_gather_operand->shape().dimensions(
original_all_gather_dimension);
reshaped_all_gather_operand_shape.set_dimensions(
transformation.transformed_collective_dimension,
operand_all_gather_dimension_size);
HloComputation* computation = all_gather_operand->parent();
return computation->AddInstruction(HloInstruction::CreateReshape(
reshaped_all_gather_operand_shape, all_gather_operand));
};
for (auto& [instruction, transformations] : all_gather_to_transformations) {
HloAllGatherInstruction* all_gather =
DynCast<HloAllGatherInstruction>(instruction);
int64_t all_gather_dimension = all_gather->all_gather_dimension();
int64_t original_all_gather_dimension_size =
all_gather->shape().dimensions(all_gather_dimension);
HloInstruction* all_gather_operand = instruction->mutable_operand(0);
for (const CollectiveTransformation& transformation : transformations) {
all_gather_operand = reshape_all_gather_operand(
all_gather_operand, all_gather_dimension, transformation);
all_gather_dimension = transformation.transformed_collective_dimension;
}
Shape new_all_gather_shape = all_gather_operand->shape();
new_all_gather_shape.set_dimensions(all_gather_dimension,
original_all_gather_dimension_size);
HloComputation* computation = all_gather_operand->parent();
HloInstruction* new_all_gather =
computation->AddInstruction(HloInstruction::CreateAllGather(
new_all_gather_shape, {all_gather_operand}, all_gather_dimension,
all_gather->device_list(), all_gather->constrain_layout(),
all_gather->channel_id(), all_gather->use_global_device_ids()));
TF_RETURN_IF_ERROR(
transformations.back().hlo->ReplaceAllUsesWith(new_all_gather));
if (computation->root_instruction() == transformations.back().hlo) {
computation->set_root_instruction(new_all_gather);
}
}
return true;
}
absl::StatusOr<bool>
CollectiveTransformationReorder::ReorderAllReduceTransformations(
HloModule* module,
const absl::flat_hash_set<absl::string_view>& execution_threads) {
HloInstructionMap<std::vector<HloInstruction*>> all_reduce_to_transformations;
for (HloComputation* computation :
module->MakeComputationPostOrder(execution_threads)) {
for (HloInstruction* instruction :
computation->MakeInstructionPostOrder()) {
if (instruction->opcode() == HloOpcode::kAllReduce) {
if (instruction->user_count() != 1 ||
computation->root_instruction() == instruction) {
continue;
}
std::vector<HloInstruction*> reshapes =
GetAllReduceTransformations(instruction);
if (reshapes.empty()) {
continue;
}
all_reduce_to_transformations[instruction] = std::move(reshapes);
}
}
}
if (all_reduce_to_transformations.empty()) {
return false;
}
for (auto& [inst, reshapes] : all_reduce_to_transformations) {
HloComputation* computation = inst->parent();
HloAllReduceInstruction* all_reduce =
DynCast<HloAllReduceInstruction>(inst);
CHECK(!reshapes.empty());
HloInstruction* cur_operand = reshapes.back()->mutable_operand(0);
HloInstruction* new_all_reduce =
computation->AddInstruction(HloInstruction::CreateAllReduce(
cur_operand->shape(), {cur_operand}, all_reduce->to_apply(),
all_reduce->device_list(), all_reduce->constrain_layout(),
all_reduce->channel_id(), all_reduce->use_global_device_ids()));
cur_operand = new_all_reduce;
for (int64_t i = reshapes.size() - 1; i >= 0; --i) {
cur_operand = computation->AddInstruction(
HloInstruction::CreateReshape(reshapes[i]->shape(), cur_operand));
}
TF_RETURN_IF_ERROR(
computation->ReplaceInstruction(all_reduce, cur_operand));
}
return true;
}
absl::StatusOr<bool> CollectiveTransformationReorder::Run(
HloModule* module,
const absl::flat_hash_set<absl::string_view>& execution_threads) {
TF_ASSIGN_OR_RETURN(bool ag_changed, ReorderAllGatherTransformations(
module, execution_threads));
TF_ASSIGN_OR_RETURN(bool ar_changed, ReorderAllReduceTransformations(
module, execution_threads));
if (ag_changed || ar_changed) {
HloDCE dce;
TF_RETURN_IF_ERROR(dce.Run(module, execution_threads).status());
}
return ag_changed || ar_changed;
}
} | #include "xla/service/collective_transformation_reorderer.h"
#include <memory>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "absl/status/statusor.h"
#include "absl/strings/string_view.h"
#include "xla/hlo/ir/hlo_instruction.h"
#include "xla/hlo/ir/hlo_module.h"
#include "xla/hlo/utils/hlo_matchers.h"
#include "xla/service/hlo_verifier.h"
#include "xla/tests/hlo_test_base.h"
#include "tsl/lib/core/status_test_util.h"
#include "tsl/platform/statusor.h"
namespace xla {
namespace {
namespace op = xla::testing::opcode_matchers;
class CollectiveTransformationReordererTest : public HloTestBase {
public:
absl::StatusOr<bool> RunCollectiveTransformationReorderer(HloModule* module) {
CollectiveTransformationReorder reorderer;
return reorderer.Run(module, {});
}
};
TEST_F(CollectiveTransformationReordererTest,
ReshapeWithinShardAfterAllGatherDim) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
param = bf16[8,4,1024] parameter(0)
all-gather = bf16[8,32,1024] all-gather(param), dimensions={1}, replica_groups={{0,1,2,3,4,5,6,7}}, channel_id=1
ROOT reshape = bf16[8,32,8,128] reshape(all-gather)
}
)";
TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> module,
ParseAndReturnVerifiedModule(hlo_string));
TF_ASSERT_OK_AND_ASSIGN(bool changed,
RunCollectiveTransformationReorderer(module.get()));
EXPECT_TRUE(changed);
EXPECT_THAT(module->entry_computation()->root_instruction(),
op::AllGather(op::Reshape(op::Parameter())));
HloInstruction* all_gather = module->entry_computation()->root_instruction();
EXPECT_THAT(all_gather->dimensions(), ::testing::ElementsAre(1));
}
TEST_F(CollectiveTransformationReordererTest,
ReshapeWithinShardBeforeAllGatherDim) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
param = bf16[8,32,8,4,1024] parameter(0)
all-gather = bf16[8,32,8,32,1024] all-gather(param), dimensions={3}, replica_groups={{0,1,2,3,4,5,6,7}}, channel_id=1
ROOT reshape = bf16[2048,32,1024] reshape(all-gather)
}
)";
TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> module,
ParseAndReturnVerifiedModule(hlo_string));
TF_ASSERT_OK_AND_ASSIGN(bool changed,
RunCollectiveTransformationReorderer(module.get()));
EXPECT_TRUE(changed);
EXPECT_THAT(module->entry_computation()->root_instruction(),
op::AllGather(op::Reshape(op::Parameter())));
HloInstruction* all_gather = module->entry_computation()->root_instruction();
EXPECT_THAT(all_gather->dimensions(), ::testing::ElementsAre(1));
}
TEST_F(CollectiveTransformationReordererTest,
ReshapeWithinShardBeforeAndAfterAllGatherDim) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
param = bf16[8,32,8,4,1024] parameter(0)
all-gather = bf16[8,32,8,32,1024] all-gather(param), dimensions={3}, replica_groups={{0,1,2,3,4,5,6,7}}, channel_id=1
ROOT reshape = bf16[2048,32,8,128] reshape(all-gather)
}
)";
TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> module,
ParseAndReturnVerifiedModule(hlo_string));
TF_ASSERT_OK_AND_ASSIGN(bool changed,
RunCollectiveTransformationReorderer(module.get()));
EXPECT_TRUE(changed);
EXPECT_THAT(module->entry_computation()->root_instruction(),
op::AllGather(op::Reshape(op::Parameter())));
HloInstruction* all_gather = module->entry_computation()->root_instruction();
EXPECT_THAT(all_gather->dimensions(), ::testing::ElementsAre(1));
}
TEST_F(CollectiveTransformationReordererTest, ReshapeAcrossShards) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
param = bf16[8,1,8,128] parameter(0)
all-gather = bf16[8,8,8,128] all-gather(param), dimensions={1}, replica_groups={{0,1,2,3,4,5,6,7}}, channel_id=1
ROOT reshape = bf16[64,8,128] reshape(all-gather)
}
)";
TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> module,
ParseAndReturnVerifiedModule(hlo_string));
TF_ASSERT_OK_AND_ASSIGN(bool changed,
RunCollectiveTransformationReorderer(module.get()));
EXPECT_FALSE(changed);
}
TEST_F(CollectiveTransformationReordererTest, MergeAllGatherDimensionWithNext) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
param = bf16[8,8,16,16] parameter(0)
all-gather = bf16[64,8,16,16] all-gather(param), dimensions={0}, replica_groups={{0,1,2,3,4,5,6,7}}, channel_id=1
ROOT reshape = bf16[512,16,16] reshape(all-gather)
}
)";
TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> module,
ParseAndReturnVerifiedModule(hlo_string));
TF_ASSERT_OK_AND_ASSIGN(bool changed,
RunCollectiveTransformationReorderer(module.get()));
EXPECT_FALSE(changed);
}
TEST_F(CollectiveTransformationReordererTest,
MergeAllGatherDimensionWithPrevious) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
param = bf16[8,8,16,16] parameter(0)
all-gather = bf16[8,64,16,16] all-gather(param), dimensions={1}, replica_groups={{0,1,2,3,4,5,6,7}}, channel_id=1
ROOT reshape = bf16[512,16,16] reshape(all-gather)
}
)";
TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> module,
ParseAndReturnVerifiedModule(hlo_string));
TF_ASSERT_OK_AND_ASSIGN(bool changed,
RunCollectiveTransformationReorderer(module.get()));
EXPECT_FALSE(changed);
}
TEST_F(CollectiveTransformationReordererTest, AllReduceSingleReshape) {
absl::string_view hlo_string = R"(
HloModule module
add {
a = bf16[] parameter(0)
b = bf16[] parameter(1)
ROOT s = bf16[] add(a, b)
}
ENTRY entry {
param = bf16[16384,6144] parameter(0)
reshape = bf16[1,16384,6144] reshape(param)
all-reduce = bf16[1,16384,6144] all-reduce(reshape), channel_id=1, replica_groups={{0,1,2,3,4,5,6,7}}, to_apply=add
constant = s32[] constant(0)
ROOT dynamic-slice = bf16[1,16384,384] dynamic-slice(all-reduce, constant, constant, constant), dynamic_slice_sizes={1,16384,384}
}
)";
TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> module,
ParseAndReturnVerifiedModule(hlo_string));
TF_ASSERT_OK_AND_ASSIGN(bool changed,
RunCollectiveTransformationReorderer(module.get()));
EXPECT_TRUE(changed);
TF_ASSERT_OK(HloVerifier(false,
true)
.Run(module.get())
.status());
EXPECT_THAT(module->entry_computation()->root_instruction(),
op::DynamicSlice(op::Reshape(op::AllReduce(op::Parameter())),
op::Constant(), op::Constant(), op::Constant()));
}
TEST_F(CollectiveTransformationReordererTest, AllReduceTwoReshapes) {
absl::string_view hlo_string = R"(
HloModule module
add {
a = bf16[] parameter(0)
b = bf16[] parameter(1)
ROOT s = bf16[] add(a, b)
}
ENTRY entry {
param = bf16[16384,3072,2] parameter(0)
reshape.1 = bf16[16384,6144] reshape(param)
reshape.2 = bf16[1,16384,6144] reshape(reshape.1)
all-reduce = bf16[1,16384,6144] all-reduce(reshape.2), channel_id=1, replica_groups={{0,1,2,3,4,5,6,7}}, to_apply=add
constant = s32[] constant(0)
ROOT dynamic-slice = bf16[1,16384,384] dynamic-slice(all-reduce, constant, constant, constant), dynamic_slice_sizes={1,16384,384}
}
)";
TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> module,
ParseAndReturnVerifiedModule(hlo_string));
TF_ASSERT_OK_AND_ASSIGN(bool changed,
RunCollectiveTransformationReorderer(module.get()));
EXPECT_TRUE(changed);
TF_ASSERT_OK(HloVerifier(false,
true)
.Run(module.get())
.status());
EXPECT_THAT(
module->entry_computation()->root_instruction(),
op::DynamicSlice(op::Reshape(op::Reshape(op::AllReduce(op::Parameter()))),
op::Constant(), op::Constant(), op::Constant()));
}
TEST_F(CollectiveTransformationReordererTest, AllReduceReshapeWithTwoUsers) {
absl::string_view hlo_string = R"(
HloModule module
add {
a = bf16[] parameter(0)
b = bf16[] parameter(1)
ROOT s = bf16[] add(a, b)
}
ENTRY entry {
param = bf16[16384,6144] parameter(0)
reshape = bf16[1,16384,6144] reshape(param)
all-reduce = bf16[1,16384,6144] all-reduce(reshape), channel_id=1, replica_groups={{0,1,2,3,4,5,6,7}}, to_apply=add
constant = s32[] constant(0)
dynamic-slice = bf16[1,16384,384] dynamic-slice(all-reduce, constant, constant, constant), dynamic_slice_sizes={1,16384,384}
copy = bf16[1,16384,6144] copy(reshape)
ROOT tuple = (bf16[1,16384,6144], bf16[1,16384,384]) tuple(copy, dynamic-slice)
}
)";
TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> module,
ParseAndReturnVerifiedModule(hlo_string));
TF_ASSERT_OK_AND_ASSIGN(bool changed,
RunCollectiveTransformationReorderer(module.get()));
EXPECT_FALSE(changed);
}
TEST_F(CollectiveTransformationReordererTest, AllReduceWithTwoUsersReshape) {
absl::string_view hlo_string = R"(
HloModule module
add {
a = bf16[] parameter(0)
b = bf16[] parameter(1)
ROOT s = bf16[] add(a, b)
}
ENTRY entry {
param = bf16[16384,6144] parameter(0)
reshape = bf16[1,16384,6144] reshape(param)
all-reduce = bf16[1,16384,6144] all-reduce(reshape), channel_id=1, replica_groups={{0,1,2,3,4,5,6,7}}, to_apply=add
constant = s32[] constant(0)
dynamic-slice = bf16[1,16384,384] dynamic-slice(all-reduce, constant, constant, constant), dynamic_slice_sizes={1,16384,384}
copy = bf16[1,16384,6144] copy(all-reduce)
ROOT tuple = (bf16[1,16384,6144], bf16[1,16384,384]) tuple(copy, dynamic-slice)
}
)";
TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> module,
ParseAndReturnVerifiedModule(hlo_string));
TF_ASSERT_OK_AND_ASSIGN(bool changed,
RunCollectiveTransformationReorderer(module.get()));
EXPECT_FALSE(changed);
}
TEST_F(CollectiveTransformationReordererTest, AllReduceConstrainLayout) {
absl::string_view hlo_string = R"(
HloModule module
add {
a = bf16[] parameter(0)
b = bf16[] parameter(1)
ROOT s = bf16[] add(a, b)
}
ENTRY entry {
param = bf16[16384,6144] parameter(0)
reshape = bf16[1,16384,6144] reshape(param)
all-reduce = bf16[1,16384,6144] all-reduce(reshape), channel_id=1, replica_groups={{0,1,2,3,4,5,6,7}}, constrain_layout=true, to_apply=add
constant = s32[] constant(0)
ROOT dynamic-slice = bf16[1,16384,384] dynamic-slice(all-reduce, constant, constant, constant), dynamic_slice_sizes={1,16384,384}
}
)";
TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> module,
ParseAndReturnVerifiedModule(hlo_string));
TF_ASSERT_OK_AND_ASSIGN(bool changed,
RunCollectiveTransformationReorderer(module.get()));
EXPECT_FALSE(changed);
}
}
} |
344 | #ifndef XLA_SERVICE_MEMORY_SPACE_ASSIGNMENT_ALGORITHM_H_
#define XLA_SERVICE_MEMORY_SPACE_ASSIGNMENT_ALGORITHM_H_
#include <algorithm>
#include <cstdint>
#include <list>
#include <map>
#include <memory>
#include <optional>
#include <set>
#include <string>
#include <tuple>
#include <type_traits>
#include <utility>
#include <variant>
#include <vector>
#if defined(__GNUC__) || defined(__clang__)
#include "absl/container/btree_map.h"
#endif
#include "absl/container/flat_hash_map.h"
#include "absl/container/flat_hash_set.h"
#include "absl/functional/any_invocable.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/types/span.h"
#include "xla/hlo/ir/hlo_instruction.h"
#include "xla/hlo/utils/hlo_live_range.h"
#include "xla/service/buffer_value.h"
#include "xla/service/call_graph.h"
#include "xla/service/heap_simulator/allocation_block.h"
#include "xla/service/heap_simulator/heap_simulator.h"
#include "xla/service/hlo.pb.h"
#include "xla/service/hlo_alias_analysis.h"
#include "xla/service/hlo_value.h"
#include "xla/service/memory_space_assignment/allocation.h"
#include "xla/service/memory_space_assignment/buffer_interval_comparator.h"
#include "xla/service/memory_space_assignment/memory_space_assignment.pb.h"
#include "xla/service/memory_space_assignment/options.h"
#include "xla/service/memory_space_assignment/slice.h"
#include "xla/shape.h"
#include "xla/shape_util.h"
#include "xla/util.h"
namespace xla {
namespace memory_space_assignment {
class AllocationValue {
public:
struct Use {
HloUse hlo_use;
int64_t time;
std::vector<HloPosition> aliases;
bool operator==(const Use& other) const {
return hlo_use == other.hlo_use && time == other.time &&
aliases == other.aliases;
}
template <typename H>
friend H AbslHashValue(H h, const Use& s) {
return H::combine(std::move(h), s.hlo_use, s.time, s.aliases);
}
};
AllocationValue(const HloValue* value, const HloPosition& position,
int64_t size)
: value_(value),
defining_position_(position),
size_(size),
requires_contiguous_allocation_(false) {}
const HloPosition& defining_position() const { return defining_position_; }
const HloInstruction* defining_instruction() const {
return defining_position().instruction;
}
int64_t size() const { return size_; }
const std::vector<Use>& uses() const { return uses_; }
std::vector<Use>& uses() { return uses_; }
const HloValue* value() const { return value_; }
const HloComputation* computation() const {
return defining_instruction()->parent();
}
AllocationSequence* mutable_allocation_sequence() {
return &allocation_sequence_;
}
const AllocationSequence* allocation_sequence() const {
return &allocation_sequence_;
}
bool requires_contiguous_allocation() const {
return requires_contiguous_allocation_;
}
void set_requires_contiguous_allocation(bool requires_contiguous_allocation) {
requires_contiguous_allocation_ = requires_contiguous_allocation;
}
void AddUse(const HloUse& use, int64_t use_time) {
uses_.push_back({use, use_time, {}});
}
std::string ToString() const;
std::string ToShortString() const;
private:
const HloValue* value_;
HloPosition defining_position_;
int64_t size_;
bool requires_contiguous_allocation_;
std::vector<Use> uses_;
AllocationSequence allocation_sequence_;
};
struct AsynchronousCopy {
int64_t exclusive_start_time;
int64_t end_time;
float resource;
MemorySpace destination;
int64_t id;
std::tuple<int64_t, int64_t, float, MemorySpace, int64_t> AsTuple() const {
return std::make_tuple(exclusive_start_time, end_time, resource,
destination, id);
}
};
bool operator<(const AsynchronousCopy& a, const AsynchronousCopy& b);
bool operator==(const AsynchronousCopy& a, const AsynchronousCopy& b);
bool operator!=(const AsynchronousCopy& a, const AsynchronousCopy& b);
class AsynchronousCopyOrdering {
public:
AsynchronousCopyOrdering() = default;
void AddCopy(const AsynchronousCopy& copy);
void RemoveCopy(const AsynchronousCopy& copy);
bool ViolatesOrdering(int64_t exclusive_start_time, int64_t end_time) const;
private:
struct Interval {
int64_t exclusive_start_time;
int64_t end_time;
bool operator<(const Interval& other) const {
return (exclusive_start_time < other.exclusive_start_time &&
end_time <= other.end_time) ||
(exclusive_start_time <= other.exclusive_start_time &&
end_time < other.end_time);
}
};
std::map<Interval, std::set<AsynchronousCopy>> ranges_;
};
class AsynchronousCopyResource {
public:
struct ResourceSpec {
int64_t exclusive_start_time;
int64_t end_time;
float resource;
};
AsynchronousCopyResource() = default;
explicit AsynchronousCopyResource(absl::Span<const float> initial_resources)
: initial_resources_(initial_resources.begin(), initial_resources.end()),
delay_(initial_resources.size(), 0) {}
void AddCopy(const AsynchronousCopy& copy);
void RemoveCopy(const AsynchronousCopy& copy);
bool HasEnoughResource(int64_t exclusive_start_time, int64_t end_time,
float resource);
bool HasEnoughResourceMultiCheck(const std::vector<ResourceSpec>& specs);
std::vector<float> GetCurrentResources() const {
std::vector<float> current_resources(initial_resources_.begin(),
initial_resources_.end());
for (int i = 0; i < current_resources.size(); ++i) {
current_resources[i] -= std::min(current_resources[i], delay_[i]);
}
return current_resources;
}
std::string Dump(int64_t start_time, int64_t end_time,
MemorySpace memory_space_filter) const;
private:
bool ConsumeResource(
int64_t exclusive_start_time, int64_t end_time, float resource,
absl::flat_hash_map<int64_t, float>* delay_change_map = nullptr,
float resource_to_free = 0.0);
void RemoveCopy(std::list<AsynchronousCopy>::iterator& copy_it);
std::list<AsynchronousCopy> async_copies_;
#if defined(__GNUC__) || defined(__clang__)
absl::btree_map<int64_t, std::list<AsynchronousCopy>::iterator>
async_copy_time_map_;
#else
std::map<int64_t, std::list<AsynchronousCopy>::iterator> async_copy_time_map_;
#endif
std::vector<float> initial_resources_;
std::vector<float> delay_;
};
class MsaAlgorithm : public GlobalDecreasingSizeBestFitHeap<HloValue> {
public:
using HloPositionOrUse = std::variant<HloPosition, HloUse>;
MsaAlgorithm(AllocationSequence* allocations, const Options& options,
const HloAliasAnalysis& alias_analysis,
const HloLiveRange& hlo_live_range);
void AllocateCrossProgramPrefetchBuffer(
HloModule* module, const MsaBufferInterval& prefetch_candidate);
absl::StatusOr<HeapSimulator::Result<HloValue>> Finish() override;
protected:
std::vector<const MsaBufferInterval*> GetSortedColocatedIntervals(
const MsaBufferInterval& interval) const;
void CreateAllocationValues(
const MsaBufferInterval& buffer_interval,
std::vector<AllocationValue>& allocation_values) const;
virtual void CreateAllocationValuesFromColocatedIntervals(
absl::Span<const MsaBufferInterval* const> colocated_intervals,
std::vector<AllocationValue>& allocation_values);
void FindAliases(std::vector<AllocationValue>* allocation_values) const;
AllocationSequence* allocations() { return allocations_; }
const Options& options() const { return options_; }
const HloAliasAnalysis& alias_analysis() { return alias_analysis_; }
const HloLiveRange& hlo_live_range() { return hlo_live_range_; }
private:
struct RepackAllocationBlock : AllocationBlock {
Allocation* allocation;
};
struct AliasedOffset {
int64_t offset;
absl::flat_hash_set<const Allocation*> allocations;
};
struct AllocationRequest {
int64_t inclusive_start_time;
int64_t end_time;
int64_t latest_prefetch_time;
int64_t size;
bool prefer_no_copy_alternate_mem_allocation;
bool allow_no_copy_alternate_mem_allocation;
bool require_no_copy_alternate_mem_allocation;
bool allow_prefetch;
std::optional<int64_t> earliest_prefetch_time;
std::optional<int64_t> preferred_prefetch_time;
AliasedOffset* preferred_offset;
const AllocationValue::Use* use;
AllocationValue* allocation_value;
absl::Span<const int64_t> all_use_times;
};
struct RequiredMemoryAssignment {
MemorySpace memory_space;
int64_t time;
AliasedOffset* offset;
bool equals_ignoring_time(const RequiredMemoryAssignment& other) const {
return memory_space == other.memory_space && offset == other.offset;
}
bool operator==(const RequiredMemoryAssignment& other) const {
return memory_space == other.memory_space && time == other.time &&
offset == other.offset;
}
bool operator!=(const RequiredMemoryAssignment& other) const {
return !(*this == other);
}
};
struct LoopOptimizedAllocationInfo {
int64_t use_index;
int64_t loop_size;
const Allocation* loop_optimized_allocation;
};
struct PrefetchContext {
struct WorkingIntervals {
MsaBufferInterval full;
std::unique_ptr<SlicedBufferInterval> sliced;
};
struct SlicedSolution {
std::vector<SliceDecision> slice_decisions_sorted_by_start_time;
std::vector<std::pair<MsaBufferInterval, Chunk>>
slices_for_pending_chunks;
std::string prefetch_picker_debug_string;
};
struct UnslicedSolution {
Chunk chunk_candidate;
float prefetch_resource;
std::string prefetch_picker_debug_string;
};
WorkingIntervals& GetMutableWorkingIntervals(bool for_sliced_solution) {
if (for_sliced_solution) {
return sliced_solution_intervals;
}
return unsliced_solution_intervals;
}
const WorkingIntervals& GetWorkingIntervals(
bool for_sliced_solution) const {
if (for_sliced_solution) {
return sliced_solution_intervals;
}
return unsliced_solution_intervals;
}
const AllocationRequest* request;
Allocation* prev_allocation_in_default_mem;
int64_t exclusive_prefetch_start_time = -1;
int64_t prefetch_end_time = -1;
const Shape* full_shape;
int64_t extra_async_copy_limit = 0;
std::optional<int64_t> exclusive_out_of_mem_start = std::nullopt;
std::optional<SliceProposalCollection> slice_proposal_collection =
std::nullopt;
WorkingIntervals sliced_solution_intervals;
std::optional<SlicedSolution> sliced_solution;
WorkingIntervals unsliced_solution_intervals;
std::optional<UnslicedSolution> unsliced_solution;
};
enum class Result {
kSuccess = 0,
kFailOutOfMemory = 1,
kFailPrevAllocationNotInAlternateMem = 2,
kFailLiveRangeTooLong = 4,
kFailLiveRangeTooShort = 8,
kFailOutOfAsyncCopies = 16,
kFailViolatesAsyncCopyResource = 32,
kFailRequiresUncommit = 64,
kAllSlicesHaveTheSameStartTime = 128,
kFailConflictingPreferredOffsets = 256
};
static bool result_is(Result result, Result failure) {
return static_cast<int>(result) & static_cast<int>(failure);
}
static Result result_mark(Result failure, Result& result) {
result = static_cast<Result>(static_cast<int>(result) |
static_cast<int>(failure));
return result;
}
static bool result_requires_uncommit(Result result) {
return result_is(result, Result::kFailRequiresUncommit);
}
static bool result_failed_because_of_async_copy(Result result) {
return result_is(result, Result::kFailOutOfAsyncCopies) ||
result_is(result, Result::kFailViolatesAsyncCopyResource);
}
absl::Status OptimizeMemoryBoundLoop(int loop_start_idx, int loop_end_idx,
int loop_size);
void IdentifyAndOptimizeMemoryBoundLoops();
void AllocateReservedScopedAllocations();
AliasedOffset* GetAliasedOffset(const Allocation& allocation);
void CreateOrAddToAliasedOffset(const Allocation& allocation,
AliasedOffset* aliased_offset);
static Allocation* GetLiveAllocationAt(const AllocationSequence& allocations,
int64_t time);
bool IsUseAllowedInAlternateMemory(const AllocationValue& value,
const HloUse& use) const;
AliasedOffset* UpdatePreferredOffsetForUse(
const AllocationValue::Use& use, AliasedOffset* preferred_offset) const;
void UpdateAllocationRequirementForUseAliases(
const AllocationValue& allocation_value, const AllocationValue::Use& use,
int64_t use_time);
void MaybeCreateMirroredParentAllocationForWhileUse(
const AllocationValue& allocation_value, const AllocationValue::Use& use,
int64_t use_time, absl::Span<AllocationValue> allocation_values,
absl::flat_hash_map<const HloComputation*, AliasedOffset*>&
preferred_offset_for_computation);
AllocationRequest CreateAllocationRequest(
AllocationValue& allocation_value, const AllocationValue::Use& use,
const AllocationValue::Use* previous_use, AliasedOffset* preferred_offset,
int64_t definition_time, bool require_no_copy_alternate_mem_allocation,
const std::vector<int64_t>& all_use_times);
absl::StatusOr<Result> AllocateAllocationValues(
absl::Span<AllocationValue> allocation_values); | #include "tensorflow/core/graph/algorithm.h"
#include <string>
#include <vector>
#include "tensorflow/core/common_runtime/graph_constructor.h"
#include "tensorflow/core/common_runtime/graph_def_builder_util.h"
#include "tensorflow/core/graph/benchmark_testlib.h"
#include "tensorflow/core/graph/graph.h"
#include "tensorflow/core/graph/graph_def_builder.h"
#include "tensorflow/core/graph/subgraph.h"
#include "tensorflow/core/kernels/ops_util.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/lib/core/status_test_util.h"
#include "tensorflow/core/platform/test.h"
#include "tensorflow/core/platform/test_benchmark.h"
namespace tensorflow {
namespace {
REGISTER_OP("TestParams").Output("o: float");
REGISTER_OP("TestInput").Output("a: float").Output("b: float");
REGISTER_OP("TestMul").Input("a: float").Input("b: float").Output("o: float");
REGISTER_OP("TestUnary").Input("a: float").Output("o: float");
REGISTER_OP("TestBinary")
.Input("a: float")
.Input("b: float")
.Output("o: float");
bool ExpectBefore(const std::vector<std::pair<string, string>>& ordered_pairs,
const std::vector<Node*>& inputs, string* error) {
for (const std::pair<string, string>& pair : ordered_pairs) {
const string& before_node = pair.first;
const string& after_node = pair.second;
bool seen_before = false;
bool seen_both = false;
for (const Node* node : inputs) {
if (!seen_before && after_node == node->name()) {
*error = strings::StrCat("Saw ", after_node, " before ", before_node);
return false;
}
if (before_node == node->name()) {
seen_before = true;
} else if (after_node == node->name()) {
seen_both = seen_before;
break;
}
}
if (!seen_both) {
*error = strings::StrCat("didn't see either ", before_node, " or ",
after_node);
return false;
}
}
return true;
}
TEST(AlgorithmTest, ReversePostOrder) {
GraphDefBuilder b(GraphDefBuilder::kFailImmediately);
using namespace ::tensorflow::ops;
Node* w1 = SourceOp("TestParams", b.opts().WithName("W1"));
Node* w2 = SourceOp("TestParams", b.opts().WithName("W2"));
Node* input =
SourceOp("TestInput", b.opts().WithName("input").WithControlInput(w1));
Node* t1 = BinaryOp("TestMul", w1, {input, 1}, b.opts().WithName("t1"));
BinaryOp("TestMul", w1, {input, 1},
b.opts().WithName("t2").WithControlInput(t1));
BinaryOp("TestMul", w2, {input, 1}, b.opts().WithName("t3"));
Graph g(OpRegistry::Global());
TF_ASSERT_OK(GraphDefBuilderToGraph(b, &g));
std::vector<Node*> order;
GetReversePostOrder(g, &order);
std::vector<std::pair<string, string>> reverse_orders = {
{"W1", "input"}, {"W1", "t1"}, {"W1", "t2"}, {"W1", "t3"},
{"input", "t1"}, {"input", "t3"}, {"t1", "t2"}, {"W2", "t3"}};
string error;
EXPECT_TRUE(ExpectBefore(reverse_orders, order, &error)) << error;
reverse_orders = {{"input", "W1"}};
EXPECT_FALSE(ExpectBefore(reverse_orders, order, &error));
GetPostOrder(g, &order);
std::vector<std::pair<string, string>> orders = {
{"input", "W1"}, {"t1", "W1"}, {"t2", "W1"}, {"t3", "W1"},
{"t1", "input"}, {"t3", "input"}, {"t2", "t1"}, {"t3", "W2"}};
EXPECT_TRUE(ExpectBefore(orders, order, &error)) << error;
orders = {{"W1", "t3"}};
EXPECT_FALSE(ExpectBefore(orders, order, &error));
}
TEST(AlgorithmTest, ReversePostOrderStable) {
int64_t run_count = 100;
using namespace ::tensorflow::ops;
for (int64_t i = 0; i < run_count; ++i) {
GraphDefBuilder b(GraphDefBuilder::kFailImmediately);
string error;
Node* w1 = SourceOp("TestParams", b.opts().WithName("W1"));
Node* input =
SourceOp("TestInput", b.opts().WithName("input").WithControlInput(w1));
BinaryOp("TestMul", w1, {input, 1}, b.opts().WithName("t2"));
for (int64_t j = 0; j < i; ++j) {
BinaryOp("TestMul", w1, {input, 1},
b.opts().WithName(strings::StrCat("internal", j)));
}
BinaryOp("TestMul", w1, {input, 1}, b.opts().WithName("t3"));
Graph g(OpRegistry::Global());
TF_ASSERT_OK(GraphDefBuilderToGraph(b, &g));
std::vector<Node*> order;
GetReversePostOrder(g, &order, NodeComparatorName());
EXPECT_TRUE(ExpectBefore({{"t2", "t3"}}, order, &error));
}
}
TEST(AlgorithmTest, PostOrderWithEdgeFilter) {
GraphDefBuilder b(GraphDefBuilder::kFailImmediately);
Node* n0 = ops::SourceOp("TestParams", b.opts().WithName("n0"));
Node* n1 = ops::UnaryOp("TestUnary", n0, b.opts().WithName("n1"));
Node* n2 = ops::UnaryOp("TestUnary", n1, b.opts().WithName("n2"));
Node* n3 = ops::BinaryOp("TestBinary", n2, n0, b.opts().WithName("n3"));
Graph g(OpRegistry::Global());
TF_ASSERT_OK(GraphDefBuilderToGraph(b, &g));
g.AddEdge(g.FindNodeId(n3->id()), 0, g.FindNodeId(n1->id()), 1);
std::vector<Node*> post_order;
auto edge_filter = [&](const Edge& e) {
return !(e.src()->id() == n3->id() && e.dst()->id() == n1->id());
};
std::vector<Node*> expected_post_order = {
g.sink_node(), g.FindNodeId(n3->id()), g.FindNodeId(n2->id()),
g.FindNodeId(n1->id()), g.FindNodeId(n0->id()), g.source_node()};
std::vector<Node*> expected_reverse_post_order = expected_post_order;
std::reverse(expected_reverse_post_order.begin(),
expected_reverse_post_order.end());
GetPostOrder(g, &post_order, {},
edge_filter);
ASSERT_EQ(expected_post_order.size(), post_order.size());
for (int i = 0; i < post_order.size(); i++) {
CHECK_EQ(post_order[i], expected_post_order[i])
<< post_order[i]->name() << " vs. " << expected_post_order[i]->name();
}
std::vector<Node*> reverse_post_order;
GetReversePostOrder(g, &reverse_post_order, {},
edge_filter);
ASSERT_EQ(expected_reverse_post_order.size(), reverse_post_order.size());
for (int i = 0; i < reverse_post_order.size(); i++) {
CHECK_EQ(reverse_post_order[i], expected_reverse_post_order[i])
<< reverse_post_order[i]->name() << " vs. "
<< expected_reverse_post_order[i]->name();
}
}
void BM_PruneForReverseReachability(::testing::benchmark::State& state) {
const int num_nodes = state.range(0);
const int num_edges_per_node = state.range(1);
const GraphDef graph_def =
test::CreateGraphDef(num_nodes, num_edges_per_node);
const auto registry = OpRegistry::Global();
GraphConstructorOptions opts;
for (auto s : state) {
state.PauseTiming();
Graph graph(registry);
TF_CHECK_OK(ConvertGraphDefToGraph(opts, graph_def, &graph));
std::unordered_set<const Node*> visited;
visited.insert(graph.FindNodeId(graph.num_nodes() - 1));
state.ResumeTiming();
PruneForReverseReachability(&graph, std::move(visited));
}
}
BENCHMARK(BM_PruneForReverseReachability)->ArgPair(10, 2);
BENCHMARK(BM_PruneForReverseReachability)->ArgPair(1 << 6, 2);
BENCHMARK(BM_PruneForReverseReachability)->ArgPair(1 << 9, 2);
BENCHMARK(BM_PruneForReverseReachability)->ArgPair(1 << 12, 2);
BENCHMARK(BM_PruneForReverseReachability)->ArgPair(1 << 15, 2);
BENCHMARK(BM_PruneForReverseReachability)->ArgPair(10, 4);
BENCHMARK(BM_PruneForReverseReachability)->ArgPair(1 << 6, 4);
BENCHMARK(BM_PruneForReverseReachability)->ArgPair(1 << 9, 4);
BENCHMARK(BM_PruneForReverseReachability)->ArgPair(1 << 12, 4);
BENCHMARK(BM_PruneForReverseReachability)->ArgPair(1 << 15, 4);
BENCHMARK(BM_PruneForReverseReachability)->ArgPair(10, 8);
BENCHMARK(BM_PruneForReverseReachability)->ArgPair(1 << 6, 8);
BENCHMARK(BM_PruneForReverseReachability)->ArgPair(1 << 9, 8);
BENCHMARK(BM_PruneForReverseReachability)->ArgPair(1 << 12, 8);
BENCHMARK(BM_PruneForReverseReachability)->ArgPair(1 << 15, 8);
BENCHMARK(BM_PruneForReverseReachability)->ArgPair(10, 16);
BENCHMARK(BM_PruneForReverseReachability)->ArgPair(1 << 6, 16);
BENCHMARK(BM_PruneForReverseReachability)->ArgPair(1 << 9, 16);
BENCHMARK(BM_PruneForReverseReachability)->ArgPair(1 << 12, 16);
BENCHMARK(BM_PruneForReverseReachability)->ArgPair(1 << 15, 16);
}
} |
345 | #ifndef TENSORFLOW_LITE_TOOLS_VERSIONING_OP_SIGNATURE_H_
#define TENSORFLOW_LITE_TOOLS_VERSIONING_OP_SIGNATURE_H_
#include <string>
#include <vector>
#include "tensorflow/lite/core/c/c_api_types.h"
#include "tensorflow/lite/core/c/common.h"
#include "tensorflow/lite/schema/schema_generated.h"
namespace tflite {
typedef struct {
TfLiteType type;
std::vector<int32_t> dims;
bool is_const;
bool is_shape_dynamic;
} OpSignatureTensorSpec;
typedef struct {
BuiltinOperator op;
std::vector<OpSignatureTensorSpec> inputs;
std::vector<OpSignatureTensorSpec> outputs;
void* builtin_data;
int version;
const void* custom_initial_data;
std::string custom_name;
union {
struct {
bool is_per_channel_quantized;
bool is_grouped_convolution;
} conv_2d;
struct {
bool is_per_channel_quantized;
} depthwise_conv_2d;
struct {
bool sparse_weight;
bool is_per_channel_quantized;
} fully_connected;
struct {
float input1_scale;
float input2_scale;
float output_scale;
bool input_quantized;
} mul;
struct {
int32_t num_dims;
} strided_slice;
struct {
bool input_quantized;
} abs;
struct {
bool is_per_channel_quantized;
} dequantize;
struct {
bool is_per_channel_quantized;
} quantize;
struct {
bool input_quantized;
} add;
} ext_options;
} OpSignature;
OpSignature GetOpSignature(const OperatorCode* op_code, const Operator* op,
const SubGraph* subgraph, const Model* model);
OpSignature GetOpSignature(const TfLiteContext* context, const TfLiteNode* node,
const TfLiteRegistration* registration);
}
#endif
#include "tensorflow/lite/tools/versioning/op_signature.h"
#include <cstdlib>
#include "tensorflow/lite/core/api/flatbuffer_conversions.h"
#include "tensorflow/lite/kernels/internal/compatibility.h"
#include "tensorflow/lite/kernels/kernel_util.h"
#include "tensorflow/lite/schema/schema_utils.h"
#include "tensorflow/lite/stderr_reporter.h"
namespace tflite {
namespace {
class MallocDataAllocator : public BuiltinDataAllocator {
public:
void* Allocate(size_t size, size_t alignment_hint) override {
return malloc(size);
}
void Deallocate(void* data) override { free(data); }
};
inline int GetNumDims(const SubGraph* subgraph, const Operator* op, int idx) {
const flatbuffers::Vector<int32_t>* ret =
subgraph->tensors()->Get(op->inputs()->Get(idx))->shape();
if (ret) {
return ret->size();
} else {
return 0;
}
}
std::vector<OpSignatureTensorSpec> GetOpSignatureTensorSpecs(
const flatbuffers::Vector<int32_t>* tensors, const SubGraph* subgraph,
const Model* model) {
std::vector<OpSignatureTensorSpec> tensor_specs;
if (!tensors) {
return tensor_specs;
}
StderrReporter error_reporter;
for (int32_t i = 0; i < tensors->Length(); ++i) {
int32_t tensor_no = tensors->Get(i);
OpSignatureTensorSpec tensor_spec = {kTfLiteNoType};
if (tensor_no >= 0) {
if (subgraph->tensors() && tensor_no < subgraph->tensors()->Length()) {
auto* fb_tensor = subgraph->tensors()->Get(tensor_no);
ConvertTensorType(fb_tensor->type(), &tensor_spec.type,
&error_reporter);
auto buffer_idx = fb_tensor->buffer();
if (buffer_idx != 0 && buffer_idx < model->buffers()->Length()) {
auto* buffer = model->buffers()->Get(buffer_idx);
if (buffer->data() && buffer->data()->size() != 0) {
tensor_spec.is_const = true;
}
}
const flatbuffers::Vector<int32_t>* shape_vec = fb_tensor->shape();
if (shape_vec) {
for (int32_t j = 0; j < shape_vec->Length(); ++j) {
tensor_spec.dims.push_back(shape_vec->Get(j));
}
}
const flatbuffers::Vector<int32_t>* shape_signature_vec =
fb_tensor->shape_signature();
tensor_spec.is_shape_dynamic = false;
if (shape_signature_vec) {
for (int32_t j = 0; j < shape_signature_vec->Length(); ++j) {
if (shape_signature_vec->Get(j) == -1) {
tensor_spec.is_shape_dynamic = true;
break;
}
}
}
}
}
tensor_specs.push_back(tensor_spec);
}
return tensor_specs;
}
std::vector<OpSignatureTensorSpec> GetOpSignatureTensorSpecs(
TfLiteIntArray* tensors, const TfLiteContext* context,
const TfLiteNode* tflite_node) {
std::vector<OpSignatureTensorSpec> tensor_specs;
for (int32_t i = 0; i < tensors->size; ++i) {
int32_t tensor_no = tensors->data[i];
OpSignatureTensorSpec tensor_spec = {kTfLiteNoType};
if (tensor_no >= 0) {
const TfLiteTensor* tfl_tensor;
if (context->tensors != nullptr) {
tfl_tensor = &context->tensors[tensor_no];
} else {
tfl_tensor = context->GetTensor(context, tensor_no);
}
if (tfl_tensor != nullptr) {
tensor_spec.type = tfl_tensor->type;
tensor_spec.is_const = (tfl_tensor->allocation_type == kTfLiteMmapRo);
if (tfl_tensor->dims) {
for (int32_t j = 0; j < tfl_tensor->dims->size; ++j) {
tensor_spec.dims.push_back(tfl_tensor->dims->data[j]);
}
}
tensor_spec.is_shape_dynamic = HasUnspecifiedDimension(tfl_tensor);
}
}
tensor_specs.push_back(tensor_spec);
}
return tensor_specs;
}
}
OpSignature GetOpSignature(const OperatorCode* op_code, const Operator* op,
const SubGraph* subgraph, const Model* model) {
auto builtin_code = GetBuiltinCode(op_code);
OpSignature op_sig = {builtin_code};
std::memset(&op_sig.ext_options, 0, sizeof(op_sig.ext_options));
if (builtin_code != BuiltinOperator_CUSTOM) {
StderrReporter error_reporter;
MallocDataAllocator allocator;
ParseOpData(op, builtin_code, &error_reporter, &allocator,
&op_sig.builtin_data);
} else {
op_sig.custom_name = op_code->custom_code()->str();
}
switch (builtin_code) {
case BuiltinOperator_DEPTHWISE_CONV_2D: {
const Tensor* filter_tensor =
subgraph->tensors()->Get(op->inputs()->Get(1));
const QuantizationParameters* filter_quant =
filter_tensor->quantization();
int num_channels = filter_tensor->shape()->Get(3);
if (filter_quant && filter_quant->scale() &&
filter_quant->scale()->Length() &&
filter_quant->scale()->Length() == num_channels) {
op_sig.ext_options.depthwise_conv_2d.is_per_channel_quantized = true;
}
} break;
case BuiltinOperator_FULLY_CONNECTED: {
const Tensor* weight_tensor =
subgraph->tensors()->Get(op->inputs()->Get(1));
op_sig.ext_options.fully_connected.sparse_weight =
(weight_tensor->sparsity() != nullptr);
const QuantizationParameters* weight_quant =
weight_tensor->quantization();
if (weight_quant && weight_quant->scale() &&
weight_quant->scale()->size() && weight_tensor->shape() &&
weight_tensor->shape()->size()) {
op_sig.ext_options.fully_connected.is_per_channel_quantized =
weight_quant->scale()->size() > 1 &&
weight_quant->scale()->size() == weight_tensor->shape()->Get(0);
}
} break;
case BuiltinOperator_MUL: {
if (op->inputs()->Length() < 2 || op->outputs()->Length() < 1) {
break;
}
const Tensor* input1_tensor =
subgraph->tensors()->Get(op->inputs()->Get(0));
const Tensor* input2_tensor =
subgraph->tensors()->Get(op->inputs()->Get(1));
const Tensor* output_tensor =
subgraph->tensors()->Get(op->outputs()->Get(0));
const QuantizationParameters* input1_quant =
input1_tensor->quantization();
const QuantizationParameters* input2_qunt = input2_tensor->quantization();
const QuantizationParameters* output_quant =
output_tensor->quantization();
if (input1_quant && input1_quant->scale() &&
input1_quant->scale()->Length() && input2_qunt &&
input2_qunt->scale() && input2_qunt->scale()->Length() &&
output_quant && output_quant->scale() &&
output_quant->scale()->Length()) {
op_sig.ext_options.mul.input1_scale = input1_quant->scale()->Get(0);
op_sig.ext_options.mul.input2_scale = input2_qunt->scale()->Get(0);
op_sig.ext_options.mul.output_scale = output_quant->scale()->Get(0);
}
if (input1_quant || input2_qunt) {
op_sig.ext_options.mul.input_quantized = true;
}
} break;
case BuiltinOperator_CONV_2D: {
const Tensor* input_tensor =
subgraph->tensors()->Get(op->inputs()->Get(0));
const Tensor* filter_tensor =
subgraph->tensors()->Get(op->inputs()->Get(1));
const QuantizationParameters* filter_quant =
filter_tensor->quantization();
int num_filters = filter_tensor->shape()->Get(0);
if (filter_quant && filter_quant->scale() &&
filter_quant->scale()->Length() &&
filter_quant->scale()->Length() == num_filters) {
op_sig.ext_options.conv_2d.is_per_channel_quantized = true;
}
if (input_tensor->shape() && input_tensor->shape()->size()) {
int num_input_channels = input_tensor->shape()->Get(3);
int num_filter_input_channels = filter_tensor->shape()->Get(3);
op_sig.ext_options.conv_2d.is_grouped_convolution =
num_input_channels != num_filter_input_channels;
} else {
op_sig.ext_options.conv_2d.is_grouped_convolution = false;
}
} break;
case BuiltinOperator_STRIDED_SLICE: {
op_sig.ext_options.strided_slice.num_dims = GetNumDims(subgraph, op, 0);
} break;
case BuiltinOperator_ABS: {
if (subgraph->tensors()->Get(op->inputs()->Get(0))->quantization()) {
op_sig.ext_options.abs.input_quantized = true;
}
} break;
case BuiltinOperator_DEQUANTIZE: {
const Tensor* input_tensor =
subgraph->tensors()->Get(op->inputs()->Get(0));
const QuantizationParameters* input_quant = input_tensor->quantization();
if (input_quant && input_quant->scale() &&
input_quant->scale()->Length() > 1 &&
input_quant->scale()->Length() ==
input_tensor->shape()->Get(input_quant->quantized_dimension())) {
op_sig.ext_options.dequantize.is_per_channel_quantized = true;
}
} break;
case BuiltinOperator_QUANTIZE: {
const Tensor* output_tensor =
subgraph->tensors()->Get(op->outputs()->Get(0));
const QuantizationParameters* output_quant =
output_tensor->quantization();
if (output_quant && output_quant->scale() &&
output_quant->scale()->Length() > 1 &&
output_quant->scale()->Length() ==
output_tensor->shape()->Get(
output_quant->quantized_dimension())) {
op_sig.ext_options.quantize.is_per_channel_quantized = true;
}
} break;
case BuiltinOperator_ADD: {
if (subgraph->tensors()->Get(op->inputs()->Get(0))->quantization()) {
op_sig.ext_options.add.input_quantized = true;
}
} break;
default:
break;
}
op_sig.inputs = GetOpSignatureTensorSpecs(op->inputs(), subgraph, model);
op_sig.outputs = GetOpSignatureTensorSpecs(op->outputs(), subgraph, model);
op_sig.version = op_code->version();
return op_sig;
}
OpSignature GetOpSignature(const TfLiteContext* context, const TfLiteNode* node,
const TfLiteRegistration* registration) {
OpSignature op_sig = {
static_cast<BuiltinOperator>(registration->builtin_code)};
op_sig.builtin_data = node->builtin_data;
if (op_sig.op == BuiltinOperator_CUSTOM) {
op_sig.custom_name = registration->custom_name;
op_sig.custom_initial_data = node->custom_initial_data;
}
std::memset(&op_sig.ext_options, 0, sizeof(op_sig.ext_options));
op_sig.inputs = GetOpSignatureTensorSpecs(node->inputs, context, node);
op_sig.outputs = GetOpSignatureTensorSpecs(node->outputs, context, node);
op_sig.version = registration->version;
return op_sig;
}
} | #include "tensorflow/lite/tools/versioning/op_signature.h"
#include <cstring>
#include <memory>
#include <string>
#include <vector>
#include <gtest/gtest.h>
#include "tensorflow/core/platform/resource_loader.h"
#include "tensorflow/lite/builtin_ops.h"
#include "tensorflow/lite/core/model_builder.h"
namespace tflite {
class StubTfLiteContext : public TfLiteContext {
public:
StubTfLiteContext(const int builtin_code, const int op_version,
const int num_inputs)
: TfLiteContext({0}) {
exec_plan_ = TfLiteIntArrayCreate(3);
for (int i = 0; i < 3; ++i) exec_plan_->data[i] = i;
int tensor_no = 0;
std::memset(nodes_, 0, sizeof(nodes_));
std::memset(registrations_, 0, sizeof(registrations_));
nodes_[0].inputs = TfLiteIntArrayCreate(1);
nodes_[0].inputs->data[0] = tensor_no++;
nodes_[0].outputs = TfLiteIntArrayCreate(1);
nodes_[0].outputs->data[0] = tensor_no;
nodes_[0].builtin_data = nullptr;
nodes_[1].inputs = TfLiteIntArrayCreate(num_inputs);
for (int i = 0; i < num_inputs; i++) {
nodes_[1].inputs->data[i] = tensor_no++;
}
nodes_[1].outputs = TfLiteIntArrayCreate(1);
nodes_[1].outputs->data[0] = tensor_no;
nodes_[1].builtin_data = malloc(1024);
std::memset(nodes_[1].builtin_data, 0, 1024);
nodes_[2].inputs = TfLiteIntArrayCreate(1);
nodes_[2].inputs->data[0] = tensor_no++;
nodes_[2].outputs = TfLiteIntArrayCreate(1);
nodes_[2].outputs->data[0] = tensor_no++;
nodes_[2].builtin_data = nullptr;
tensors_.resize(tensor_no);
for (size_t i = 0; i < tensors_.size(); i++) {
std::memset(&tensors_[i], 0, sizeof(tensors_[i]));
tensors_[i].buffer_handle = kTfLiteNullBufferHandle;
tensors_[i].type = kTfLiteFloat32;
tensors_[i].dims = TfLiteIntArrayCreate(4);
for (int d = 0; d < 4; d++) {
tensors_[i].dims->data[d] = 1;
}
}
tensors = tensors_.data();
tensors_size = tensors_.size();
registrations_[0].builtin_code = kTfLiteBuiltinAdd;
registrations_[1].builtin_code = builtin_code;
registrations_[1].version = op_version;
registrations_[2].builtin_code = kTfLiteBuiltinAdd;
this->GetExecutionPlan = StubGetExecutionPlan;
this->GetNodeAndRegistration = StubGetNodeAndRegistration;
}
~StubTfLiteContext() {
for (auto& node : nodes_) {
TfLiteIntArrayFree(node.inputs);
TfLiteIntArrayFree(node.outputs);
if (node.builtin_data) {
free(node.builtin_data);
}
}
for (auto& tensor : tensors_) {
TfLiteIntArrayFree(tensor.dims);
}
TfLiteIntArrayFree(exec_plan_);
}
TfLiteIntArray* exec_plan() const { return exec_plan_; }
TfLiteNode* node() { return &nodes_[1]; }
TfLiteRegistration* registration() { return ®istrations_[1]; }
TfLiteNode* node(int node_index) { return &nodes_[node_index]; }
TfLiteRegistration* registration(int reg_index) {
return ®istrations_[reg_index];
}
TfLiteTensor* tensor(int tensor_index) { return &tensors_[tensor_index]; }
private:
static TfLiteStatus StubGetExecutionPlan(TfLiteContext* context,
TfLiteIntArray** execution_plan) {
StubTfLiteContext* stub = reinterpret_cast<StubTfLiteContext*>(context);
*execution_plan = stub->exec_plan();
return kTfLiteOk;
}
static TfLiteStatus StubGetNodeAndRegistration(
TfLiteContext* context, int node_index, TfLiteNode** node,
TfLiteRegistration** registration) {
StubTfLiteContext* stub = reinterpret_cast<StubTfLiteContext*>(context);
*node = stub->node(node_index);
*registration = stub->registration(node_index);
return kTfLiteOk;
}
TfLiteIntArray* exec_plan_;
TfLiteNode nodes_[3];
TfLiteRegistration registrations_[3];
std::vector<TfLiteTensor> tensors_;
};
TEST(GetOpSignature, FlatBufferModel) {
const std::string& full_path =
tensorflow::GetDataDependencyFilepath("tensorflow/lite/testdata/add.bin");
auto fb_model = FlatBufferModel::BuildFromFile(full_path.data());
ASSERT_TRUE(fb_model);
auto model = fb_model->GetModel();
auto subgraphs = model->subgraphs();
const SubGraph* subgraph = subgraphs->Get(0);
const Operator* op1 = subgraph->operators()->Get(0);
const OperatorCode* op_code1 =
model->operator_codes()->Get(op1->opcode_index());
OpSignature op_sig = GetOpSignature(op_code1, op1, subgraph, model);
EXPECT_EQ(op_sig.op, BuiltinOperator_ADD);
EXPECT_EQ(op_sig.inputs[0].type, kTfLiteFloat32);
EXPECT_EQ(op_sig.inputs[0].dims.size(), 4);
EXPECT_FALSE(op_sig.inputs[0].is_const);
EXPECT_FALSE(op_sig.inputs[0].is_shape_dynamic);
EXPECT_EQ(op_sig.outputs[0].type, kTfLiteFloat32);
EXPECT_FALSE(op_sig.outputs[0].is_const);
EXPECT_EQ(op_sig.outputs[0].dims.size(), 4);
EXPECT_FALSE(op_sig.outputs[0].is_shape_dynamic);
EXPECT_NE(op_sig.builtin_data, nullptr);
EXPECT_EQ(op_sig.version, 1);
free(op_sig.builtin_data);
const Operator* op2 = subgraph->operators()->Get(1);
const OperatorCode* op_code2 =
model->operator_codes()->Get(op2->opcode_index());
op_sig = GetOpSignature(op_code2, op2, subgraph, model);
EXPECT_EQ(op_sig.op, BuiltinOperator_ADD);
EXPECT_EQ(op_sig.inputs[0].type, kTfLiteFloat32);
EXPECT_EQ(op_sig.inputs[0].dims.size(), 4);
EXPECT_FALSE(op_sig.inputs[0].is_const);
EXPECT_FALSE(op_sig.inputs[0].is_shape_dynamic);
EXPECT_EQ(op_sig.outputs[0].type, kTfLiteFloat32);
EXPECT_FALSE(op_sig.outputs[0].is_const);
EXPECT_EQ(op_sig.outputs[0].dims.size(), 4);
EXPECT_FALSE(op_sig.outputs[0].is_shape_dynamic);
EXPECT_NE(op_sig.builtin_data, nullptr);
EXPECT_EQ(op_sig.version, 1);
free(op_sig.builtin_data);
const std::string& full_path3 = tensorflow::GetDataDependencyFilepath(
"tensorflow/lite/testdata/multi_signatures.bin");
auto fb_model3 = FlatBufferModel::BuildFromFile(full_path3.data());
ASSERT_TRUE(fb_model3);
auto model3 = fb_model3->GetModel();
auto subgraphs3 = model3->subgraphs();
const SubGraph* subgraph3 = subgraphs3->Get(0);
const Operator* op3 = subgraph3->operators()->Get(0);
const OperatorCode* op_code3 =
model3->operator_codes()->Get(op3->opcode_index());
op_sig = GetOpSignature(op_code3, op3, subgraph3, model3);
EXPECT_EQ(op_sig.op, BuiltinOperator_ADD);
EXPECT_EQ(op_sig.inputs[0].type, kTfLiteFloat32);
EXPECT_EQ(op_sig.inputs[0].dims.size(), 1);
EXPECT_FALSE(op_sig.inputs[0].is_const);
EXPECT_TRUE(op_sig.inputs[0].is_shape_dynamic);
EXPECT_EQ(op_sig.outputs[0].type, kTfLiteFloat32);
EXPECT_FALSE(op_sig.outputs[0].is_const);
EXPECT_EQ(op_sig.outputs[0].dims.size(), 1);
EXPECT_TRUE(op_sig.outputs[0].is_shape_dynamic);
EXPECT_NE(op_sig.builtin_data, nullptr);
EXPECT_EQ(op_sig.version, 1);
free(op_sig.builtin_data);
}
TEST(GetOpSignature, TfLiteContext) {
auto context = std::make_unique<StubTfLiteContext>(kTfLiteBuiltinAdd,
1,
4);
OpSignature op_sig =
GetOpSignature(context.get(), context->node(), context->registration());
EXPECT_EQ(op_sig.op, BuiltinOperator_ADD);
EXPECT_EQ(op_sig.inputs[0].type, kTfLiteFloat32);
EXPECT_EQ(op_sig.inputs[0].dims.size(), 4);
EXPECT_FALSE(op_sig.inputs[0].is_const);
EXPECT_FALSE(op_sig.inputs[0].is_shape_dynamic);
EXPECT_EQ(op_sig.outputs[0].type, kTfLiteFloat32);
EXPECT_FALSE(op_sig.outputs[0].is_const);
EXPECT_EQ(op_sig.outputs[0].dims.size(), 4);
EXPECT_FALSE(op_sig.outputs[0].is_shape_dynamic);
EXPECT_NE(op_sig.builtin_data, nullptr);
EXPECT_EQ(op_sig.version, 1);
}
} |
346 | #ifndef AROLLA_CODEGEN_OPERATOR_PACKAGE_LOAD_OPERATOR_PACKAGE_H_
#define AROLLA_CODEGEN_OPERATOR_PACKAGE_LOAD_OPERATOR_PACKAGE_H_
#include "absl/status/status.h"
#include "absl/strings/string_view.h"
#include "arolla/codegen/operator_package/operator_package.pb.h"
namespace arolla::operator_package {
absl::Status ParseEmbeddedOperatorPackage(
absl::string_view embedded_zlib_data,
OperatorPackageProto* operator_package_proto);
absl::Status LoadOperatorPackage(
const OperatorPackageProto& operator_package_proto);
}
#endif
#include "arolla/codegen/operator_package/load_operator_package.h"
#include <set>
#include "absl/status/status.h"
#include "absl/strings/str_format.h"
#include "absl/strings/str_join.h"
#include "absl/strings/string_view.h"
#include "google/protobuf/io/gzip_stream.h"
#include "google/protobuf/io/zero_copy_stream_impl_lite.h"
#include "arolla/codegen/operator_package/operator_package.pb.h"
#include "arolla/expr/expr_operator.h"
#include "arolla/expr/registered_expr_operator.h"
#include "arolla/qtype/qtype_traits.h"
#include "arolla/serialization/decode.h"
#include "arolla/util/status_macros_backport.h"
namespace arolla::operator_package {
using ::arolla::expr::ExprOperatorPtr;
using ::arolla::expr::ExprOperatorRegistry;
absl::Status ParseEmbeddedOperatorPackage(
absl::string_view embedded_zlib_data,
OperatorPackageProto* operator_package_proto) {
::google::protobuf::io::ArrayInputStream input_stream(embedded_zlib_data.data(),
embedded_zlib_data.size());
::google::protobuf::io::GzipInputStream gzip_input_stream(&input_stream);
if (!operator_package_proto->ParseFromZeroCopyStream(&gzip_input_stream) ||
gzip_input_stream.ZlibErrorMessage() != nullptr) {
return absl::InternalError("unable to parse an embedded operator package");
}
return absl::OkStatus();
}
absl::Status LoadOperatorPackage(
const OperatorPackageProto& operator_package_proto) {
if (operator_package_proto.version() != 1) {
return absl::InvalidArgumentError(
absl::StrFormat("expected operator_package_proto.version=1, got %d",
operator_package_proto.version()));
}
auto* const operator_registry = ExprOperatorRegistry::GetInstance();
auto check_registered_operator_presence = [&](absl::string_view name) {
return operator_registry->LookupOperatorOrNull(name) != nullptr;
};
std::set<absl::string_view> missing_operators;
for (absl::string_view operator_name :
operator_package_proto.required_registered_operators()) {
if (!check_registered_operator_presence(operator_name)) {
missing_operators.insert(operator_name);
}
}
if (!missing_operators.empty()) {
return absl::FailedPreconditionError(
"missing dependencies: M." + absl::StrJoin(missing_operators, ", M."));
}
std::set<absl::string_view> already_registered_operators;
for (const auto& operator_proto : operator_package_proto.operators()) {
if (check_registered_operator_presence(
operator_proto.registration_name())) {
already_registered_operators.insert(operator_proto.registration_name());
}
}
if (!already_registered_operators.empty()) {
return absl::FailedPreconditionError(
"already present in the registry: M." +
absl::StrJoin(already_registered_operators, ", M."));
}
for (int i = 0; i < operator_package_proto.operators_size(); ++i) {
const auto& operator_proto = operator_package_proto.operators(i);
ASSIGN_OR_RETURN(auto decode_result,
serialization::Decode(operator_proto.implementation()),
_ << "operators[" << i << "].registration_name="
<< operator_proto.registration_name());
if (decode_result.values.size() != 1 || !decode_result.exprs.empty()) {
return absl::InvalidArgumentError(absl::StrFormat(
"expected to get a value, got %d values and %d exprs; "
"operators[%d].registration_name=%s",
decode_result.values.size(), decode_result.exprs.size(), i,
operator_proto.registration_name()));
}
const auto& qvalue = decode_result.values[0];
if (qvalue.GetType() != GetQType<ExprOperatorPtr>()) {
return absl::InvalidArgumentError(absl::StrFormat(
"expected to get %s, got %s; operators[%d].registration_name=%s",
GetQType<ExprOperatorPtr>()->name(), qvalue.GetType()->name(), i,
operator_proto.registration_name()));
}
RETURN_IF_ERROR(operator_registry
->Register(operator_proto.registration_name(),
qvalue.UnsafeAs<ExprOperatorPtr>())
.status());
}
return absl::OkStatus();
}
} | #include "arolla/codegen/operator_package/load_operator_package.h"
#include <cstdint>
#include <string>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "arolla/codegen/operator_package/operator_package.pb.h"
#include "arolla/expr/expr.h"
#include "arolla/expr/expr_operator.h"
#include "arolla/expr/lambda_expr_operator.h"
#include "arolla/expr/registered_expr_operator.h"
#include "arolla/qtype/base_types.h"
#include "arolla/qtype/typed_value.h"
#include "arolla/serialization/encode.h"
#include "arolla/util/init_arolla.h"
#include "arolla/util/testing/status_matchers_backport.h"
namespace arolla::operator_package {
namespace {
using ::arolla::expr::ExprOperatorPtr;
using ::arolla::expr::LookupOperator;
using ::arolla::expr::Placeholder;
using ::arolla::testing::StatusIs;
using ::testing::HasSubstr;
class ParseEmbeddedOperatorPackageTest : public ::testing::Test {
protected:
void SetUp() override { ASSERT_OK(InitArolla()); }
};
TEST_F(ParseEmbeddedOperatorPackageTest, TrivialOperatorPackage) {
OperatorPackageProto operator_package_proto;
ASSERT_OK(ParseEmbeddedOperatorPackage("x\x9c\xe3`\x04\x00\x00\x13\x00\n",
&operator_package_proto));
EXPECT_THAT(operator_package_proto.version(), 1);
}
TEST_F(ParseEmbeddedOperatorPackageTest, ZLibError) {
OperatorPackageProto operator_package_proto;
EXPECT_THAT(ParseEmbeddedOperatorPackage("abc", &operator_package_proto),
StatusIs(absl::StatusCode::kInternal,
"unable to parse an embedded operator package"));
}
TEST_F(ParseEmbeddedOperatorPackageTest, ProtoError) {
OperatorPackageProto operator_package_proto;
EXPECT_THAT(
ParseEmbeddedOperatorPackage("x\xda\xe3\x98\x06\x00\x00\xa8\x00\x9f",
&operator_package_proto),
StatusIs(absl::StatusCode::kInternal,
"unable to parse an embedded operator package"));
}
class LoadOperatorPackageTest : public ::testing::Test {
protected:
void SetUp() override { ASSERT_OK(InitArolla()); }
template <typename Proto>
static absl::StatusOr<std::string> SerializeToString(const Proto& proto) {
if (std::string result; proto.SerializeToString(&result)) {
return result;
}
return absl::InvalidArgumentError("unable to serialize a proto message");
}
};
TEST_F(LoadOperatorPackageTest, Registration) {
ASSERT_OK_AND_ASSIGN(ExprOperatorPtr op,
MakeLambdaOperator(Placeholder("x")));
OperatorPackageProto operator_package_proto;
operator_package_proto.set_version(1);
auto* operator_proto = operator_package_proto.add_operators();
operator_proto->set_registration_name("foo.bar.registration");
ASSERT_OK_AND_ASSIGN(*operator_proto->mutable_implementation(),
serialization::Encode({TypedValue::FromValue(op)}, {}));
EXPECT_OK(LoadOperatorPackage(operator_package_proto));
ASSERT_OK_AND_ASSIGN(auto reg_op, LookupOperator("foo.bar.registration"));
ASSERT_OK_AND_ASSIGN(auto op_impl, reg_op->GetImplementation());
ASSERT_NE(op_impl, nullptr);
EXPECT_EQ(op_impl->fingerprint(), op->fingerprint());
}
TEST_F(LoadOperatorPackageTest, ErrorAlreadyRegistered) {
ASSERT_OK_AND_ASSIGN(ExprOperatorPtr op,
MakeLambdaOperator(Placeholder("x")));
OperatorPackageProto operator_package_proto;
operator_package_proto.set_version(1);
auto* operator_proto = operator_package_proto.add_operators();
operator_proto->set_registration_name("foo.bar.already_registered");
ASSERT_OK_AND_ASSIGN(*operator_proto->mutable_implementation(),
serialization::Encode({TypedValue::FromValue(op)}, {}));
EXPECT_OK(LoadOperatorPackage(operator_package_proto));
EXPECT_THAT(LoadOperatorPackage(operator_package_proto),
StatusIs(absl::StatusCode::kFailedPrecondition,
"already present in the registry: "
"M.foo.bar.already_registered"));
}
TEST_F(LoadOperatorPackageTest, ErrorUnexpectedFormatVersion) {
OperatorPackageProto operator_package_proto;
EXPECT_THAT(LoadOperatorPackage(operator_package_proto),
StatusIs(absl::StatusCode::kInvalidArgument,
"expected operator_package_proto.version=1, got 0"));
}
TEST_F(LoadOperatorPackageTest, ErrorMissingDependency) {
OperatorPackageProto operator_package_proto;
operator_package_proto.set_version(1);
operator_package_proto.add_required_registered_operators("foo.bar");
operator_package_proto.add_required_registered_operators("far.boo");
EXPECT_THAT(LoadOperatorPackage(operator_package_proto),
StatusIs(absl::StatusCode::kFailedPrecondition,
"missing dependencies: M.far.boo, M.foo.bar"));
}
TEST_F(LoadOperatorPackageTest, ErrorBrokenOperatorImplementation) {
OperatorPackageProto operator_package_proto;
operator_package_proto.set_version(1);
operator_package_proto.add_operators()->set_registration_name("foo.bar");
EXPECT_THAT(LoadOperatorPackage(operator_package_proto),
StatusIs(absl::StatusCode::kInvalidArgument,
HasSubstr("; operators[0].registration_name=foo.bar")));
}
TEST_F(LoadOperatorPackageTest, ErrorNoValueInOperatorImplementation) {
OperatorPackageProto operator_package_proto;
operator_package_proto.set_version(1);
auto* operator_proto = operator_package_proto.add_operators();
operator_proto->set_registration_name("foo.bar");
ASSERT_OK_AND_ASSIGN(*operator_proto->mutable_implementation(),
serialization::Encode({}, {}));
EXPECT_THAT(
LoadOperatorPackage(operator_package_proto),
StatusIs(absl::StatusCode::kInvalidArgument,
HasSubstr("expected to get a value, got 0 values and 0 exprs; "
"operators[0].registration_name=foo.bar")));
}
TEST_F(LoadOperatorPackageTest, ErrorUnexpectedValueInOperatorImplementation) {
OperatorPackageProto operator_package_proto;
operator_package_proto.set_version(1);
auto* operator_proto = operator_package_proto.add_operators();
operator_proto->set_registration_name("foo.bar");
ASSERT_OK_AND_ASSIGN(
*operator_proto->mutable_implementation(),
serialization::Encode({TypedValue::FromValue<int64_t>(0)}, {}));
EXPECT_THAT(LoadOperatorPackage(operator_package_proto),
StatusIs(absl::StatusCode::kInvalidArgument,
HasSubstr("expected to get EXPR_OPERATOR, got INT64; "
"operators[0].registration_name=foo.bar")));
}
}
} |
347 | #ifndef ABSL_LOG_LOG_SINK_H_
#define ABSL_LOG_LOG_SINK_H_
#include "absl/base/config.h"
#include "absl/log/log_entry.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
class LogSink {
public:
virtual ~LogSink() = default;
virtual void Send(const absl::LogEntry& entry) = 0;
virtual void Flush() {}
protected:
LogSink() = default;
LogSink(const LogSink&) = default;
LogSink& operator=(const LogSink&) = default;
private:
virtual void KeyFunction() const final;
};
ABSL_NAMESPACE_END
}
#endif
#include "absl/log/log_sink.h"
#include "absl/base/config.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
void LogSink::KeyFunction() const {}
ABSL_NAMESPACE_END
} | #include "absl/log/log_sink.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "absl/base/attributes.h"
#include "absl/log/internal/test_actions.h"
#include "absl/log/internal/test_helpers.h"
#include "absl/log/internal/test_matchers.h"
#include "absl/log/log.h"
#include "absl/log/log_sink_registry.h"
#include "absl/log/scoped_mock_log.h"
#include "absl/strings/string_view.h"
namespace {
using ::absl::log_internal::DeathTestExpectedLogging;
using ::absl::log_internal::DeathTestUnexpectedLogging;
using ::absl::log_internal::DeathTestValidateExpectations;
using ::absl::log_internal::DiedOfFatal;
using ::testing::_;
using ::testing::AnyNumber;
using ::testing::HasSubstr;
using ::testing::InSequence;
auto* test_env ABSL_ATTRIBUTE_UNUSED = ::testing::AddGlobalTestEnvironment(
new absl::log_internal::LogTestEnvironment);
TEST(LogSinkRegistryTest, AddLogSink) {
absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected);
InSequence s;
EXPECT_CALL(test_sink, Log(_, _, "hello world")).Times(0);
EXPECT_CALL(test_sink, Log(absl::LogSeverity::kInfo, __FILE__, "Test : 42"));
EXPECT_CALL(test_sink,
Log(absl::LogSeverity::kWarning, __FILE__, "Danger ahead"));
EXPECT_CALL(test_sink,
Log(absl::LogSeverity::kError, __FILE__, "This is an error"));
LOG(INFO) << "hello world";
test_sink.StartCapturingLogs();
LOG(INFO) << "Test : " << 42;
LOG(WARNING) << "Danger" << ' ' << "ahead";
LOG(ERROR) << "This is an error";
test_sink.StopCapturingLogs();
LOG(INFO) << "Goodby world";
}
TEST(LogSinkRegistryTest, MultipleLogSinks) {
absl::ScopedMockLog test_sink1(absl::MockLogDefault::kDisallowUnexpected);
absl::ScopedMockLog test_sink2(absl::MockLogDefault::kDisallowUnexpected);
::testing::InSequence seq;
EXPECT_CALL(test_sink1, Log(absl::LogSeverity::kInfo, _, "First")).Times(1);
EXPECT_CALL(test_sink2, Log(absl::LogSeverity::kInfo, _, "First")).Times(0);
EXPECT_CALL(test_sink1, Log(absl::LogSeverity::kInfo, _, "Second")).Times(1);
EXPECT_CALL(test_sink2, Log(absl::LogSeverity::kInfo, _, "Second")).Times(1);
EXPECT_CALL(test_sink1, Log(absl::LogSeverity::kInfo, _, "Third")).Times(0);
EXPECT_CALL(test_sink2, Log(absl::LogSeverity::kInfo, _, "Third")).Times(1);
LOG(INFO) << "Before first";
test_sink1.StartCapturingLogs();
LOG(INFO) << "First";
test_sink2.StartCapturingLogs();
LOG(INFO) << "Second";
test_sink1.StopCapturingLogs();
LOG(INFO) << "Third";
test_sink2.StopCapturingLogs();
LOG(INFO) << "Fourth";
}
TEST(LogSinkRegistrationDeathTest, DuplicateSinkRegistration) {
ASSERT_DEATH_IF_SUPPORTED(
{
absl::ScopedMockLog sink;
sink.StartCapturingLogs();
absl::AddLogSink(&sink.UseAsLocalSink());
},
HasSubstr("Duplicate log sinks"));
}
TEST(LogSinkRegistrationDeathTest, MismatchSinkRemoval) {
ASSERT_DEATH_IF_SUPPORTED(
{
absl::ScopedMockLog sink;
absl::RemoveLogSink(&sink.UseAsLocalSink());
},
HasSubstr("Mismatched log sink"));
}
TEST(LogSinkTest, FlushSinks) {
absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected);
EXPECT_CALL(test_sink, Flush()).Times(2);
test_sink.StartCapturingLogs();
absl::FlushLogSinks();
absl::FlushLogSinks();
}
TEST(LogSinkDeathTest, DeathInSend) {
class FatalSendSink : public absl::LogSink {
public:
void Send(const absl::LogEntry&) override { LOG(FATAL) << "goodbye world"; }
};
FatalSendSink sink;
EXPECT_EXIT({ LOG(INFO).ToSinkAlso(&sink) << "hello world"; }, DiedOfFatal,
_);
}
TEST(LogSinkTest, ToSinkAlso) {
absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected);
absl::ScopedMockLog another_sink(absl::MockLogDefault::kDisallowUnexpected);
EXPECT_CALL(test_sink, Log(_, _, "hello world"));
EXPECT_CALL(another_sink, Log(_, _, "hello world"));
test_sink.StartCapturingLogs();
LOG(INFO).ToSinkAlso(&another_sink.UseAsLocalSink()) << "hello world";
}
TEST(LogSinkTest, ToSinkOnly) {
absl::ScopedMockLog another_sink(absl::MockLogDefault::kDisallowUnexpected);
EXPECT_CALL(another_sink, Log(_, _, "hello world"));
LOG(INFO).ToSinkOnly(&another_sink.UseAsLocalSink()) << "hello world";
}
TEST(LogSinkTest, ToManySinks) {
absl::ScopedMockLog sink1(absl::MockLogDefault::kDisallowUnexpected);
absl::ScopedMockLog sink2(absl::MockLogDefault::kDisallowUnexpected);
absl::ScopedMockLog sink3(absl::MockLogDefault::kDisallowUnexpected);
absl::ScopedMockLog sink4(absl::MockLogDefault::kDisallowUnexpected);
absl::ScopedMockLog sink5(absl::MockLogDefault::kDisallowUnexpected);
EXPECT_CALL(sink3, Log(_, _, "hello world"));
EXPECT_CALL(sink4, Log(_, _, "hello world"));
EXPECT_CALL(sink5, Log(_, _, "hello world"));
LOG(INFO)
.ToSinkAlso(&sink1.UseAsLocalSink())
.ToSinkAlso(&sink2.UseAsLocalSink())
.ToSinkOnly(&sink3.UseAsLocalSink())
.ToSinkAlso(&sink4.UseAsLocalSink())
.ToSinkAlso(&sink5.UseAsLocalSink())
<< "hello world";
}
class ReentrancyTest : public ::testing::Test {
protected:
ReentrancyTest() = default;
enum class LogMode : int { kNormal, kToSinkAlso, kToSinkOnly };
class ReentrantSendLogSink : public absl::LogSink {
public:
explicit ReentrantSendLogSink(absl::LogSeverity severity,
absl::LogSink* sink, LogMode mode)
: severity_(severity), sink_(sink), mode_(mode) {}
explicit ReentrantSendLogSink(absl::LogSeverity severity)
: ReentrantSendLogSink(severity, nullptr, LogMode::kNormal) {}
void Send(const absl::LogEntry&) override {
switch (mode_) {
case LogMode::kNormal:
LOG(LEVEL(severity_)) << "The log is coming from *inside the sink*.";
break;
case LogMode::kToSinkAlso:
LOG(LEVEL(severity_)).ToSinkAlso(sink_)
<< "The log is coming from *inside the sink*.";
break;
case LogMode::kToSinkOnly:
LOG(LEVEL(severity_)).ToSinkOnly(sink_)
<< "The log is coming from *inside the sink*.";
break;
default:
LOG(FATAL) << "Invalid mode " << static_cast<int>(mode_);
}
}
private:
absl::LogSeverity severity_;
absl::LogSink* sink_;
LogMode mode_;
};
static absl::string_view LogAndReturn(absl::LogSeverity severity,
absl::string_view to_log,
absl::string_view to_return) {
LOG(LEVEL(severity)) << to_log;
return to_return;
}
};
TEST_F(ReentrancyTest, LogFunctionThatLogs) {
absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected);
InSequence seq;
EXPECT_CALL(test_sink, Log(absl::LogSeverity::kInfo, _, "hello"));
EXPECT_CALL(test_sink, Log(absl::LogSeverity::kInfo, _, "world"));
EXPECT_CALL(test_sink, Log(absl::LogSeverity::kWarning, _, "danger"));
EXPECT_CALL(test_sink, Log(absl::LogSeverity::kInfo, _, "here"));
test_sink.StartCapturingLogs();
LOG(INFO) << LogAndReturn(absl::LogSeverity::kInfo, "hello", "world");
LOG(INFO) << LogAndReturn(absl::LogSeverity::kWarning, "danger", "here");
}
TEST_F(ReentrancyTest, RegisteredLogSinkThatLogsInSend) {
absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected);
ReentrantSendLogSink renentrant_sink(absl::LogSeverity::kInfo);
EXPECT_CALL(test_sink, Log(_, _, "hello world"));
test_sink.StartCapturingLogs();
absl::AddLogSink(&renentrant_sink);
LOG(INFO) << "hello world";
absl::RemoveLogSink(&renentrant_sink);
}
TEST_F(ReentrancyTest, AlsoLogSinkThatLogsInSend) {
absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected);
ReentrantSendLogSink reentrant_sink(absl::LogSeverity::kInfo);
EXPECT_CALL(test_sink, Log(_, _, "hello world"));
EXPECT_CALL(test_sink,
Log(_, _, "The log is coming from *inside the sink*."));
test_sink.StartCapturingLogs();
LOG(INFO).ToSinkAlso(&reentrant_sink) << "hello world";
}
TEST_F(ReentrancyTest, RegisteredAlsoLogSinkThatLogsInSend) {
absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected);
ReentrantSendLogSink reentrant_sink(absl::LogSeverity::kInfo);
EXPECT_CALL(test_sink, Log(_, _, "hello world"));
EXPECT_CALL(test_sink,
Log(_, _, "The log is coming from *inside the sink*."));
test_sink.StartCapturingLogs();
absl::AddLogSink(&reentrant_sink);
LOG(INFO).ToSinkAlso(&reentrant_sink) << "hello world";
absl::RemoveLogSink(&reentrant_sink);
}
TEST_F(ReentrancyTest, OnlyLogSinkThatLogsInSend) {
absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected);
ReentrantSendLogSink reentrant_sink(absl::LogSeverity::kInfo);
EXPECT_CALL(test_sink,
Log(_, _, "The log is coming from *inside the sink*."));
test_sink.StartCapturingLogs();
LOG(INFO).ToSinkOnly(&reentrant_sink) << "hello world";
}
TEST_F(ReentrancyTest, RegisteredOnlyLogSinkThatLogsInSend) {
absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected);
ReentrantSendLogSink reentrant_sink(absl::LogSeverity::kInfo);
EXPECT_CALL(test_sink,
Log(_, _, "The log is coming from *inside the sink*."));
test_sink.StartCapturingLogs();
absl::AddLogSink(&reentrant_sink);
LOG(INFO).ToSinkOnly(&reentrant_sink) << "hello world";
absl::RemoveLogSink(&reentrant_sink);
}
using ReentrancyDeathTest = ReentrancyTest;
TEST_F(ReentrancyDeathTest, LogFunctionThatLogsFatal) {
EXPECT_EXIT(
{
absl::ScopedMockLog test_sink;
EXPECT_CALL(test_sink, Log)
.Times(AnyNumber())
.WillRepeatedly(DeathTestUnexpectedLogging());
EXPECT_CALL(test_sink, Log(_, _, "hello"))
.WillOnce(DeathTestExpectedLogging());
test_sink.StartCapturingLogs();
LOG(INFO) << LogAndReturn(absl::LogSeverity::kFatal, "hello", "world");
},
DiedOfFatal, DeathTestValidateExpectations());
}
TEST_F(ReentrancyDeathTest, RegisteredLogSinkThatLogsFatalInSend) {
EXPECT_EXIT(
{
absl::ScopedMockLog test_sink;
ReentrantSendLogSink reentrant_sink(absl::LogSeverity::kFatal);
EXPECT_CALL(test_sink, Log)
.Times(AnyNumber())
.WillRepeatedly(DeathTestUnexpectedLogging());
EXPECT_CALL(test_sink, Log(_, _, "hello world"))
.WillOnce(DeathTestExpectedLogging());
test_sink.StartCapturingLogs();
absl::AddLogSink(&reentrant_sink);
LOG(INFO) << "hello world";
},
DiedOfFatal, DeathTestValidateExpectations());
}
TEST_F(ReentrancyDeathTest, AlsoLogSinkThatLogsFatalInSend) {
EXPECT_EXIT(
{
absl::ScopedMockLog test_sink;
ReentrantSendLogSink reentrant_sink(absl::LogSeverity::kFatal);
EXPECT_CALL(test_sink, Log)
.Times(AnyNumber())
.WillRepeatedly(DeathTestUnexpectedLogging());
EXPECT_CALL(test_sink, Log(_, _, "hello world"))
.WillOnce(DeathTestExpectedLogging());
EXPECT_CALL(test_sink,
Log(_, _, "The log is coming from *inside the sink*."))
.WillOnce(DeathTestExpectedLogging());
test_sink.StartCapturingLogs();
LOG(INFO).ToSinkAlso(&reentrant_sink) << "hello world";
},
DiedOfFatal, DeathTestValidateExpectations());
}
TEST_F(ReentrancyDeathTest, RegisteredAlsoLogSinkThatLogsFatalInSend) {
EXPECT_EXIT(
{
absl::ScopedMockLog test_sink;
ReentrantSendLogSink reentrant_sink(absl::LogSeverity::kFatal);
EXPECT_CALL(test_sink, Log)
.Times(AnyNumber())
.WillRepeatedly(DeathTestUnexpectedLogging());
EXPECT_CALL(test_sink, Log(_, _, "hello world"))
.WillOnce(DeathTestExpectedLogging());
EXPECT_CALL(test_sink,
Log(_, _, "The log is coming from *inside the sink*."))
.WillOnce(DeathTestExpectedLogging());
test_sink.StartCapturingLogs();
absl::AddLogSink(&reentrant_sink);
LOG(INFO).ToSinkAlso(&reentrant_sink) << "hello world";
},
DiedOfFatal, DeathTestValidateExpectations());
}
TEST_F(ReentrancyDeathTest, OnlyLogSinkThatLogsFatalInSend) {
EXPECT_EXIT(
{
absl::ScopedMockLog test_sink;
ReentrantSendLogSink reentrant_sink(absl::LogSeverity::kFatal);
EXPECT_CALL(test_sink, Log)
.Times(AnyNumber())
.WillRepeatedly(DeathTestUnexpectedLogging());
EXPECT_CALL(test_sink,
Log(_, _, "The log is coming from *inside the sink*."))
.WillOnce(DeathTestExpectedLogging());
test_sink.StartCapturingLogs();
LOG(INFO).ToSinkOnly(&reentrant_sink) << "hello world";
},
DiedOfFatal, DeathTestValidateExpectations());
}
TEST_F(ReentrancyDeathTest, RegisteredOnlyLogSinkThatLogsFatalInSend) {
EXPECT_EXIT(
{
absl::ScopedMockLog test_sink;
ReentrantSendLogSink reentrant_sink(absl::LogSeverity::kFatal);
EXPECT_CALL(test_sink, Log)
.Times(AnyNumber())
.WillRepeatedly(DeathTestUnexpectedLogging());
EXPECT_CALL(test_sink,
Log(_, _, "The log is coming from *inside the sink*."))
.WillOnce(DeathTestExpectedLogging());
test_sink.StartCapturingLogs();
absl::AddLogSink(&reentrant_sink);
LOG(INFO).ToSinkOnly(&reentrant_sink) << "hello world";
},
DiedOfFatal, DeathTestValidateExpectations());
}
} |
348 | #ifndef THIRD_PARTY_CEL_CPP_EVAL_COMPILER_RESOLVER_H_
#define THIRD_PARTY_CEL_CPP_EVAL_COMPILER_RESOLVER_H_
#include <cstdint>
#include <string>
#include <utility>
#include <vector>
#include "absl/container/flat_hash_map.h"
#include "absl/status/statusor.h"
#include "absl/strings/string_view.h"
#include "absl/types/optional.h"
#include "base/kind.h"
#include "common/value.h"
#include "common/value_manager.h"
#include "runtime/function_overload_reference.h"
#include "runtime/function_registry.h"
#include "runtime/type_registry.h"
namespace google::api::expr::runtime {
class Resolver {
public:
Resolver(
absl::string_view container,
const cel::FunctionRegistry& function_registry,
const cel::TypeRegistry& type_registry, cel::ValueManager& value_factory,
const absl::flat_hash_map<std::string, cel::TypeRegistry::Enumeration>&
resolveable_enums,
bool resolve_qualified_type_identifiers = true);
~Resolver() = default;
absl::optional<cel::Value> FindConstant(absl::string_view name,
int64_t expr_id) const;
absl::StatusOr<absl::optional<std::pair<std::string, cel::Type>>> FindType(
absl::string_view name, int64_t expr_id) const;
std::vector<cel::FunctionRegistry::LazyOverload> FindLazyOverloads(
absl::string_view name, bool receiver_style,
const std::vector<cel::Kind>& types, int64_t expr_id = -1) const;
std::vector<cel::FunctionOverloadReference> FindOverloads(
absl::string_view name, bool receiver_style,
const std::vector<cel::Kind>& types, int64_t expr_id = -1) const;
std::vector<std::string> FullyQualifiedNames(absl::string_view base_name,
int64_t expr_id = -1) const;
private:
std::vector<std::string> namespace_prefixes_;
absl::flat_hash_map<std::string, cel::Value> enum_value_map_;
const cel::FunctionRegistry& function_registry_;
cel::ValueManager& value_factory_;
const absl::flat_hash_map<std::string, cel::TypeRegistry::Enumeration>&
resolveable_enums_;
bool resolve_qualified_type_identifiers_;
};
inline std::vector<cel::Kind> ArgumentsMatcher(int argument_count) {
std::vector<cel::Kind> argument_matcher(argument_count);
for (int i = 0; i < argument_count; i++) {
argument_matcher[i] = cel::Kind::kAny;
}
return argument_matcher;
}
}
#endif
#include "eval/compiler/resolver.h"
#include <cstdint>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "absl/base/nullability.h"
#include "absl/container/flat_hash_map.h"
#include "absl/status/statusor.h"
#include "absl/strings/match.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 "absl/types/optional.h"
#include "base/kind.h"
#include "common/memory.h"
#include "common/type.h"
#include "common/value.h"
#include "common/value_manager.h"
#include "internal/status_macros.h"
#include "runtime/function_overload_reference.h"
#include "runtime/function_registry.h"
#include "runtime/type_registry.h"
namespace google::api::expr::runtime {
using ::cel::Value;
Resolver::Resolver(
absl::string_view container, const cel::FunctionRegistry& function_registry,
const cel::TypeRegistry&, cel::ValueManager& value_factory,
const absl::flat_hash_map<std::string, cel::TypeRegistry::Enumeration>&
resolveable_enums,
bool resolve_qualified_type_identifiers)
: namespace_prefixes_(),
enum_value_map_(),
function_registry_(function_registry),
value_factory_(value_factory),
resolveable_enums_(resolveable_enums),
resolve_qualified_type_identifiers_(resolve_qualified_type_identifiers) {
auto container_elements = absl::StrSplit(container, '.');
std::string prefix = "";
namespace_prefixes_.push_back(prefix);
for (const auto& elem : container_elements) {
if (elem.empty()) {
continue;
}
absl::StrAppend(&prefix, elem, ".");
namespace_prefixes_.insert(namespace_prefixes_.begin(), prefix);
}
for (const auto& prefix : namespace_prefixes_) {
for (auto iter = resolveable_enums_.begin();
iter != resolveable_enums_.end(); ++iter) {
absl::string_view enum_name = iter->first;
if (!absl::StartsWith(enum_name, prefix)) {
continue;
}
auto remainder = absl::StripPrefix(enum_name, prefix);
const auto& enum_type = iter->second;
for (const auto& enumerator : enum_type.enumerators) {
auto key = absl::StrCat(remainder, !remainder.empty() ? "." : "",
enumerator.name);
enum_value_map_[key] = value_factory.CreateIntValue(enumerator.number);
}
}
}
}
std::vector<std::string> Resolver::FullyQualifiedNames(absl::string_view name,
int64_t expr_id) const {
std::vector<std::string> names;
if (absl::StartsWith(name, ".")) {
std::string fully_qualified_name = std::string(name.substr(1));
names.push_back(fully_qualified_name);
return names;
}
for (const auto& prefix : namespace_prefixes_) {
std::string fully_qualified_name = absl::StrCat(prefix, name);
names.push_back(fully_qualified_name);
}
return names;
}
absl::optional<cel::Value> Resolver::FindConstant(absl::string_view name,
int64_t expr_id) const {
auto names = FullyQualifiedNames(name, expr_id);
for (const auto& name : names) {
auto enum_entry = enum_value_map_.find(name);
if (enum_entry != enum_value_map_.end()) {
return enum_entry->second;
}
if (resolve_qualified_type_identifiers_ || !absl::StrContains(name, ".")) {
auto type_value = value_factory_.FindType(name);
if (type_value.ok() && type_value->has_value()) {
return value_factory_.CreateTypeValue(**type_value);
}
}
}
return absl::nullopt;
}
std::vector<cel::FunctionOverloadReference> Resolver::FindOverloads(
absl::string_view name, bool receiver_style,
const std::vector<cel::Kind>& types, int64_t expr_id) const {
std::vector<cel::FunctionOverloadReference> funcs;
auto names = FullyQualifiedNames(name, expr_id);
for (auto it = names.begin(); it != names.end(); it++) {
funcs = function_registry_.FindStaticOverloads(*it, receiver_style, types);
if (!funcs.empty()) {
return funcs;
}
}
return funcs;
}
std::vector<cel::FunctionRegistry::LazyOverload> Resolver::FindLazyOverloads(
absl::string_view name, bool receiver_style,
const std::vector<cel::Kind>& types, int64_t expr_id) const {
std::vector<cel::FunctionRegistry::LazyOverload> funcs;
auto names = FullyQualifiedNames(name, expr_id);
for (const auto& name : names) {
funcs = function_registry_.FindLazyOverloads(name, receiver_style, types);
if (!funcs.empty()) {
return funcs;
}
}
return funcs;
}
absl::StatusOr<absl::optional<std::pair<std::string, cel::Type>>>
Resolver::FindType(absl::string_view name, int64_t expr_id) const {
auto qualified_names = FullyQualifiedNames(name, expr_id);
for (auto& qualified_name : qualified_names) {
CEL_ASSIGN_OR_RETURN(auto maybe_type,
value_factory_.FindType(qualified_name));
if (maybe_type.has_value()) {
return std::make_pair(std::move(qualified_name), std::move(*maybe_type));
}
}
return absl::nullopt;
}
} | #include "eval/compiler/resolver.h"
#include <memory>
#include <string>
#include <vector>
#include "absl/status/status.h"
#include "absl/types/optional.h"
#include "base/type_provider.h"
#include "common/memory.h"
#include "common/type_factory.h"
#include "common/type_manager.h"
#include "common/value.h"
#include "common/value_manager.h"
#include "common/values/legacy_value_manager.h"
#include "eval/public/cel_function.h"
#include "eval/public/cel_function_registry.h"
#include "eval/public/cel_type_registry.h"
#include "eval/public/cel_value.h"
#include "eval/public/structs/protobuf_descriptor_type_provider.h"
#include "eval/testutil/test_message.pb.h"
#include "internal/testing.h"
namespace google::api::expr::runtime {
namespace {
using ::cel::IntValue;
using ::cel::TypeFactory;
using ::cel::TypeManager;
using ::cel::TypeValue;
using ::cel::ValueManager;
using testing::Eq;
class FakeFunction : public CelFunction {
public:
explicit FakeFunction(const std::string& name)
: CelFunction(CelFunctionDescriptor{name, false, {}}) {}
absl::Status Evaluate(absl::Span<const CelValue> args, CelValue* result,
google::protobuf::Arena* arena) const override {
return absl::OkStatus();
}
};
class ResolverTest : public testing::Test {
public:
ResolverTest()
: value_factory_(cel::MemoryManagerRef::ReferenceCounting(),
type_registry_.GetTypeProvider()) {}
protected:
CelTypeRegistry type_registry_;
cel::common_internal::LegacyValueManager value_factory_;
};
TEST_F(ResolverTest, TestFullyQualifiedNames) {
CelFunctionRegistry func_registry;
Resolver resolver("google.api.expr", func_registry.InternalGetRegistry(),
type_registry_.InternalGetModernRegistry(), value_factory_,
type_registry_.resolveable_enums());
auto names = resolver.FullyQualifiedNames("simple_name");
std::vector<std::string> expected_names(
{"google.api.expr.simple_name", "google.api.simple_name",
"google.simple_name", "simple_name"});
EXPECT_THAT(names, Eq(expected_names));
}
TEST_F(ResolverTest, TestFullyQualifiedNamesPartiallyQualifiedName) {
CelFunctionRegistry func_registry;
Resolver resolver("google.api.expr", func_registry.InternalGetRegistry(),
type_registry_.InternalGetModernRegistry(), value_factory_,
type_registry_.resolveable_enums());
auto names = resolver.FullyQualifiedNames("expr.simple_name");
std::vector<std::string> expected_names(
{"google.api.expr.expr.simple_name", "google.api.expr.simple_name",
"google.expr.simple_name", "expr.simple_name"});
EXPECT_THAT(names, Eq(expected_names));
}
TEST_F(ResolverTest, TestFullyQualifiedNamesAbsoluteName) {
CelFunctionRegistry func_registry;
Resolver resolver("google.api.expr", func_registry.InternalGetRegistry(),
type_registry_.InternalGetModernRegistry(), value_factory_,
type_registry_.resolveable_enums());
auto names = resolver.FullyQualifiedNames(".google.api.expr.absolute_name");
EXPECT_THAT(names.size(), Eq(1));
EXPECT_THAT(names[0], Eq("google.api.expr.absolute_name"));
}
TEST_F(ResolverTest, TestFindConstantEnum) {
CelFunctionRegistry func_registry;
type_registry_.Register(TestMessage::TestEnum_descriptor());
Resolver resolver("google.api.expr.runtime.TestMessage",
func_registry.InternalGetRegistry(),
type_registry_.InternalGetModernRegistry(), value_factory_,
type_registry_.resolveable_enums());
auto enum_value = resolver.FindConstant("TestEnum.TEST_ENUM_1", -1);
ASSERT_TRUE(enum_value);
ASSERT_TRUE(enum_value->Is<IntValue>());
EXPECT_THAT((*enum_value).As<IntValue>().NativeValue(), Eq(1L));
enum_value = resolver.FindConstant(
".google.api.expr.runtime.TestMessage.TestEnum.TEST_ENUM_2", -1);
ASSERT_TRUE(enum_value);
ASSERT_TRUE(enum_value->Is<IntValue>());
EXPECT_THAT((*enum_value).As<IntValue>().NativeValue(), Eq(2L));
}
TEST_F(ResolverTest, TestFindConstantUnqualifiedType) {
CelFunctionRegistry func_registry;
Resolver resolver("cel", func_registry.InternalGetRegistry(),
type_registry_.InternalGetModernRegistry(), value_factory_,
type_registry_.resolveable_enums());
auto type_value = resolver.FindConstant("int", -1);
EXPECT_TRUE(type_value);
EXPECT_TRUE(type_value->Is<TypeValue>());
EXPECT_THAT((*type_value).As<TypeValue>().name(), Eq("int"));
}
TEST_F(ResolverTest, TestFindConstantFullyQualifiedType) {
google::protobuf::LinkMessageReflection<TestMessage>();
CelFunctionRegistry func_registry;
type_registry_.RegisterTypeProvider(
std::make_unique<ProtobufDescriptorProvider>(
google::protobuf::DescriptorPool::generated_pool(),
google::protobuf::MessageFactory::generated_factory()));
Resolver resolver("cel", func_registry.InternalGetRegistry(),
type_registry_.InternalGetModernRegistry(), value_factory_,
type_registry_.resolveable_enums());
auto type_value =
resolver.FindConstant(".google.api.expr.runtime.TestMessage", -1);
ASSERT_TRUE(type_value);
ASSERT_TRUE(type_value->Is<TypeValue>());
EXPECT_THAT((*type_value).As<TypeValue>().name(),
Eq("google.api.expr.runtime.TestMessage"));
}
TEST_F(ResolverTest, TestFindConstantQualifiedTypeDisabled) {
CelFunctionRegistry func_registry;
type_registry_.RegisterTypeProvider(
std::make_unique<ProtobufDescriptorProvider>(
google::protobuf::DescriptorPool::generated_pool(),
google::protobuf::MessageFactory::generated_factory()));
Resolver resolver("", func_registry.InternalGetRegistry(),
type_registry_.InternalGetModernRegistry(), value_factory_,
type_registry_.resolveable_enums(), false);
auto type_value =
resolver.FindConstant(".google.api.expr.runtime.TestMessage", -1);
EXPECT_FALSE(type_value);
}
TEST_F(ResolverTest, FindTypeBySimpleName) {
CelFunctionRegistry func_registry;
Resolver resolver("google.api.expr.runtime",
func_registry.InternalGetRegistry(),
type_registry_.InternalGetModernRegistry(), value_factory_,
type_registry_.resolveable_enums());
type_registry_.RegisterTypeProvider(
std::make_unique<ProtobufDescriptorProvider>(
google::protobuf::DescriptorPool::generated_pool(),
google::protobuf::MessageFactory::generated_factory()));
ASSERT_OK_AND_ASSIGN(auto type, resolver.FindType("TestMessage", -1));
EXPECT_TRUE(type.has_value());
EXPECT_EQ(type->second->name(), "google.api.expr.runtime.TestMessage");
}
TEST_F(ResolverTest, FindTypeByQualifiedName) {
CelFunctionRegistry func_registry;
type_registry_.RegisterTypeProvider(
std::make_unique<ProtobufDescriptorProvider>(
google::protobuf::DescriptorPool::generated_pool(),
google::protobuf::MessageFactory::generated_factory()));
Resolver resolver("google.api.expr.runtime",
func_registry.InternalGetRegistry(),
type_registry_.InternalGetModernRegistry(), value_factory_,
type_registry_.resolveable_enums());
ASSERT_OK_AND_ASSIGN(
auto type, resolver.FindType(".google.api.expr.runtime.TestMessage", -1));
ASSERT_TRUE(type.has_value());
EXPECT_EQ(type->second->name(), "google.api.expr.runtime.TestMessage");
}
TEST_F(ResolverTest, TestFindDescriptorNotFound) {
CelFunctionRegistry func_registry;
type_registry_.RegisterTypeProvider(
std::make_unique<ProtobufDescriptorProvider>(
google::protobuf::DescriptorPool::generated_pool(),
google::protobuf::MessageFactory::generated_factory()));
Resolver resolver("google.api.expr.runtime",
func_registry.InternalGetRegistry(),
type_registry_.InternalGetModernRegistry(), value_factory_,
type_registry_.resolveable_enums());
ASSERT_OK_AND_ASSIGN(auto type, resolver.FindType("UndefinedMessage", -1));
EXPECT_FALSE(type.has_value()) << type->second;
}
TEST_F(ResolverTest, TestFindOverloads) {
CelFunctionRegistry func_registry;
auto status =
func_registry.Register(std::make_unique<FakeFunction>("fake_func"));
ASSERT_OK(status);
status = func_registry.Register(
std::make_unique<FakeFunction>("cel.fake_ns_func"));
ASSERT_OK(status);
Resolver resolver("cel", func_registry.InternalGetRegistry(),
type_registry_.InternalGetModernRegistry(), value_factory_,
type_registry_.resolveable_enums());
auto overloads =
resolver.FindOverloads("fake_func", false, ArgumentsMatcher(0));
EXPECT_THAT(overloads.size(), Eq(1));
EXPECT_THAT(overloads[0].descriptor.name(), Eq("fake_func"));
overloads =
resolver.FindOverloads("fake_ns_func", false, ArgumentsMatcher(0));
EXPECT_THAT(overloads.size(), Eq(1));
EXPECT_THAT(overloads[0].descriptor.name(), Eq("cel.fake_ns_func"));
}
TEST_F(ResolverTest, TestFindLazyOverloads) {
CelFunctionRegistry func_registry;
auto status = func_registry.RegisterLazyFunction(
CelFunctionDescriptor{"fake_lazy_func", false, {}});
ASSERT_OK(status);
status = func_registry.RegisterLazyFunction(
CelFunctionDescriptor{"cel.fake_lazy_ns_func", false, {}});
ASSERT_OK(status);
Resolver resolver("cel", func_registry.InternalGetRegistry(),
type_registry_.InternalGetModernRegistry(), value_factory_,
type_registry_.resolveable_enums());
auto overloads =
resolver.FindLazyOverloads("fake_lazy_func", false, ArgumentsMatcher(0));
EXPECT_THAT(overloads.size(), Eq(1));
overloads = resolver.FindLazyOverloads("fake_lazy_ns_func", false,
ArgumentsMatcher(0));
EXPECT_THAT(overloads.size(), Eq(1));
}
}
} |
349 | #ifndef TENSORFLOW_CORE_KERNELS_DATA_REDUCE_DATASET_OP_H_
#define TENSORFLOW_CORE_KERNELS_DATA_REDUCE_DATASET_OP_H_
#include "tensorflow/core/data/captured_function.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/framework/types.h"
#include "tensorflow/core/kernels/data/iterator_ops.h"
namespace tensorflow {
namespace data {
class ReduceDatasetOp : public HybridAsyncOpKernel {
public:
explicit ReduceDatasetOp(OpKernelConstruction* ctx);
protected:
Status DoCompute(OpKernelContext* ctx) override;
std::shared_ptr<FunctionMetadata> func_metadata_ = nullptr;
DataTypeVector output_types_;
std::vector<PartialTensorShape> output_shapes_;
};
}
}
#endif
#include "tensorflow/core/kernels/data/reduce_dataset_op.h"
#include "tensorflow/core/common_runtime/input_colocation_exemption_registry.h"
#include "tensorflow/core/data/root_dataset.h"
#include "tensorflow/core/platform/resource.h"
#include "tensorflow/core/profiler/lib/traceme.h"
namespace tensorflow {
namespace data {
namespace {
const char kOutputShapes[] = "output_shapes";
const char kOutputTypes[] = "output_types";
}
ReduceDatasetOp::ReduceDatasetOp(OpKernelConstruction* ctx)
: HybridAsyncOpKernel(ctx, "tf_data_reduce_dataset") {
FunctionMetadata::Params params;
OP_REQUIRES_OK(ctx, ctx->GetAttr("use_inter_op_parallelism",
¶ms.use_inter_op_parallelism));
params.use_default_device = false;
OP_REQUIRES_OK(ctx,
FunctionMetadata::Create(ctx, "f", params, &func_metadata_));
OP_REQUIRES_OK(ctx, ctx->GetAttr(kOutputTypes, &output_types_));
OP_REQUIRES_OK(ctx, ctx->GetAttr(kOutputShapes, &output_shapes_));
}
Status ReduceDatasetOp::DoCompute(OpKernelContext* ctx) {
tsl::profiler::TraceMe traceme(
[&] {
return tsl::profiler::TraceMeEncode("ReduceDatasetOp::DoCompute",
{{"id", ctx->step_id()}});
},
profiler::kInfo);
tensorflow::ResourceTagger tag(kTFDataResourceTag,
ctx->op_kernel().type_string());
metrics::RecordTFDataFetchOp("ReduceDatasetOp");
DatasetBase* dataset;
TF_RETURN_IF_ERROR(GetDatasetFromVariantTensor(ctx->input(0), &dataset));
OpInputList inputs;
TF_RETURN_IF_ERROR(ctx->input_list("initial_state", &inputs));
std::vector<Tensor> state(inputs.begin(), inputs.end());
std::unique_ptr<CapturedFunction> captured_func;
TF_RETURN_IF_ERROR(CapturedFunction::Create(
ctx, func_metadata_, "other_arguments", &captured_func));
IteratorContext::Params params(ctx);
auto function_handle_cache =
std::make_unique<FunctionHandleCache>(params.flr);
params.function_handle_cache = function_handle_cache.get();
ResourceMgr resource_mgr;
params.resource_mgr = &resource_mgr;
CancellationManager cancellation_manager(ctx->cancellation_manager());
params.cancellation_manager = &cancellation_manager;
IteratorContext iter_ctx(std::move(params));
std::unique_ptr<InstantiatedCapturedFunction> instantiated_captured_func;
TF_RETURN_IF_ERROR(
captured_func->Instantiate(&iter_ctx, &instantiated_captured_func));
std::unique_ptr<IteratorBase> iterator;
if (ctx->function_library()->device()->device_type() == DEVICE_CPU) {
DatasetBase* finalized_dataset = nullptr;
TF_RETURN_IF_ERROR(FinalizeDataset(ctx, dataset, &finalized_dataset));
core::ScopedUnref unref(finalized_dataset);
TF_RETURN_IF_ERROR(finalized_dataset->MakeIterator(
&iter_ctx, nullptr, "ReduceIterator", &iterator));
} else {
TF_RETURN_IF_ERROR(dataset->MakeIterator(&iter_ctx, nullptr,
"ReduceIterator", &iterator));
}
while (true) {
if (ctx->cancellation_manager()->IsCancelled()) {
return errors::Cancelled("Operation was cancelled");
}
std::vector<Tensor> next_input_element;
bool end_of_input;
TF_RETURN_IF_ERROR(
iterator->GetNext(&iter_ctx, &next_input_element, &end_of_input));
if (end_of_input) {
break;
}
std::vector<Tensor> args;
args.reserve(state.size() + next_input_element.size());
std::copy(state.begin(), state.end(), std::back_inserter(args));
std::copy(next_input_element.begin(), next_input_element.end(),
std::back_inserter(args));
std::vector<Tensor> reduce_func_output;
TF_RETURN_IF_ERROR(instantiated_captured_func->Run(
&iter_ctx, std::move(args), &reduce_func_output, nullptr));
if (reduce_func_output.size() != state.size()) {
return errors::InvalidArgument(
"The number of components of the initial state and the "
"reduce "
"function output does not match. (initial_state=",
state.size(), ", output=", reduce_func_output.size(), ").");
}
std::swap(reduce_func_output, state);
}
TF_RETURN_IF_ERROR(VerifyTypesMatch(output_types_, state));
TF_RETURN_IF_ERROR(VerifyShapesCompatible(output_shapes_, state));
for (size_t i = 0; i < state.size(); ++i) {
ctx->set_output(i, state[i]);
}
return absl::OkStatus();
}
namespace {
REGISTER_KERNEL_BUILDER(Name("ReduceDataset").Device(DEVICE_CPU),
ReduceDatasetOp);
REGISTER_INPUT_COLOCATION_EXEMPTION("ReduceDataset");
}
}
} | #include "tensorflow/core/data/dataset_test_base.h"
namespace tensorflow {
namespace data {
namespace {
constexpr char kNodeName[] = "reduce_dataset";
class ReduceDatasetParams : public DatasetParams {
public:
template <typename T>
ReduceDatasetParams(T input_dataset_params, std::vector<Tensor> initial_state,
std::vector<Tensor> other_arguments,
FunctionDefHelper::AttrValueWrapper func,
std::vector<FunctionDef> func_lib,
DataTypeVector type_state, DataTypeVector type_arguments,
DataTypeVector output_dtypes,
std::vector<PartialTensorShape> output_shapes,
bool use_inter_op_parallelism, string node_name)
: DatasetParams(std::move(output_dtypes), std::move(output_shapes),
std::move(node_name)),
initial_state_(std::move(initial_state)),
other_arguments_(std::move(other_arguments)),
func_(std::move(func)),
func_lib_(std::move(func_lib)),
type_state_(std::move(type_state)),
type_arguments_(std::move(type_arguments)),
use_inter_op_parallelism_(use_inter_op_parallelism) {
input_dataset_params_.push_back(std::make_unique<T>(input_dataset_params));
iterator_prefix_ =
name_utils::IteratorPrefix(input_dataset_params.dataset_type(),
input_dataset_params.iterator_prefix());
}
std::vector<Tensor> GetInputTensors() const override {
std::vector<Tensor> input_tensors = initial_state_;
input_tensors.insert(input_tensors.end(), other_arguments_.begin(),
other_arguments_.end());
return input_tensors;
}
Status GetInputNames(std::vector<string>* input_names) const override {
input_names->clear();
input_names->emplace_back("input_dataset");
for (int i = 0; i < initial_state_.size(); ++i) {
input_names->emplace_back(strings::StrCat("initial_state_", i));
}
for (int i = 0; i < other_arguments_.size(); ++i) {
input_names->emplace_back(strings::StrCat("other_arguments_", i));
}
return absl::OkStatus();
}
Status GetAttributes(AttributeVector* attr_vector) const override {
attr_vector->clear();
*attr_vector = {{"f", func_},
{"Tstate", type_state_},
{"Targuments", type_arguments_},
{"output_types", output_dtypes_},
{"output_shapes", output_shapes_},
{"use_inter_op_parallelism", use_inter_op_parallelism_},
{"metadata", ""}};
return absl::OkStatus();
}
string dataset_type() const override { return "Reduce"; }
std::vector<FunctionDef> func_lib() const override { return func_lib_; }
private:
std::vector<Tensor> initial_state_;
std::vector<Tensor> other_arguments_;
FunctionDefHelper::AttrValueWrapper func_;
std::vector<FunctionDef> func_lib_;
DataTypeVector type_state_;
DataTypeVector type_arguments_;
bool use_inter_op_parallelism_;
};
class ReduceDatasetOpTest : public DatasetOpsTestBase {};
ReduceDatasetParams ReduceDatasetParams1() {
return ReduceDatasetParams(
RangeDatasetParams(0, 10, 1),
CreateTensors<int64_t>(TensorShape({}), {{1}}),
{},
FunctionDefHelper::FunctionRef("XAddY", {{"T", DT_INT64}}),
{test::function::XAddY()},
{DT_INT64},
{},
{DT_INT64},
{PartialTensorShape({})},
true,
kNodeName);
}
ReduceDatasetParams ReduceDatasetParams2() {
return ReduceDatasetParams(
RangeDatasetParams(1, 10, 1),
CreateTensors<int64_t>(TensorShape({}), {{1}, {1}}),
{},
FunctionDefHelper::FunctionRef("XPlusOneXTimesY", {{"T", DT_INT64}}),
{test::function::XPlusOneXTimesY()},
{DT_INT64, DT_INT64},
{},
{DT_INT64, DT_INT64},
{PartialTensorShape({}), PartialTensorShape({})},
true,
kNodeName);
}
ReduceDatasetParams ReduceDatasetParams3() {
return ReduceDatasetParams(
RangeDatasetParams(0, 0, 1),
CreateTensors<int64_t>(TensorShape({}), {{1}, {3}}),
{},
FunctionDefHelper::FunctionRef("XAddY", {{"T", DT_INT64}}),
{test::function::XAddY()},
{DT_INT64, DT_INT64},
{},
{DT_INT64, DT_INT64},
{PartialTensorShape({}), PartialTensorShape({})},
true,
kNodeName);
}
std::vector<GetNextTestCase<ReduceDatasetParams>> GetNextTestCases() {
return {{
ReduceDatasetParams1(),
CreateTensors<int64_t>(TensorShape({}), {{46}})},
{ReduceDatasetParams2(),
CreateTensors<int64_t>(TensorShape({}),
{{10}, {1 * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9}})},
{
ReduceDatasetParams3(),
CreateTensors<int64_t>(TensorShape{}, {{1}, {3}})}};
}
class ParameterizedReduceDatasetOpTest
: public ReduceDatasetOpTest,
public ::testing::WithParamInterface<
GetNextTestCase<ReduceDatasetParams>> {};
TEST_P(ParameterizedReduceDatasetOpTest, Compute) {
auto test_case = GetParam();
TF_ASSERT_OK(InitializeRuntime(test_case.dataset_params));
std::vector<Tensor> output;
TF_ASSERT_OK(RunDatasetOp(test_case.dataset_params, &output));
TF_EXPECT_OK(
ExpectEqual(test_case.expected_outputs, output, true));
}
INSTANTIATE_TEST_SUITE_P(ReduceDatasetOpTest, ParameterizedReduceDatasetOpTest,
::testing::ValuesIn(GetNextTestCases()));
}
}
} |
350 | #ifndef AROLLA_EXPR_EXPR_VISITOR_H_
#define AROLLA_EXPR_EXPR_VISITOR_H_
#include <cstddef>
#include <optional>
#include <type_traits>
#include <utility>
#include <vector>
#include "absl/algorithm/container.h"
#include "absl/base/attributes.h"
#include "absl/functional/function_ref.h"
#include "absl/log/check.h"
#include "absl/status/statusor.h"
#include "absl/types/span.h"
#include "arolla/expr/expr.h"
#include "arolla/expr/expr_debug_string.h"
#include "arolla/expr/expr_node.h"
#include "arolla/util/meta.h"
#include "arolla/util/status_macros_backport.h"
namespace arolla::expr {
class PostOrder {
public:
PostOrder() = default;
explicit PostOrder(const ExprNodePtr& root);
absl::Span<const ExprNodePtr> nodes() const { return nodes_; }
size_t nodes_size() const { return nodes_.size(); }
const ExprNodePtr& node(size_t node_index) const
ABSL_ATTRIBUTE_LIFETIME_BOUND {
return nodes_[node_index];
}
absl::Span<const size_t> dep_indices(size_t node_index) const {
DCHECK(node_index < nodes_.size());
return absl::Span<const size_t>(
adjacency_array_.data() + adjacency_array_[node_index],
adjacency_array_[node_index + 1] - adjacency_array_[node_index]);
}
private:
std::vector<ExprNodePtr> nodes_;
std::vector<size_t> adjacency_array_;
};
std::vector<ExprNodePtr> VisitorOrder(ExprNodePtr root);
std::vector<std::pair<bool, ExprNodePtr>> PreAndPostVisitorOrder(
ExprNodePtr root);
template <typename VisitorResultType>
struct ExprVisitorResultTraits;
template <typename Visitor>
auto PostOrderTraverse(const PostOrder& post_order, Visitor visitor) {
using Traits = ExprVisitorResultTraits<
typename meta::function_traits<Visitor>::return_type>;
using T = typename Traits::ResultType;
static_assert(std::is_invocable_r_v<absl::StatusOr<T>, Visitor, ExprNodePtr,
absl::Span<const T* const>>,
"Visitor has an unexpected signature.");
struct WrappedT {
T value;
WrappedT(T&& value) : value(std::move(value)) {}
WrappedT(WrappedT&&) = default;
WrappedT& operator=(WrappedT&&) = default;
};
std::vector<WrappedT> results;
results.reserve(post_order.nodes_size());
std::vector<const T*> args;
const auto invoke_visitor = [&](size_t node_index) {
const auto dep_indices = post_order.dep_indices(node_index);
args.resize(dep_indices.size());
for (size_t j = 0; j < dep_indices.size(); ++j) {
args[j] = &results[dep_indices[j]].value;
}
return visitor(post_order.node(node_index), absl::MakeConstSpan(args));
};
for (size_t i = 0; i + 1 < post_order.nodes_size(); ++i) {
auto visit_result = invoke_visitor(i);
if (!Traits::ok(visit_result)) {
return visit_result;
}
results.emplace_back(Traits::value(std::move(visit_result)));
}
return invoke_visitor(post_order.nodes_size() - 1);
}
template <typename Visitor>
auto PostOrderTraverse(const ExprNodePtr& root, Visitor visitor) {
return PostOrderTraverse(PostOrder(root), visitor);
}
template <typename TransformFn>
absl::StatusOr<ExprNodePtr> Transform(const ExprNodePtr& root,
TransformFn transform_fn) {
return TransformOnPostOrder(PostOrder(root), std::move(transform_fn));
}
template <typename TransformFn>
absl::StatusOr<ExprNodePtr> TransformOnPostOrder(const PostOrder& post_order,
TransformFn transform_fn) {
using Traits = ExprVisitorResultTraits<
typename meta::function_traits<TransformFn>::return_type>;
static_assert(std::is_invocable_r_v<absl::StatusOr<ExprNodePtr>, TransformFn,
ExprNodePtr>,
"TransformFn has an unexpected signature.");
std::vector<ExprNodePtr> results(post_order.nodes_size());
for (size_t i = 0; i < post_order.nodes_size(); ++i) {
const auto& node = post_order.node(i);
const auto& dep_indices = post_order.dep_indices(i);
bool has_modified_dep =
node->is_op() && absl::c_any_of(dep_indices, [&](size_t k) {
return results[k] != nullptr;
});
ExprNodePtr transform_fn_input_node;
if (has_modified_dep) {
const auto& deps = node->node_deps();
std::vector<ExprNodePtr> new_deps(dep_indices.size());
for (size_t j = 0; j < dep_indices.size(); ++j) {
const size_t k = dep_indices[j];
if (results[k] != nullptr) {
new_deps[j] = results[k];
} else {
new_deps[j] = deps[j];
}
}
ASSIGN_OR_RETURN(transform_fn_input_node,
MakeOpNode(node->op(), std::move(new_deps)),
_ << "while processing " << GetDebugSnippet(node));
} else {
transform_fn_input_node = node;
}
auto transform_fn_result = transform_fn(std::move(transform_fn_input_node));
if (!Traits::ok(transform_fn_result)) {
return transform_fn_result;
}
auto new_node = Traits::value(std::move(transform_fn_result));
if (new_node->fingerprint() != node->fingerprint()) {
results[i] = Traits::value(std::move(new_node));
}
}
if (results.back() != nullptr) {
return std::move(results.back());
} else {
return post_order.nodes().back();
}
}
enum class DeepTransformStage {
kWithNewDeps,
kNewChildAfterTransformation
};
using LogTransformationFn = absl::FunctionRef<void(
ExprNodePtr new_node, ExprNodePtr old_node, DeepTransformStage stage)>;
absl::StatusOr<ExprNodePtr> DeepTransform(
const ExprNodePtr& root,
absl::FunctionRef<absl::StatusOr<ExprNodePtr>(ExprNodePtr)> transform_fn,
std::optional<LogTransformationFn> log_transformation_fn = std::nullopt,
size_t processed_node_limit = 10'000'000);
template <typename VisitorResultType>
struct ExprVisitorResultTraits {
using ResultType = VisitorResultType;
static constexpr bool ok(const VisitorResultType&) { return true; }
static constexpr ResultType value(VisitorResultType&& input) { return input; }
};
template <typename T>
struct ExprVisitorResultTraits<absl::StatusOr<T>> {
using ResultType = T;
static bool ok(const absl::StatusOr<T>& input) { return input.ok(); }
static ResultType value(absl::StatusOr<T>&& input) {
return *std::move(input);
}
};
template <typename T>
std::vector<T> DereferenceVisitPointers(absl::Span<const T* const> visits) {
std::vector<T> res;
res.reserve(visits.size());
for (const T* ptr : visits) {
res.push_back(*ptr);
}
return res;
}
}
#endif
#include "arolla/expr/expr_visitor.h"
#include <cstddef>
#include <limits>
#include <optional>
#include <stack>
#include <utility>
#include <vector>
#include "absl/container/flat_hash_map.h"
#include "absl/container/flat_hash_set.h"
#include "absl/functional/function_ref.h"
#include "absl/log/check.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/str_format.h"
#include "arolla/expr/expr.h"
#include "arolla/expr/expr_debug_string.h"
#include "arolla/expr/expr_node.h"
#include "arolla/util/fingerprint.h"
#include "arolla/util/status_macros_backport.h"
namespace arolla::expr {
namespace {
template <class PrevisitFn, class PostVisitFn>
void VisitorOrderImpl(const ExprNodePtr& root, PrevisitFn previsit_fn,
PostVisitFn postvisit_fn) {
struct Frame {
const ExprNodePtr& node;
size_t processed_deps_count = 0;
};
absl::flat_hash_set<Fingerprint> visited = {root->fingerprint()};
std::vector<Frame> stack = {Frame{root}};
while (!stack.empty()) {
auto& frame = stack.back();
if (frame.processed_deps_count == 0) {
previsit_fn(frame.node);
}
const auto& node_deps = frame.node->node_deps();
if (frame.processed_deps_count == node_deps.size()) {
postvisit_fn(frame.node);
stack.pop_back();
continue;
}
const auto& dep = node_deps[frame.processed_deps_count++];
if (visited.insert(dep->fingerprint()).second) {
stack.push_back(Frame{dep});
}
}
}
}
std::vector<ExprNodePtr> VisitorOrder(ExprNodePtr root) {
std::vector<ExprNodePtr> res_visits;
VisitorOrderImpl(
root, [](auto) {},
[&res_visits](const auto& node) { res_visits.push_back(node); });
return res_visits;
}
std::vector<std::pair<bool, ExprNodePtr>> PreAndPostVisitorOrder(
ExprNodePtr root) {
std::vector<std::pair<bool, ExprNodePtr>> res_visits;
VisitorOrderImpl(
root,
[&res_visits](const auto& node) { res_visits.emplace_back(true, node); },
[&res_visits](const auto& node) {
res_visits.emplace_back(false, node);
});
return res_visits;
}
PostOrder::PostOrder(const ExprNodePtr& root) {
struct Frame {
const ExprNodePtr& node;
size_t dep_idx = 0;
};
absl::flat_hash_map<Fingerprint, size_t> node_indices;
{
std::vector<Frame> stack;
stack.push_back(Frame{root});
while (!stack.empty()) {
auto& frame = stack.back();
const auto& deps = frame.node->node_deps();
while (frame.dep_idx < deps.size() &&
node_indices.contains(deps[frame.dep_idx]->fingerprint())) {
++frame.dep_idx;
}
if (frame.dep_idx < deps.size()) {
stack.push_back(Frame{deps[frame.dep_idx++]});
} else {
node_indices.emplace(frame.node->fingerprint(), nodes_.size());
nodes_.push_back(frame.node);
stack.pop_back();
}
}
}
{
size_t total_arc_count = 0;
for (const auto& node : nodes_) {
total_arc_count += node->node_deps().size();
}
adjacency_array_.resize(nodes_.size() + 1 + total_arc_count);
size_t i = 0;
size_t j = nodes_.size() + 1;
while (i < nodes_.size()) {
adjacency_array_[i] = j;
for (const auto& dep : nodes_[i++]->node_deps()) {
adjacency_array_[j++] = node_indices.at(dep->fingerprint());
}
}
adjacency_array_[nodes_.size()] = j;
}
}
absl::StatusOr<ExprNodePtr> DeepTransform(
const ExprNodePtr& root,
absl::FunctionRef<absl::StatusOr<ExprNodePtr>(ExprNodePtr)> transform_fn,
std::optional<LogTransformationFn> log_transformation_fn,
size_t processed_node_limit) {
constexpr size_t kSkipFirstStage = std::numeric_limits<size_t>::max();
constexpr auto infinite_loop_error = [](const ExprNodePtr& node) {
return absl::FailedPreconditionError(absl::StrFormat(
"infinite loop of node transformations containing node %s",
GetDebugSnippet(node)));
};
struct Frame {
ExprNodePtr node;
size_t dep_idx = 0;
Fingerprint new_node_fingerprint;
Fingerprint transformed_new_node_fingerprint;
std::optional<ExprNodePtr> original_node = std::nullopt;
};
absl::flat_hash_map<Fingerprint, ExprNodePtr> cache;
std::stack<Frame> stack;
cache.emplace(root->fingerprint(), nullptr);
stack.emplace(Frame{.node = root});
while (!stack.empty()) {
auto& frame = stack.top();
if (cache.size() > processed_node_limit) {
return absl::FailedPreconditionError(absl::StrFormat(
"too many processed nodes (%i), this probably means an infinite "
"transformation. Possibly caused by node %s",
cache.size(), GetDebugSnippet(frame.node)));
}
if (frame.dep_idx != kSkipFirstStage) {
const auto& deps = frame.node->node_deps();
while (
frame.dep_idx < deps.size() &&
!cache.emplace(deps[frame.dep_idx]->fingerprint(), nullptr).second) {
++frame.dep_idx;
}
if (frame.dep_idx < deps.size()) {
if (log_transformation_fn.has_value() &&
frame.original_node != std::nullopt) {
(*log_transformation_fn)(
deps[frame.dep_idx], frame.node,
DeepTransformStage::kNewChildAfterTransformation);
}
stack.emplace(Frame{.node = deps[frame.dep_idx++],
.original_node = frame.original_node});
continue;
}
std::vector<ExprNodePtr> new_deps(deps.size());
for (size_t i = 0; i < deps.size(); ++i) {
new_deps[i] = cache[deps[i]->fingerprint()];
if (new_deps[i] == nullptr) {
return infinite_loop_error(frame.node);
}
}
ASSIGN_OR_RETURN(auto new_node,
WithNewDependencies(frame.node, std::move(new_deps)));
if (log_transformation_fn.has_value()) {
(*log_transformation_fn)(new_node, frame.node,
DeepTransformStage::kWithNewDeps);
}
if (new_node->fingerprint() != frame.node->fingerprint()) {
if (auto [it, miss] = cache.emplace(new_node->fingerprint(), nullptr);
!miss) {
if (it->second == nullptr) {
return infinite_loop_error(frame.node);
}
cache[frame.node->fingerprint()] = it->second;
stack.pop();
continue;
}
}
ASSIGN_OR_RETURN(
auto transformed_new_node, transform_fn(new_node),
_ << "while transforming " << GetDebugSnippet(frame.node));
DCHECK_NE(transformed_new_node, nullptr);
if (transformed_new_node->fingerprint() == new_node->fingerprint()) {
cache[frame.node->fingerprint()] = std::move(transformed_new_node);
if (new_node->fingerprint() != frame.node->fingerprint()) {
cache[new_node->fingerprint()] = std::move(new_node);
}
stack.pop();
continue;
}
if (auto [it, miss] =
cache.emplace(transformed_new_node->fingerprint(), nullptr);
!miss) {
if (it->second == nullptr) {
return infinite_loop_error(frame.node);
}
cache[frame.node->fingerprint()] = it->second;
if (new_node->fingerprint() != frame.node->fingerprint()) {
cache[new_node->fingerprint()] = it->second;
}
stack.pop();
continue;
}
frame.dep_idx = kSkipFirstStage;
frame.new_node_fingerprint = new_node->fingerprint();
frame.transformed_new_node_fingerprint =
transformed_new_node->fingerprint();
stack.emplace(Frame{.node = transformed_new_node,
.original_node = transformed_new_node});
continue;
}
const auto& node_result = cache.at(frame.transformed_new_node_fingerprint);
DCHECK_NE(node_result, nullptr);
cache[frame.node->fingerprint()] = node_result;
if (frame.new_node_fingerprint != frame.node->fingerprint()) {
cache[frame.new_node_fingerprint] = node_result;
}
stack.pop();
}
auto& root_result = cache.at(root->fingerprint());
DCHECK_NE(root_result, nullptr);
return std::move(root_result);
}
} | #include "arolla/expr/expr_visitor.h"
#include <cstddef>
#include <functional>
#include <memory>
#include <optional>
#include <string>
#include <utility>
#include <vector>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "absl/container/flat_hash_set.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/types/span.h"
#include "arolla/expr/expr.h"
#include "arolla/expr/expr_debug_string.h"
#include "arolla/expr/expr_node.h"
#include "arolla/expr/expr_operator.h"
#include "arolla/expr/expr_operator_signature.h"
#include "arolla/expr/testing/test_operators.h"
#include "arolla/expr/testing/testing.h"
#include "arolla/util/fingerprint.h"
#include "arolla/util/init_arolla.h"
#include "arolla/util/testing/status_matchers_backport.h"
namespace arolla::expr {
namespace {
using ::arolla::expr::testing::DummyOp;
using ::arolla::testing::EqualsExpr;
using ::arolla::testing::IsOkAndHolds;
using ::arolla::testing::StatusIs;
using ::testing::ElementsAre;
using ::testing::Eq;
using ::testing::HasSubstr;
using ::testing::Pair;
using ::testing::Pointer;
size_t CountNodes(const ExprNodePtr& expr) {
size_t result = 0;
return PostOrderTraverse(
expr,
[&](const ExprNodePtr& ,
absl::Span<const size_t* const> ) { return ++result; });
}
class ExprVisitorTest : public ::testing::Test {
public:
template <typename... Args>
ExprNodePtr Bar(Args&&... args) {
return CallOp(bar_, {std::forward<Args>(args)...}).value();
}
template <typename... Args>
ExprNodePtr Baz(Args&&... args) {
return CallOp(baz_, {std::forward<Args>(args)...}).value();
}
template <typename... Args>
ExprNodePtr Qux(Args&&... args) {
return CallOp(qux_, {std::forward<Args>(args)...}).value();
}
protected:
void SetUp() override { ASSERT_OK(InitArolla()); }
ExprOperatorPtr bar_ = std::make_shared<DummyOp>(
"bar", ExprOperatorSignature::MakeVariadicArgs());
ExprOperatorPtr baz_ = std::make_shared<DummyOp>(
"baz", ExprOperatorSignature::MakeVariadicArgs());
ExprOperatorPtr qux_ = std::make_shared<DummyOp>(
"qux", ExprOperatorSignature::MakeVariadicArgs());
};
TEST_F(ExprVisitorTest, PostOrder_Trivial) {
auto x0 = Leaf("x0");
PostOrder post_order(x0);
ASSERT_THAT(post_order.nodes(), ElementsAre(Pointer(x0.get())));
ASSERT_THAT(post_order.dep_indices(0), ElementsAre());
}
TEST_F(ExprVisitorTest, PostOrder) {
auto x0 = Leaf("x0");
auto x1 = Leaf("x1");
auto x2 = Leaf("x2");
auto add01 = Bar(x0, x1);
auto add012 = Bar(add01, x0, x1, x2);
PostOrder post_order(add012);
ASSERT_THAT(
post_order.nodes(),
ElementsAre(Pointer(x0.get()), Pointer(x1.get()), Pointer(add01.get()),
Pointer(x2.get()), Pointer(add012.get())));
ASSERT_THAT(post_order.dep_indices(0), ElementsAre());
ASSERT_THAT(post_order.dep_indices(1), ElementsAre());
ASSERT_THAT(post_order.dep_indices(2), ElementsAre(0, 1));
ASSERT_THAT(post_order.dep_indices(3), ElementsAre());
ASSERT_THAT(post_order.dep_indices(4), ElementsAre(2, 0, 1, 3));
}
TEST_F(ExprVisitorTest, VisitOrder) {
auto x0 = Leaf("x0");
auto x1 = Leaf("x1");
auto x2 = Leaf("x2");
auto add01 = Bar(x0, x1);
auto add012 = Bar(add01, x2);
std::vector<ExprNodePtr> actual_order = VisitorOrder(add012);
ASSERT_THAT(actual_order, ElementsAre(Pointer(x0.get()), Pointer(x1.get()),
Pointer(add01.get()), Pointer(x2.get()),
Pointer(add012.get())));
}
TEST_F(ExprVisitorTest, PreAndPostVisitorOrder) {
auto x0 = Leaf("x0");
auto x1 = Leaf("x1");
auto x2 = Leaf("x2");
auto add01 = Bar(x0, x1);
auto add012 = Bar(add01, x2);
std::vector<std::pair<bool, ExprNodePtr>> actual_order =
PreAndPostVisitorOrder(add012);
ASSERT_THAT(
actual_order,
ElementsAre(
Pair(true, Pointer(add012.get())), Pair(true, Pointer(add01.get())),
Pair(true, Pointer(x0.get())), Pair(false, Pointer(x0.get())),
Pair(true, Pointer(x1.get())), Pair(false, Pointer(x1.get())),
Pair(false, Pointer(add01.get())), Pair(true, Pointer(x2.get())),
Pair(false, Pointer(x2.get())), Pair(false, Pointer(add012.get()))));
}
TEST_F(ExprVisitorTest, PostOrderTraverseBool) {
ASSERT_TRUE(PostOrderTraverse(
Leaf("x"),
[](ExprNodePtr, absl::Span<bool const* const>) -> bool { return true; }));
}
TEST_F(ExprVisitorTest, PostOrderTraverseStatusOrBool) {
ASSERT_THAT(PostOrderTraverse(Leaf("x"),
[](ExprNodePtr, absl::Span<bool const* const>) {
return absl::StatusOr<bool>(true);
}),
IsOkAndHolds(true));
}
TEST_F(ExprVisitorTest, VisitLeaf) { ASSERT_EQ(CountNodes(Leaf("x")), 1); }
TEST_F(ExprVisitorTest, VisitOperator) {
ASSERT_EQ(CountNodes(Bar(Leaf("x"), Leaf("y"))), 3);
}
TEST_F(ExprVisitorTest, LargeAst) {
ASSERT_EQ(CountNodes(Bar(Bar(Leaf("x"), Leaf("y")), Leaf("x"))), 4);
}
TEST_F(ExprVisitorTest, Transform_WithStatusOrFn) {
auto expr = Bar(Bar(Baz(Leaf("a"), Leaf("b")), Leaf("c")), Leaf("d"));
ASSERT_OK_AND_ASSIGN(
ExprNodePtr expr_with_qux,
Transform(expr, [&](ExprNodePtr node) -> absl::StatusOr<ExprNodePtr> {
if (node->op() == bar_) {
return WithNewOperator(node, qux_);
}
return node;
}));
ASSERT_THAT(
expr_with_qux,
EqualsExpr(Qux(Qux(Baz(Leaf("a"), Leaf("b")), Leaf("c")), Leaf("d"))));
EXPECT_THAT(expr_with_qux->node_deps()[0]->node_deps()[0].get(),
Eq(expr->node_deps()[0]->node_deps()[0].get()));
}
TEST_F(ExprVisitorTest, Transform_WithNoStatusFn) {
auto expr = Bar(Bar(Baz(Leaf("a"), Leaf("b")), Leaf("c")), Leaf("d"));
EXPECT_THAT(Transform(expr,
[&](ExprNodePtr node) -> ExprNodePtr {
if (node->op() == bar_) {
return node->node_deps()[0];
} else {
return node;
}
}),
IsOkAndHolds(EqualsExpr(expr->node_deps()[0]->node_deps()[0])));
}
TEST_F(ExprVisitorTest, Transform_NoChangeRequired) {
auto expr = Baz(Bar(Baz(Leaf("a"), Leaf("b")), Leaf("c")), Leaf("d"));
EXPECT_THAT(Transform(expr, [](ExprNodePtr node) { return node; }),
IsOkAndHolds(EqualsExpr(expr)));
}
class DeepTransformTest : public ::testing::Test {
public:
template <typename... Args>
ExprNodePtr A(Args&&... args) {
return CallOp(a_, {std::forward<Args>(args)...}).value();
}
template <typename... Args>
ExprNodePtr B(Args&&... args) {
return CallOp(b_, {std::forward<Args>(args)...}).value();
}
template <typename... Args>
ExprNodePtr S(Args&&... args) {
return CallOp(s_, {std::forward<Args>(args)...}).value();
}
template <typename... Args>
ExprNodePtr C(Args&&... args) {
return CallOp(c_, {std::forward<Args>(args)...}).value();
}
auto SabTransform()
-> std::function<absl::StatusOr<ExprNodePtr>(ExprNodePtr)> {
return [this, visited = absl::flat_hash_set<Fingerprint>()](
ExprNodePtr node) mutable -> absl::StatusOr<ExprNodePtr> {
EXPECT_TRUE(visited.emplace(node->fingerprint()).second)
<< "duplicate call to transform_fn";
if (node->op() == s_) {
std::vector<absl::StatusOr<ExprNodePtr>> new_deps;
for (auto& dep : node->node_deps()) {
new_deps.push_back(WithNewOperator(dep, s_));
}
return CallOp(a_, new_deps);
}
if (node->op() == a_) {
std::vector<absl::StatusOr<ExprNodePtr>> new_deps;
for (auto& dep : node->node_deps()) {
new_deps.push_back(WithNewOperator(dep, s_));
}
return CallOp(b_, new_deps);
}
if (node->op() == c_) {
std::vector<absl::StatusOr<ExprNodePtr>> new_deps;
for (auto& dep : node->node_deps()) {
new_deps.push_back(CallOp(b_, {dep}));
}
return CallOp(b_, new_deps);
}
return node;
};
}
private:
void SetUp() override { ASSERT_OK(InitArolla()); }
ExprOperatorPtr a_ =
std::make_shared<DummyOp>("a", ExprOperatorSignature::MakeVariadicArgs());
ExprOperatorPtr b_ =
std::make_shared<DummyOp>("b", ExprOperatorSignature::MakeVariadicArgs());
ExprOperatorPtr c_ =
std::make_shared<DummyOp>("c", ExprOperatorSignature::MakeVariadicArgs());
ExprOperatorPtr s_ =
std::make_shared<DummyOp>("s", ExprOperatorSignature::MakeVariadicArgs());
};
TEST_F(DeepTransformTest, Trivial) {
ASSERT_THAT(DeepTransform(A(), SabTransform()),
IsOkAndHolds(EqualsExpr(B())));
ASSERT_THAT(DeepTransform(B(), SabTransform()),
IsOkAndHolds(EqualsExpr(B())));
ASSERT_THAT(DeepTransform(S(), SabTransform()),
IsOkAndHolds(EqualsExpr(B())));
}
TEST_F(DeepTransformTest, CacheHitCoverage) {
{
auto expr = B(A(A()), A(S()));
auto expected = B(B(B()), B(B()));
ASSERT_THAT(DeepTransform(expr, SabTransform()),
IsOkAndHolds(EqualsExpr(expected)));
}
{
auto expr = B(B(S()), A(S()));
auto expected = B(B(B()), B(B()));
ASSERT_THAT(DeepTransform(expr, SabTransform()),
IsOkAndHolds(EqualsExpr(expected)));
}
}
TEST_F(DeepTransformTest, TooManyProcessedNodes) {
ASSERT_THAT(DeepTransform(
Literal<int>(0),
[](ExprNodePtr node) {
return Literal<int>(node->qvalue()->UnsafeAs<int>() + 1);
},
std::nullopt,
1000),
StatusIs(absl::StatusCode::kFailedPrecondition,
HasSubstr("too many processed nodes")));
}
TEST_F(DeepTransformTest, LogTransformationFn) {
std::string trace;
auto transformations_logger = [&trace](ExprNodePtr a, ExprNodePtr b,
DeepTransformStage stage) {
if (stage == DeepTransformStage::kWithNewDeps) {
if (a->fingerprint() != b->fingerprint()) {
trace += GetDebugSnippet(b) +
" got new dependencies: " + GetDebugSnippet(a) + "\n";
}
} else if (stage == DeepTransformStage::kNewChildAfterTransformation) {
trace += GetDebugSnippet(b) + " contains " + GetDebugSnippet(a) + "\n";
}
};
ASSERT_OK(DeepTransform(C(A()), SabTransform(),
transformations_logger));
EXPECT_EQ(
"c(a():INT32):INT32 got new dependencies: c(b():INT32):INT32\n"
"b(b(...):INT32):INT32 contains b(b():INT32):INT32\n",
trace);
}
TEST_F(DeepTransformTest, InfiniteLoop) {
ASSERT_THAT(DeepTransform(S(), [&](ExprNodePtr) { return S(S()); }),
StatusIs(absl::StatusCode::kFailedPrecondition,
HasSubstr("infinite loop of node transformations "
"containing node s(s():INT32):INT32")));
}
TEST_F(DeepTransformTest, UnaryRecursion) {
auto expr = S();
auto expected = B();
for (int i = 0; i < 10; ++i) {
expr = S(expr);
expected = B(expected);
}
ASSERT_THAT(DeepTransform(expr, SabTransform()),
IsOkAndHolds(EqualsExpr(expected)));
}
TEST_F(DeepTransformTest, UnaryRecursionStress) {
auto expr = S();
auto expected = B();
for (int i = 0; i < 1000; ++i) {
expr = S(expr);
expected = B(expected);
}
ASSERT_THAT(DeepTransform(expr, SabTransform()),
IsOkAndHolds(EqualsExpr(expected)));
}
TEST_F(DeepTransformTest, BinaryRecursion) {
auto expr = S();
auto expected = B();
for (int i = 0; i < 10; ++i) {
expr = S(expr, expr);
expected = B(expected, expected);
}
ASSERT_THAT(DeepTransform(expr, SabTransform()),
IsOkAndHolds(EqualsExpr(expected)));
}
TEST_F(DeepTransformTest, BinaryRecursionStress) {
auto expr = S();
auto expected = B();
for (int i = 0; i < 1000; ++i) {
expr = S(expr, expr);
expected = B(expected, expected);
}
ASSERT_THAT(DeepTransform(expr, SabTransform()),
IsOkAndHolds(EqualsExpr(expected)));
}
TEST_F(DeepTransformTest, TernaryRecursionStress) {
auto expr = S();
auto expected = B();
for (int i = 0; i < 1000; ++i) {
expr = S(expr, expr, expr);
expected = B(expected, expected, expected);
}
ASSERT_THAT(DeepTransform(expr, SabTransform()),
IsOkAndHolds(EqualsExpr(expected)));
}
TEST_F(DeepTransformTest, ComplexRecursionStress) {
auto expr = S();
auto expected = B();
for (int i = 0; i < 1000; ++i) {
expr = S(A(expr), B(expr, expected), expr);
expected = B(B(expected), B(expected, expected), expected);
}
ASSERT_THAT(DeepTransform(expr, SabTransform()),
IsOkAndHolds(EqualsExpr(expected)));
}
}
} |
351 | #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));
}
}
} |
352 | #ifndef TENSORFLOW_C_EXPERIMENTAL_OPS_GEN_CPP_RENDERERS_RENDERER_H_
#define TENSORFLOW_C_EXPERIMENTAL_OPS_GEN_CPP_RENDERERS_RENDERER_H_
#include "absl/strings/string_view.h"
#include "absl/strings/substitute.h"
#include "tensorflow/c/experimental/ops/gen/cpp/renderers/renderer_context.h"
#include "tensorflow/core/platform/types.h"
namespace tensorflow {
namespace generator {
namespace cpp {
class Renderer {
public:
explicit Renderer(RendererContext context);
protected:
Renderer &BlankLine();
Renderer &CodeLine(const string &text);
template <typename... Args>
Renderer CodeLine(absl::string_view text, const Args &...args) {
return CodeLine(absl::Substitute(text, args...));
}
Renderer &CodeLines(const string &text);
template <typename... Args>
Renderer CodeLines(absl::string_view text, const Args &...args) {
return CodeLines(absl::Substitute(text, args...));
}
Renderer &Statement(const string &text);
template <typename... Args>
Renderer Statement(absl::string_view text, const Args &...args) {
return Statement(absl::Substitute(text, args...));
}
Renderer &TFStatement(const string &text);
template <typename... Args>
Renderer TFStatement(absl::string_view text, const Args &...args) {
return TFStatement(absl::Substitute(text, args...));
}
Renderer &CommentLine(const string &text = "");
template <typename... Args>
Renderer CommentLine(absl::string_view text, const Args &...args) {
return CommentLine(absl::Substitute(text, args...));
}
Renderer &BlockOpen(const string &text);
template <typename... Args>
Renderer BlockOpen(absl::string_view text, const Args &...args) {
return BlockOpen(absl::Substitute(text, args...));
}
Renderer &BlockClose(const string &text = "");
template <typename... Args>
Renderer BlockClose(absl::string_view text, const Args &...args) {
return BlockClose(absl::Substitute(text, args...));
}
protected:
RendererContext context_;
};
}
}
}
#endif
#include "tensorflow/c/experimental/ops/gen/cpp/renderers/renderer.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/substitute.h"
#include "tensorflow/c/experimental/ops/gen/cpp/renderers/renderer_context.h"
#include "tensorflow/core/lib/strings/str_util.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/stringpiece.h"
namespace tensorflow {
namespace generator {
namespace cpp {
Renderer::Renderer(RendererContext context) : context_(context) {}
Renderer& Renderer::BlankLine() {
context_.code.AddLineWithoutIndent("");
return *this;
}
Renderer& Renderer::CodeLine(const string& text) {
context_.code.AddLineWithoutIndent(text);
return *this;
}
Renderer& Renderer::CodeLines(const string& text) {
StringPiece trimmed_text(text);
str_util::RemoveWhitespaceContext(&trimmed_text);
for (const string& line : str_util::Split(trimmed_text, '\n')) {
context_.code.AddLineWithoutIndent(line);
}
return *this;
}
Renderer& Renderer::Statement(const string& text) {
if (str_util::EndsWith(text, ";")) {
LOG(WARNING) << "Superfluous terminating ';' in '" << text << "'";
context_.code.AddLineWithIndent(text);
} else {
context_.code.AddLineWithIndent(absl::StrCat(text, ";"));
}
return *this;
}
Renderer& Renderer::TFStatement(const string& text) {
return Statement(absl::Substitute("TF_RETURN_IF_ERROR($0)", text));
}
Renderer& Renderer::CommentLine(const string& text) {
context_.code.AddLineWithIndent(absl::StrCat("
return *this;
}
Renderer& Renderer::BlockOpen(const string& text) {
context_.code.AddLineWithIndent(absl::StrCat(text, " {"));
context_.code.IncreaseIndent();
return *this;
}
Renderer& Renderer::BlockClose(const string& text) {
context_.code.DecreaseIndent();
context_.code.AddLineWithIndent(absl::StrCat("}", text));
return *this;
}
}
}
} | #include "tensorflow/c/experimental/ops/gen/cpp/renderers/renderer.h"
#include "tensorflow/c/experimental/ops/gen/common/path_config.h"
#include "tensorflow/c/experimental/ops/gen/common/source_code.h"
#include "tensorflow/c/experimental/ops/gen/cpp/renderers/cpp_config.h"
#include "tensorflow/c/experimental/ops/gen/cpp/renderers/renderer_context.h"
#include "tensorflow/core/platform/test.h"
#include "tensorflow/core/platform/types.h"
namespace tensorflow {
namespace generator {
namespace cpp {
namespace {
TEST(Renderer, typical_usage) {
class TestRenderer : Renderer {
public:
explicit TestRenderer(SourceCode& code)
: Renderer(
{RendererContext::kSource, code, CppConfig(), PathConfig()}) {}
void Render() {
CommentLine("File level comment.");
CodeLine("#include \"header.h\"");
BlankLine();
BlockOpen("void TestFunction()");
{
Statement("int i = 1");
BlankLine();
BlockOpen("while (i == 1)");
{
CommentLine("Do nothing, really....");
CodeLine("#if 0");
Statement("call()");
CodeLine("#endif");
BlockClose();
}
BlockClose("
}
}
};
SourceCode code;
TestRenderer(code).Render();
string expected = R"(
#include "header.h"
void TestFunction() {
int i = 1;
while (i == 1) {
#if 0
call();
#endif
}
}
)";
code.SetSpacesPerIndent(3);
EXPECT_EQ(expected, code.Render());
}
}
}
}
} |
353 | #ifndef XLA_TEXT_LITERAL_WRITER_H_
#define XLA_TEXT_LITERAL_WRITER_H_
#include "absl/strings/string_view.h"
#include "xla/literal.h"
#include "xla/types.h"
#include "xla/xla_data.pb.h"
#include "tsl/platform/status.h"
namespace xla {
class TextLiteralWriter {
public:
static absl::Status WriteToPath(const Literal& literal,
absl::string_view path);
private:
TextLiteralWriter(const TextLiteralWriter&) = delete;
TextLiteralWriter& operator=(const TextLiteralWriter&) = delete;
};
}
#endif
#include "xla/text_literal_writer.h"
#include <memory>
#include <string>
#include "absl/strings/str_cat.h"
#include "absl/strings/str_join.h"
#include "absl/types/span.h"
#include "xla/literal.h"
#include "xla/shape_util.h"
#include "xla/status_macros.h"
#include "xla/types.h"
#include "tsl/platform/env.h"
namespace xla {
absl::Status TextLiteralWriter::WriteToPath(
const Literal& literal, absl::string_view path) {
std::unique_ptr<tsl::WritableFile> f;
auto s = tsl::Env::Default()->NewWritableFile(std::string(path), &f);
if (!s.ok()) {
return s;
}
s = f->Append(ShapeUtil::HumanString(literal.shape()) + "\n");
if (!s.ok()) {
return s;
}
absl::Status status;
tsl::WritableFile* f_ptr = f.get();
literal.EachCellAsString([f_ptr, &status](absl::Span<const int64_t> indices,
const std::string& value) {
if (!status.ok()) {
return;
}
std::string coordinates =
absl::StrCat("(", absl::StrJoin(indices, ", "), ")");
status = f_ptr->Append(absl::StrCat(coordinates, ": ", value, "\n"));
});
auto ignored = f->Close();
return status;
}
} | #include "xla/text_literal_writer.h"
#include <memory>
#include <string>
#include "xla/literal.h"
#include "xla/literal_util.h"
#include "xla/test.h"
#include "xla/test_helpers.h"
#include "xla/types.h"
#include "tsl/lib/core/status_test_util.h"
#include "tsl/platform/env.h"
namespace xla {
namespace {
TEST(TextLiteralWriterTest, WritesFloatLiteral) {
auto literal = LiteralUtil::CreateR2<float>({
{3.14, 2.17},
{1.23, 4.56},
});
std::string path;
ASSERT_TRUE(tsl::Env::Default()->LocalTempFilename(&path));
ASSERT_IS_OK(TextLiteralWriter::WriteToPath(literal, path));
std::string contents;
TF_ASSERT_OK(tsl::ReadFileToString(tsl::Env::Default(), path, &contents));
const std::string expected = R"(f32[2,2]
(0, 0): 3.14
(0, 1): 2.17
(1, 0): 1.23
(1, 1): 4.56
)";
EXPECT_EQ(expected, contents);
}
}
} |
354 | #ifndef QUICHE_QUIC_CORE_CRYPTO_QUIC_HKDF_H_
#define QUICHE_QUIC_CORE_CRYPTO_QUIC_HKDF_H_
#include <cstdint>
#include <vector>
#include "absl/strings/string_view.h"
#include "quiche/quic/platform/api/quic_export.h"
namespace quic {
class QUICHE_EXPORT QuicHKDF {
public:
QuicHKDF(absl::string_view secret, absl::string_view salt,
absl::string_view info, size_t key_bytes_to_generate,
size_t iv_bytes_to_generate, size_t subkey_secret_bytes_to_generate);
QuicHKDF(absl::string_view secret, absl::string_view salt,
absl::string_view info, size_t client_key_bytes_to_generate,
size_t server_key_bytes_to_generate,
size_t client_iv_bytes_to_generate,
size_t server_iv_bytes_to_generate,
size_t subkey_secret_bytes_to_generate);
~QuicHKDF();
absl::string_view client_write_key() const { return client_write_key_; }
absl::string_view client_write_iv() const { return client_write_iv_; }
absl::string_view server_write_key() const { return server_write_key_; }
absl::string_view server_write_iv() const { return server_write_iv_; }
absl::string_view subkey_secret() const { return subkey_secret_; }
absl::string_view client_hp_key() const { return client_hp_key_; }
absl::string_view server_hp_key() const { return server_hp_key_; }
private:
std::vector<uint8_t> output_;
absl::string_view client_write_key_;
absl::string_view server_write_key_;
absl::string_view client_write_iv_;
absl::string_view server_write_iv_;
absl::string_view subkey_secret_;
absl::string_view client_hp_key_;
absl::string_view server_hp_key_;
};
}
#endif
#include "quiche/quic/core/crypto/quic_hkdf.h"
#include <memory>
#include "absl/strings/string_view.h"
#include "openssl/digest.h"
#include "openssl/hkdf.h"
#include "quiche/quic/platform/api/quic_logging.h"
namespace quic {
const size_t kSHA256HashLength = 32;
const size_t kMaxKeyMaterialSize = kSHA256HashLength * 256;
QuicHKDF::QuicHKDF(absl::string_view secret, absl::string_view salt,
absl::string_view info, size_t key_bytes_to_generate,
size_t iv_bytes_to_generate,
size_t subkey_secret_bytes_to_generate)
: QuicHKDF(secret, salt, info, key_bytes_to_generate, key_bytes_to_generate,
iv_bytes_to_generate, iv_bytes_to_generate,
subkey_secret_bytes_to_generate) {}
QuicHKDF::QuicHKDF(absl::string_view secret, absl::string_view salt,
absl::string_view info, size_t client_key_bytes_to_generate,
size_t server_key_bytes_to_generate,
size_t client_iv_bytes_to_generate,
size_t server_iv_bytes_to_generate,
size_t subkey_secret_bytes_to_generate) {
const size_t material_length =
2 * client_key_bytes_to_generate + client_iv_bytes_to_generate +
2 * server_key_bytes_to_generate + server_iv_bytes_to_generate +
subkey_secret_bytes_to_generate;
QUICHE_DCHECK_LT(material_length, kMaxKeyMaterialSize);
output_.resize(material_length);
if (output_.empty()) {
return;
}
::HKDF(&output_[0], output_.size(), ::EVP_sha256(),
reinterpret_cast<const uint8_t*>(secret.data()), secret.size(),
reinterpret_cast<const uint8_t*>(salt.data()), salt.size(),
reinterpret_cast<const uint8_t*>(info.data()), info.size());
size_t j = 0;
if (client_key_bytes_to_generate) {
client_write_key_ = absl::string_view(reinterpret_cast<char*>(&output_[j]),
client_key_bytes_to_generate);
j += client_key_bytes_to_generate;
}
if (server_key_bytes_to_generate) {
server_write_key_ = absl::string_view(reinterpret_cast<char*>(&output_[j]),
server_key_bytes_to_generate);
j += server_key_bytes_to_generate;
}
if (client_iv_bytes_to_generate) {
client_write_iv_ = absl::string_view(reinterpret_cast<char*>(&output_[j]),
client_iv_bytes_to_generate);
j += client_iv_bytes_to_generate;
}
if (server_iv_bytes_to_generate) {
server_write_iv_ = absl::string_view(reinterpret_cast<char*>(&output_[j]),
server_iv_bytes_to_generate);
j += server_iv_bytes_to_generate;
}
if (subkey_secret_bytes_to_generate) {
subkey_secret_ = absl::string_view(reinterpret_cast<char*>(&output_[j]),
subkey_secret_bytes_to_generate);
j += subkey_secret_bytes_to_generate;
}
if (client_key_bytes_to_generate) {
client_hp_key_ = absl::string_view(reinterpret_cast<char*>(&output_[j]),
client_key_bytes_to_generate);
j += client_key_bytes_to_generate;
}
if (server_key_bytes_to_generate) {
server_hp_key_ = absl::string_view(reinterpret_cast<char*>(&output_[j]),
server_key_bytes_to_generate);
j += server_key_bytes_to_generate;
}
}
QuicHKDF::~QuicHKDF() {}
} | #include "quiche/quic/core/crypto/quic_hkdf.h"
#include <string>
#include "absl/base/macros.h"
#include "absl/strings/escaping.h"
#include "quiche/quic/platform/api/quic_test.h"
namespace quic {
namespace test {
namespace {
struct HKDFInput {
const char* key_hex;
const char* salt_hex;
const char* info_hex;
const char* output_hex;
};
static const HKDFInput kHKDFInputs[] = {
{
"0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b",
"000102030405060708090a0b0c",
"f0f1f2f3f4f5f6f7f8f9",
"3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf340072"
"08d5"
"b887185865",
},
{
"000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122"
"2324"
"25262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f4041424344454647"
"4849"
"4a4b4c4d4e4f",
"606162636465666768696a6b6c6d6e6f707172737475767778797a7b7c7d7e7f808182"
"8384"
"85868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9fa0a1a2a3a4a5a6a7"
"a8a9"
"aaabacadaeaf",
"b0b1b2b3b4b5b6b7b8b9babbbcbdbebfc0c1c2c3c4c5c6c7c8c9cacbcccdcecfd0d1d2"
"d3d4"
"d5d6d7d8d9dadbdcdddedfe0e1e2e3e4e5e6e7e8e9eaebecedeeeff0f1f2f3f4f5f6f7"
"f8f9"
"fafbfcfdfeff",
"b11e398dc80327a1c8e7f78c596a49344f012eda2d4efad8a050cc4c19afa97c59045a"
"99ca"
"c7827271cb41c65e590e09da3275600c2f09b8367793a9aca3db71cc30c58179ec3e87"
"c14c"
"01d5c1f3434f1d87",
},
{
"0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b",
"",
"",
"8da4e775a563c18f715f802a063c5a31b8a11f5c5ee1879ec3454e5f3c738d2d9d2013"
"95fa"
"a4b61a96c8",
},
};
class QuicHKDFTest : public QuicTest {};
TEST_F(QuicHKDFTest, HKDF) {
for (size_t i = 0; i < ABSL_ARRAYSIZE(kHKDFInputs); i++) {
const HKDFInput& test(kHKDFInputs[i]);
SCOPED_TRACE(i);
std::string key;
std::string salt;
std::string info;
std::string expected;
ASSERT_TRUE(absl::HexStringToBytes(test.key_hex, &key));
ASSERT_TRUE(absl::HexStringToBytes(test.salt_hex, &salt));
ASSERT_TRUE(absl::HexStringToBytes(test.info_hex, &info));
ASSERT_TRUE(absl::HexStringToBytes(test.output_hex, &expected));
QuicHKDF hkdf(key, salt, info, expected.size(), 0, 0);
ASSERT_EQ(expected.size(), hkdf.client_write_key().size());
EXPECT_EQ(0, memcmp(expected.data(), hkdf.client_write_key().data(),
expected.size()));
}
}
}
}
} |
355 | #ifndef QUICHE_OBLIVIOUS_HTTP_BUFFERS_OBLIVIOUS_HTTP_REQUEST_H_
#define QUICHE_OBLIVIOUS_HTTP_BUFFERS_OBLIVIOUS_HTTP_REQUEST_H_
#include <memory>
#include <optional>
#include <string>
#include "absl/status/statusor.h"
#include "absl/strings/string_view.h"
#include "openssl/hpke.h"
#include "quiche/oblivious_http/common/oblivious_http_header_key_config.h"
namespace quiche {
class QUICHE_EXPORT ObliviousHttpRequest {
public:
class QUICHE_EXPORT Context {
public:
~Context() = default;
Context(Context&& other) = default;
Context& operator=(Context&& other) = default;
private:
explicit Context(bssl::UniquePtr<EVP_HPKE_CTX> hpke_context,
std::string encapsulated_key);
friend class ObliviousHttpRequest;
friend class ObliviousHttpResponse;
friend class
ObliviousHttpRequest_TestDecapsulateWithSpecAppendixAExample_Test;
friend class ObliviousHttpRequest_TestEncapsulatedRequestStructure_Test;
friend class
ObliviousHttpRequest_TestEncapsulatedOhttpEncryptedPayload_Test;
friend class ObliviousHttpRequest_TestDeterministicSeededOhttpRequest_Test;
friend class ObliviousHttpResponse_EndToEndTestForResponse_Test;
friend class ObliviousHttpResponse_TestEncapsulateWithQuicheRandom_Test;
bssl::UniquePtr<EVP_HPKE_CTX> hpke_context_;
std::string encapsulated_key_;
};
static absl::StatusOr<ObliviousHttpRequest> CreateServerObliviousRequest(
absl::string_view encrypted_data, const EVP_HPKE_KEY& gateway_key,
const ObliviousHttpHeaderKeyConfig& ohttp_key_config,
absl::string_view request_label =
ObliviousHttpHeaderKeyConfig::kOhttpRequestLabel);
static absl::StatusOr<ObliviousHttpRequest> CreateClientObliviousRequest(
std::string plaintext_payload, absl::string_view hpke_public_key,
const ObliviousHttpHeaderKeyConfig& ohttp_key_config,
absl::string_view request_label =
ObliviousHttpHeaderKeyConfig::kOhttpRequestLabel);
static absl::StatusOr<ObliviousHttpRequest> CreateClientWithSeedForTesting(
std::string plaintext_payload, absl::string_view hpke_public_key,
const ObliviousHttpHeaderKeyConfig& ohttp_key_config,
absl::string_view seed,
absl::string_view request_label =
ObliviousHttpHeaderKeyConfig::kOhttpRequestLabel);
ObliviousHttpRequest(ObliviousHttpRequest&& other) = default;
ObliviousHttpRequest& operator=(ObliviousHttpRequest&& other) = default;
~ObliviousHttpRequest() = default;
std::string EncapsulateAndSerialize() const;
absl::string_view GetPlaintextData() const;
Context ReleaseContext() && {
return std::move(oblivious_http_request_context_.value());
}
private:
explicit ObliviousHttpRequest(
bssl::UniquePtr<EVP_HPKE_CTX> hpke_context, std::string encapsulated_key,
const ObliviousHttpHeaderKeyConfig& ohttp_key_config,
std::string req_ciphertext, std::string req_plaintext);
static absl::StatusOr<ObliviousHttpRequest> EncapsulateWithSeed(
std::string plaintext_payload, absl::string_view hpke_public_key,
const ObliviousHttpHeaderKeyConfig& ohttp_key_config,
absl::string_view seed, absl::string_view request_label);
std::optional<Context> oblivious_http_request_context_;
ObliviousHttpHeaderKeyConfig key_config_;
std::string request_ciphertext_;
std::string request_plaintext_;
};
}
#endif
#include "quiche/oblivious_http/buffers/oblivious_http_request.h"
#include <stddef.h>
#include <stdint.h>
#include <memory>
#include <optional>
#include <string>
#include <utility>
#include "absl/memory/memory.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/string_view.h"
#include "openssl/hpke.h"
#include "quiche/common/platform/api/quiche_bug_tracker.h"
#include "quiche/common/platform/api/quiche_logging.h"
#include "quiche/common/quiche_crypto_logging.h"
namespace quiche {
ObliviousHttpRequest::Context::Context(
bssl::UniquePtr<EVP_HPKE_CTX> hpke_context, std::string encapsulated_key)
: hpke_context_(std::move(hpke_context)),
encapsulated_key_(std::move(encapsulated_key)) {}
ObliviousHttpRequest::ObliviousHttpRequest(
bssl::UniquePtr<EVP_HPKE_CTX> hpke_context, std::string encapsulated_key,
const ObliviousHttpHeaderKeyConfig& ohttp_key_config,
std::string req_ciphertext, std::string req_plaintext)
: oblivious_http_request_context_(absl::make_optional(
Context(std::move(hpke_context), std::move(encapsulated_key)))),
key_config_(ohttp_key_config),
request_ciphertext_(std::move(req_ciphertext)),
request_plaintext_(std::move(req_plaintext)) {}
absl::StatusOr<ObliviousHttpRequest>
ObliviousHttpRequest::CreateServerObliviousRequest(
absl::string_view encrypted_data, const EVP_HPKE_KEY& gateway_key,
const ObliviousHttpHeaderKeyConfig& ohttp_key_config,
absl::string_view request_label) {
if (EVP_HPKE_KEY_kem(&gateway_key) == nullptr) {
return absl::InvalidArgumentError(
"Invalid input param. Failed to import gateway_key.");
}
bssl::UniquePtr<EVP_HPKE_CTX> gateway_ctx(EVP_HPKE_CTX_new());
if (gateway_ctx == nullptr) {
return SslErrorAsStatus("Failed to initialize Gateway/Server's Context.");
}
QuicheDataReader reader(encrypted_data);
auto is_hdr_ok = ohttp_key_config.ParseOhttpPayloadHeader(reader);
if (!is_hdr_ok.ok()) {
return is_hdr_ok;
}
size_t enc_key_len = EVP_HPKE_KEM_enc_len(EVP_HPKE_KEY_kem(&gateway_key));
absl::string_view enc_key_received;
if (!reader.ReadStringPiece(&enc_key_received, enc_key_len)) {
return absl::FailedPreconditionError(absl::StrCat(
"Failed to extract encapsulation key of expected len=", enc_key_len,
"from payload."));
}
std::string info =
ohttp_key_config.SerializeRecipientContextInfo(request_label);
if (!EVP_HPKE_CTX_setup_recipient(
gateway_ctx.get(), &gateway_key, ohttp_key_config.GetHpkeKdf(),
ohttp_key_config.GetHpkeAead(),
reinterpret_cast<const uint8_t*>(enc_key_received.data()),
enc_key_received.size(),
reinterpret_cast<const uint8_t*>(info.data()), info.size())) {
return SslErrorAsStatus("Failed to setup recipient context");
}
absl::string_view ciphertext_received = reader.ReadRemainingPayload();
std::string decrypted(ciphertext_received.size(), '\0');
size_t decrypted_len;
if (!EVP_HPKE_CTX_open(
gateway_ctx.get(), reinterpret_cast<uint8_t*>(decrypted.data()),
&decrypted_len, decrypted.size(),
reinterpret_cast<const uint8_t*>(ciphertext_received.data()),
ciphertext_received.size(), nullptr, 0)) {
return SslErrorAsStatus("Failed to decrypt.",
absl::StatusCode::kInvalidArgument);
}
decrypted.resize(decrypted_len);
return ObliviousHttpRequest(
std::move(gateway_ctx), std::string(enc_key_received), ohttp_key_config,
std::string(ciphertext_received), std::move(decrypted));
}
absl::StatusOr<ObliviousHttpRequest>
ObliviousHttpRequest::CreateClientObliviousRequest(
std::string plaintext_payload, absl::string_view hpke_public_key,
const ObliviousHttpHeaderKeyConfig& ohttp_key_config,
absl::string_view request_label) {
return EncapsulateWithSeed(std::move(plaintext_payload), hpke_public_key,
ohttp_key_config, "", request_label);
}
absl::StatusOr<ObliviousHttpRequest>
ObliviousHttpRequest::CreateClientWithSeedForTesting(
std::string plaintext_payload, absl::string_view hpke_public_key,
const ObliviousHttpHeaderKeyConfig& ohttp_key_config,
absl::string_view seed, absl::string_view request_label) {
return ObliviousHttpRequest::EncapsulateWithSeed(
std::move(plaintext_payload), hpke_public_key, ohttp_key_config, seed,
request_label);
}
absl::StatusOr<ObliviousHttpRequest> ObliviousHttpRequest::EncapsulateWithSeed(
std::string plaintext_payload, absl::string_view hpke_public_key,
const ObliviousHttpHeaderKeyConfig& ohttp_key_config,
absl::string_view seed, absl::string_view request_label) {
if (plaintext_payload.empty() || hpke_public_key.empty()) {
return absl::InvalidArgumentError("Invalid input.");
}
bssl::UniquePtr<EVP_HPKE_KEY> client_key(EVP_HPKE_KEY_new());
if (client_key == nullptr) {
return SslErrorAsStatus("Failed to initialize HPKE Client Key.");
}
bssl::UniquePtr<EVP_HPKE_CTX> client_ctx(EVP_HPKE_CTX_new());
if (client_ctx == nullptr) {
return SslErrorAsStatus("Failed to initialize HPKE Client Context.");
}
std::string encapsulated_key(EVP_HPKE_MAX_ENC_LENGTH, '\0');
size_t enc_len;
std::string info =
ohttp_key_config.SerializeRecipientContextInfo(request_label);
if (seed.empty()) {
if (!EVP_HPKE_CTX_setup_sender(
client_ctx.get(),
reinterpret_cast<uint8_t*>(encapsulated_key.data()), &enc_len,
encapsulated_key.size(), ohttp_key_config.GetHpkeKem(),
ohttp_key_config.GetHpkeKdf(), ohttp_key_config.GetHpkeAead(),
reinterpret_cast<const uint8_t*>(hpke_public_key.data()),
hpke_public_key.size(),
reinterpret_cast<const uint8_t*>(info.data()), info.size())) {
return SslErrorAsStatus(
"Failed to setup HPKE context with given public key param "
"hpke_public_key.");
}
} else {
if (!EVP_HPKE_CTX_setup_sender_with_seed_for_testing(
client_ctx.get(),
reinterpret_cast<uint8_t*>(encapsulated_key.data()), &enc_len,
encapsulated_key.size(), ohttp_key_config.GetHpkeKem(),
ohttp_key_config.GetHpkeKdf(), ohttp_key_config.GetHpkeAead(),
reinterpret_cast<const uint8_t*>(hpke_public_key.data()),
hpke_public_key.size(),
reinterpret_cast<const uint8_t*>(info.data()), info.size(),
reinterpret_cast<const uint8_t*>(seed.data()), seed.size())) {
return SslErrorAsStatus(
"Failed to setup HPKE context with given public key param "
"hpke_public_key and seed.");
}
}
encapsulated_key.resize(enc_len);
std::string ciphertext(
plaintext_payload.size() + EVP_HPKE_CTX_max_overhead(client_ctx.get()),
'\0');
size_t ciphertext_len;
if (!EVP_HPKE_CTX_seal(
client_ctx.get(), reinterpret_cast<uint8_t*>(ciphertext.data()),
&ciphertext_len, ciphertext.size(),
reinterpret_cast<const uint8_t*>(plaintext_payload.data()),
plaintext_payload.size(), nullptr, 0)) {
return SslErrorAsStatus(
"Failed to encrypt plaintext_payload with given public key param "
"hpke_public_key.");
}
ciphertext.resize(ciphertext_len);
if (encapsulated_key.empty() || ciphertext.empty()) {
return absl::InternalError(absl::StrCat(
"Failed to generate required data: ",
(encapsulated_key.empty() ? "encapsulated key is empty" : ""),
(ciphertext.empty() ? "encrypted data is empty" : ""), "."));
}
return ObliviousHttpRequest(
std::move(client_ctx), std::move(encapsulated_key), ohttp_key_config,
std::move(ciphertext), std::move(plaintext_payload));
}
std::string ObliviousHttpRequest::EncapsulateAndSerialize() const {
if (!oblivious_http_request_context_.has_value()) {
QUICHE_BUG(ohttp_encapsulate_after_context_extract)
<< "EncapsulateAndSerialize cannot be called after ReleaseContext()";
return "";
}
return absl::StrCat(key_config_.SerializeOhttpPayloadHeader(),
oblivious_http_request_context_->encapsulated_key_,
request_ciphertext_);
}
absl::string_view ObliviousHttpRequest::GetPlaintextData() const {
return request_plaintext_;
}
} | #include "quiche/oblivious_http/buffers/oblivious_http_request.h"
#include <stddef.h>
#include <cstdint>
#include <memory>
#include <string>
#include <utility>
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/escaping.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/string_view.h"
#include "openssl/hkdf.h"
#include "openssl/hpke.h"
#include "quiche/common/platform/api/quiche_test.h"
#include "quiche/common/quiche_data_reader.h"
#include "quiche/oblivious_http/common/oblivious_http_header_key_config.h"
namespace quiche {
namespace {
const uint32_t kHeaderLength = ObliviousHttpHeaderKeyConfig::kHeaderLength;
std::string GetHpkePrivateKey() {
absl::string_view hpke_key_hex =
"b77431ecfa8f4cfc30d6e467aafa06944dffe28cb9dd1409e33a3045f5adc8a1";
std::string hpke_key_bytes;
EXPECT_TRUE(absl::HexStringToBytes(hpke_key_hex, &hpke_key_bytes));
return hpke_key_bytes;
}
std::string GetHpkePublicKey() {
absl::string_view public_key =
"6d21cfe09fbea5122f9ebc2eb2a69fcc4f06408cd54aac934f012e76fcdcef62";
std::string public_key_bytes;
EXPECT_TRUE(absl::HexStringToBytes(public_key, &public_key_bytes));
return public_key_bytes;
}
std::string GetAlternativeHpkePublicKey() {
absl::string_view public_key =
"6d21cfe09fbea5122f9ebc2eb2a69fcc4f06408cd54aac934f012e76fcdcef63";
std::string public_key_bytes;
EXPECT_TRUE(absl::HexStringToBytes(public_key, &public_key_bytes));
return public_key_bytes;
}
std::string GetSeed() {
absl::string_view seed =
"52c4a758a802cd8b936eceea314432798d5baf2d7e9235dc084ab1b9cfa2f736";
std::string seed_bytes;
EXPECT_TRUE(absl::HexStringToBytes(seed, &seed_bytes));
return seed_bytes;
}
std::string GetSeededEncapsulatedKey() {
absl::string_view encapsulated_key =
"37fda3567bdbd628e88668c3c8d7e97d1d1253b6d4ea6d44c150f741f1bf4431";
std::string encapsulated_key_bytes;
EXPECT_TRUE(
absl::HexStringToBytes(encapsulated_key, &encapsulated_key_bytes));
return encapsulated_key_bytes;
}
bssl::UniquePtr<EVP_HPKE_KEY> ConstructHpkeKey(
absl::string_view hpke_key,
const ObliviousHttpHeaderKeyConfig &ohttp_key_config) {
bssl::UniquePtr<EVP_HPKE_KEY> bssl_hpke_key(EVP_HPKE_KEY_new());
EXPECT_NE(bssl_hpke_key, nullptr);
EXPECT_TRUE(EVP_HPKE_KEY_init(
bssl_hpke_key.get(), ohttp_key_config.GetHpkeKem(),
reinterpret_cast<const uint8_t *>(hpke_key.data()), hpke_key.size()));
return bssl_hpke_key;
}
const ObliviousHttpHeaderKeyConfig GetOhttpKeyConfig(uint8_t key_id,
uint16_t kem_id,
uint16_t kdf_id,
uint16_t aead_id) {
auto ohttp_key_config =
ObliviousHttpHeaderKeyConfig::Create(key_id, kem_id, kdf_id, aead_id);
EXPECT_TRUE(ohttp_key_config.ok());
return std::move(ohttp_key_config.value());
}
}
TEST(ObliviousHttpRequest, TestDecapsulateWithSpecAppendixAExample) {
auto ohttp_key_config =
GetOhttpKeyConfig(1, EVP_HPKE_DHKEM_X25519_HKDF_SHA256,
EVP_HPKE_HKDF_SHA256, EVP_HPKE_AES_128_GCM);
constexpr absl::string_view kX25519SecretKey =
"3c168975674b2fa8e465970b79c8dcf09f1c741626480bd4c6162fc5b6a98e1a";
constexpr absl::string_view kEncapsulatedRequest =
"010020000100014b28f881333e7c164ffc499ad9796f877f4e1051ee6d31bad19dec96c2"
"08b4726374e469135906992e1268c594d2a10c695d858c40a026e7965e7d86b83dd440b2"
"c0185204b4d63525";
std::string encapsulated_request_bytes;
ASSERT_TRUE(absl::HexStringToBytes(kEncapsulatedRequest,
&encapsulated_request_bytes));
std::string x25519_secret_key_bytes;
ASSERT_TRUE(
absl::HexStringToBytes(kX25519SecretKey, &x25519_secret_key_bytes));
auto instance = ObliviousHttpRequest::CreateServerObliviousRequest(
encapsulated_request_bytes,
*(ConstructHpkeKey(x25519_secret_key_bytes, ohttp_key_config)),
ohttp_key_config);
ASSERT_TRUE(instance.ok());
auto decrypted = instance->GetPlaintextData();
constexpr absl::string_view kExpectedEphemeralPublicKey =
"4b28f881333e7c164ffc499ad9796f877f4e1051ee6d31bad19dec96c208b472";
std::string expected_ephemeral_public_key_bytes;
ASSERT_TRUE(absl::HexStringToBytes(kExpectedEphemeralPublicKey,
&expected_ephemeral_public_key_bytes));
auto oblivious_request_context = std::move(instance.value()).ReleaseContext();
EXPECT_EQ(oblivious_request_context.encapsulated_key_,
expected_ephemeral_public_key_bytes);
constexpr absl::string_view kExpectedBinaryHTTPMessage =
"00034745540568747470730b6578616d706c652e636f6d012f";
std::string expected_binary_http_message_bytes;
ASSERT_TRUE(absl::HexStringToBytes(kExpectedBinaryHTTPMessage,
&expected_binary_http_message_bytes));
EXPECT_EQ(decrypted, expected_binary_http_message_bytes);
}
TEST(ObliviousHttpRequest, TestEncapsulatedRequestStructure) {
uint8_t test_key_id = 7;
uint16_t test_kem_id = EVP_HPKE_DHKEM_X25519_HKDF_SHA256;
uint16_t test_kdf_id = EVP_HPKE_HKDF_SHA256;
uint16_t test_aead_id = EVP_HPKE_AES_256_GCM;
std::string plaintext = "test";
auto instance = ObliviousHttpRequest::CreateClientObliviousRequest(
plaintext, GetHpkePublicKey(),
GetOhttpKeyConfig(test_key_id, test_kem_id, test_kdf_id, test_aead_id));
ASSERT_TRUE(instance.ok());
auto payload_bytes = instance->EncapsulateAndSerialize();
EXPECT_GE(payload_bytes.size(), kHeaderLength);
QuicheDataReader reader(payload_bytes);
uint8_t key_id;
EXPECT_TRUE(reader.ReadUInt8(&key_id));
EXPECT_EQ(key_id, test_key_id);
uint16_t kem_id;
EXPECT_TRUE(reader.ReadUInt16(&kem_id));
EXPECT_EQ(kem_id, test_kem_id);
uint16_t kdf_id;
EXPECT_TRUE(reader.ReadUInt16(&kdf_id));
EXPECT_EQ(kdf_id, test_kdf_id);
uint16_t aead_id;
EXPECT_TRUE(reader.ReadUInt16(&aead_id));
EXPECT_EQ(aead_id, test_aead_id);
auto client_request_context = std::move(instance.value()).ReleaseContext();
auto client_encapsulated_key = client_request_context.encapsulated_key_;
EXPECT_EQ(client_encapsulated_key.size(), X25519_PUBLIC_VALUE_LEN);
auto enc_key_plus_ciphertext = payload_bytes.substr(kHeaderLength);
auto packed_encapsulated_key =
enc_key_plus_ciphertext.substr(0, X25519_PUBLIC_VALUE_LEN);
EXPECT_EQ(packed_encapsulated_key, client_encapsulated_key);
auto ciphertext = enc_key_plus_ciphertext.substr(X25519_PUBLIC_VALUE_LEN);
EXPECT_GE(ciphertext.size(), plaintext.size());
}
TEST(ObliviousHttpRequest, TestDeterministicSeededOhttpRequest) {
auto ohttp_key_config =
GetOhttpKeyConfig(4, EVP_HPKE_DHKEM_X25519_HKDF_SHA256,
EVP_HPKE_HKDF_SHA256, EVP_HPKE_AES_256_GCM);
auto encapsulated = ObliviousHttpRequest::CreateClientWithSeedForTesting(
"test", GetHpkePublicKey(), ohttp_key_config, GetSeed());
ASSERT_TRUE(encapsulated.ok());
auto encapsulated_request = encapsulated->EncapsulateAndSerialize();
auto ohttp_request_context = std::move(encapsulated.value()).ReleaseContext();
EXPECT_EQ(ohttp_request_context.encapsulated_key_,
GetSeededEncapsulatedKey());
absl::string_view expected_encrypted_request =
"9f37cfed07d0111ecd2c34f794671759bcbd922a";
std::string expected_encrypted_request_bytes;
ASSERT_TRUE(absl::HexStringToBytes(expected_encrypted_request,
&expected_encrypted_request_bytes));
EXPECT_NE(ohttp_request_context.hpke_context_, nullptr);
size_t encapsulated_key_len = EVP_HPKE_KEM_enc_len(
EVP_HPKE_CTX_kem(ohttp_request_context.hpke_context_.get()));
int encrypted_payload_offset = kHeaderLength + encapsulated_key_len;
EXPECT_EQ(encapsulated_request.substr(encrypted_payload_offset),
expected_encrypted_request_bytes);
}
TEST(ObliviousHttpRequest,
TestSeededEncapsulatedKeySamePlaintextsSameCiphertexts) {
auto ohttp_key_config =
GetOhttpKeyConfig(8, EVP_HPKE_DHKEM_X25519_HKDF_SHA256,
EVP_HPKE_HKDF_SHA256, EVP_HPKE_AES_256_GCM);
auto req_with_same_plaintext_1 =
ObliviousHttpRequest::CreateClientWithSeedForTesting(
"same plaintext", GetHpkePublicKey(), ohttp_key_config, GetSeed());
ASSERT_TRUE(req_with_same_plaintext_1.ok());
auto ciphertext_1 = req_with_same_plaintext_1->EncapsulateAndSerialize();
auto req_with_same_plaintext_2 =
ObliviousHttpRequest::CreateClientWithSeedForTesting(
"same plaintext", GetHpkePublicKey(), ohttp_key_config, GetSeed());
ASSERT_TRUE(req_with_same_plaintext_2.ok());
auto ciphertext_2 = req_with_same_plaintext_2->EncapsulateAndSerialize();
EXPECT_EQ(ciphertext_1, ciphertext_2);
}
TEST(ObliviousHttpRequest,
TestSeededEncapsulatedKeyDifferentPlaintextsDifferentCiphertexts) {
auto ohttp_key_config =
GetOhttpKeyConfig(8, EVP_HPKE_DHKEM_X25519_HKDF_SHA256,
EVP_HPKE_HKDF_SHA256, EVP_HPKE_AES_256_GCM);
auto req_with_different_plaintext_1 =
ObliviousHttpRequest::CreateClientWithSeedForTesting(
"different 1", GetHpkePublicKey(), ohttp_key_config, GetSeed());
ASSERT_TRUE(req_with_different_plaintext_1.ok());
auto ciphertext_1 = req_with_different_plaintext_1->EncapsulateAndSerialize();
auto req_with_different_plaintext_2 =
ObliviousHttpRequest::CreateClientWithSeedForTesting(
"different 2", GetHpkePublicKey(), ohttp_key_config, GetSeed());
ASSERT_TRUE(req_with_different_plaintext_2.ok());
auto ciphertext_2 = req_with_different_plaintext_2->EncapsulateAndSerialize();
EXPECT_NE(ciphertext_1, ciphertext_2);
}
TEST(ObliviousHttpRequest, TestInvalidInputsOnClientSide) {
auto ohttp_key_config =
GetOhttpKeyConfig(30, EVP_HPKE_DHKEM_X25519_HKDF_SHA256,
EVP_HPKE_HKDF_SHA256, EVP_HPKE_AES_256_GCM);
EXPECT_EQ(ObliviousHttpRequest::CreateClientObliviousRequest(
"", GetHpkePublicKey(), ohttp_key_config)
.status()
.code(),
absl::StatusCode::kInvalidArgument);
EXPECT_EQ(ObliviousHttpRequest::CreateClientObliviousRequest(
"some plaintext",
"", ohttp_key_config)
.status()
.code(),
absl::StatusCode::kInvalidArgument);
}
TEST(ObliviousHttpRequest, TestInvalidInputsOnServerSide) {
auto ohttp_key_config =
GetOhttpKeyConfig(4, EVP_HPKE_DHKEM_X25519_HKDF_SHA256,
EVP_HPKE_HKDF_SHA256, EVP_HPKE_AES_256_GCM);
EXPECT_EQ(ObliviousHttpRequest::CreateServerObliviousRequest(
"",
*(ConstructHpkeKey(GetHpkePrivateKey(), ohttp_key_config)),
ohttp_key_config)
.status()
.code(),
absl::StatusCode::kInvalidArgument);
EXPECT_EQ(ObliviousHttpRequest::CreateServerObliviousRequest(
absl::StrCat(ohttp_key_config.SerializeOhttpPayloadHeader(),
GetSeededEncapsulatedKey(),
"9f37cfed07d0111ecd2c34f794671759bcbd922a"),
{}, ohttp_key_config)
.status()
.code(),
absl::StatusCode::kInvalidArgument);
}
TEST(ObliviousHttpRequest, EndToEndTestForRequest) {
auto ohttp_key_config =
GetOhttpKeyConfig(5, EVP_HPKE_DHKEM_X25519_HKDF_SHA256,
EVP_HPKE_HKDF_SHA256, EVP_HPKE_AES_256_GCM);
auto encapsulate = ObliviousHttpRequest::CreateClientObliviousRequest(
"test", GetHpkePublicKey(), ohttp_key_config);
ASSERT_TRUE(encapsulate.ok());
auto oblivious_request = encapsulate->EncapsulateAndSerialize();
auto decapsulate = ObliviousHttpRequest::CreateServerObliviousRequest(
oblivious_request,
*(ConstructHpkeKey(GetHpkePrivateKey(), ohttp_key_config)),
ohttp_key_config);
ASSERT_TRUE(decapsulate.ok());
auto decrypted = decapsulate->GetPlaintextData();
EXPECT_EQ(decrypted, "test");
}
TEST(ObliviousHttpRequest, EndToEndTestForRequestWithWrongKey) {
auto ohttp_key_config =
GetOhttpKeyConfig(5, EVP_HPKE_DHKEM_X25519_HKDF_SHA256,
EVP_HPKE_HKDF_SHA256, EVP_HPKE_AES_256_GCM);
auto encapsulate = ObliviousHttpRequest::CreateClientObliviousRequest(
"test", GetAlternativeHpkePublicKey(), ohttp_key_config);
ASSERT_TRUE(encapsulate.ok());
auto oblivious_request = encapsulate->EncapsulateAndSerialize();
auto decapsulate = ObliviousHttpRequest::CreateServerObliviousRequest(
oblivious_request,
*(ConstructHpkeKey(GetHpkePrivateKey(), ohttp_key_config)),
ohttp_key_config);
EXPECT_EQ(decapsulate.status().code(), absl::StatusCode::kInvalidArgument);
}
} |
356 | #ifndef THIRD_PARTY_CEL_CPP_EVAL_PUBLIC_STRUCTS_CEL_PROTO_DESCRIPTOR_POOL_BUILDER_H_
#define THIRD_PARTY_CEL_CPP_EVAL_PUBLIC_STRUCTS_CEL_PROTO_DESCRIPTOR_POOL_BUILDER_H_
#include "google/protobuf/descriptor.pb.h"
#include "google/protobuf/descriptor.h"
#include "absl/status/status.h"
namespace google::api::expr::runtime {
absl::Status AddStandardMessageTypesToDescriptorPool(
google::protobuf::DescriptorPool& descriptor_pool);
google::protobuf::FileDescriptorSet GetStandardMessageTypesFileDescriptorSet();
}
#endif
#include "eval/public/structs/cel_proto_descriptor_pool_builder.h"
#include <string>
#include "google/protobuf/any.pb.h"
#include "google/protobuf/duration.pb.h"
#include "google/protobuf/empty.pb.h"
#include "google/protobuf/field_mask.pb.h"
#include "google/protobuf/struct.pb.h"
#include "google/protobuf/timestamp.pb.h"
#include "google/protobuf/wrappers.pb.h"
#include "absl/container/flat_hash_map.h"
#include "internal/proto_util.h"
#include "internal/status_macros.h"
namespace google::api::expr::runtime {
namespace {
template <class MessageType>
absl::Status AddOrValidateMessageType(google::protobuf::DescriptorPool& descriptor_pool) {
const google::protobuf::Descriptor* descriptor = MessageType::descriptor();
if (descriptor_pool.FindMessageTypeByName(descriptor->full_name()) !=
nullptr) {
return internal::ValidateStandardMessageType<MessageType>(descriptor_pool);
}
google::protobuf::FileDescriptorProto file_descriptor_proto;
descriptor->file()->CopyTo(&file_descriptor_proto);
if (descriptor_pool.BuildFile(file_descriptor_proto) == nullptr) {
return absl::InternalError(
absl::StrFormat("Failed to add descriptor '%s' to descriptor pool",
descriptor->full_name()));
}
return absl::OkStatus();
}
template <class MessageType>
void AddStandardMessageTypeToMap(
absl::flat_hash_map<std::string, google::protobuf::FileDescriptorProto>& fdmap) {
const google::protobuf::Descriptor* descriptor = MessageType::descriptor();
if (fdmap.contains(descriptor->file()->name())) return;
descriptor->file()->CopyTo(&fdmap[descriptor->file()->name()]);
}
}
absl::Status AddStandardMessageTypesToDescriptorPool(
google::protobuf::DescriptorPool& descriptor_pool) {
CEL_RETURN_IF_ERROR(
AddOrValidateMessageType<google::protobuf::Any>(descriptor_pool));
CEL_RETURN_IF_ERROR(
AddOrValidateMessageType<google::protobuf::BoolValue>(descriptor_pool));
CEL_RETURN_IF_ERROR(
AddOrValidateMessageType<google::protobuf::BytesValue>(descriptor_pool));
CEL_RETURN_IF_ERROR(
AddOrValidateMessageType<google::protobuf::DoubleValue>(descriptor_pool));
CEL_RETURN_IF_ERROR(
AddOrValidateMessageType<google::protobuf::Duration>(descriptor_pool));
CEL_RETURN_IF_ERROR(
AddOrValidateMessageType<google::protobuf::FloatValue>(descriptor_pool));
CEL_RETURN_IF_ERROR(
AddOrValidateMessageType<google::protobuf::Int32Value>(descriptor_pool));
CEL_RETURN_IF_ERROR(
AddOrValidateMessageType<google::protobuf::Int64Value>(descriptor_pool));
CEL_RETURN_IF_ERROR(
AddOrValidateMessageType<google::protobuf::ListValue>(descriptor_pool));
CEL_RETURN_IF_ERROR(
AddOrValidateMessageType<google::protobuf::StringValue>(descriptor_pool));
CEL_RETURN_IF_ERROR(
AddOrValidateMessageType<google::protobuf::Struct>(descriptor_pool));
CEL_RETURN_IF_ERROR(
AddOrValidateMessageType<google::protobuf::Timestamp>(descriptor_pool));
CEL_RETURN_IF_ERROR(
AddOrValidateMessageType<google::protobuf::UInt32Value>(descriptor_pool));
CEL_RETURN_IF_ERROR(
AddOrValidateMessageType<google::protobuf::UInt64Value>(descriptor_pool));
CEL_RETURN_IF_ERROR(
AddOrValidateMessageType<google::protobuf::Value>(descriptor_pool));
CEL_RETURN_IF_ERROR(
AddOrValidateMessageType<google::protobuf::FieldMask>(descriptor_pool));
CEL_RETURN_IF_ERROR(
AddOrValidateMessageType<google::protobuf::Empty>(descriptor_pool));
return absl::OkStatus();
}
google::protobuf::FileDescriptorSet GetStandardMessageTypesFileDescriptorSet() {
absl::flat_hash_map<std::string, google::protobuf::FileDescriptorProto> files;
AddStandardMessageTypeToMap<google::protobuf::Any>(files);
AddStandardMessageTypeToMap<google::protobuf::BoolValue>(files);
AddStandardMessageTypeToMap<google::protobuf::BytesValue>(files);
AddStandardMessageTypeToMap<google::protobuf::DoubleValue>(files);
AddStandardMessageTypeToMap<google::protobuf::Duration>(files);
AddStandardMessageTypeToMap<google::protobuf::FloatValue>(files);
AddStandardMessageTypeToMap<google::protobuf::Int32Value>(files);
AddStandardMessageTypeToMap<google::protobuf::Int64Value>(files);
AddStandardMessageTypeToMap<google::protobuf::ListValue>(files);
AddStandardMessageTypeToMap<google::protobuf::StringValue>(files);
AddStandardMessageTypeToMap<google::protobuf::Struct>(files);
AddStandardMessageTypeToMap<google::protobuf::Timestamp>(files);
AddStandardMessageTypeToMap<google::protobuf::UInt32Value>(files);
AddStandardMessageTypeToMap<google::protobuf::UInt64Value>(files);
AddStandardMessageTypeToMap<google::protobuf::Value>(files);
AddStandardMessageTypeToMap<google::protobuf::FieldMask>(files);
AddStandardMessageTypeToMap<google::protobuf::Empty>(files);
google::protobuf::FileDescriptorSet fdset;
for (const auto& [name, fdproto] : files) {
*fdset.add_file() = fdproto;
}
return fdset;
}
} | #include "eval/public/structs/cel_proto_descriptor_pool_builder.h"
#include <string>
#include <vector>
#include "google/protobuf/any.pb.h"
#include "absl/container/flat_hash_map.h"
#include "eval/testutil/test_message.pb.h"
#include "internal/testing.h"
namespace google::api::expr::runtime {
namespace {
using testing::HasSubstr;
using testing::UnorderedElementsAre;
using cel::internal::StatusIs;
TEST(DescriptorPoolUtilsTest, PopulatesEmptyDescriptorPool) {
google::protobuf::DescriptorPool descriptor_pool;
ASSERT_EQ(descriptor_pool.FindMessageTypeByName("google.protobuf.Any"),
nullptr);
ASSERT_EQ(descriptor_pool.FindMessageTypeByName("google.protobuf.BoolValue"),
nullptr);
ASSERT_EQ(descriptor_pool.FindMessageTypeByName("google.protobuf.BytesValue"),
nullptr);
ASSERT_EQ(
descriptor_pool.FindMessageTypeByName("google.protobuf.DoubleValue"),
nullptr);
ASSERT_EQ(descriptor_pool.FindMessageTypeByName("google.protobuf.Duration"),
nullptr);
ASSERT_EQ(descriptor_pool.FindMessageTypeByName("google.protobuf.FloatValue"),
nullptr);
ASSERT_EQ(descriptor_pool.FindMessageTypeByName("google.protobuf.Int32Value"),
nullptr);
ASSERT_EQ(descriptor_pool.FindMessageTypeByName("google.protobuf.Int64Value"),
nullptr);
ASSERT_EQ(descriptor_pool.FindMessageTypeByName("google.protobuf.ListValue"),
nullptr);
ASSERT_EQ(
descriptor_pool.FindMessageTypeByName("google.protobuf.StringValue"),
nullptr);
ASSERT_EQ(descriptor_pool.FindMessageTypeByName("google.protobuf.Struct"),
nullptr);
ASSERT_EQ(descriptor_pool.FindMessageTypeByName("google.protobuf.Timestamp"),
nullptr);
ASSERT_EQ(
descriptor_pool.FindMessageTypeByName("google.protobuf.UInt32Value"),
nullptr);
ASSERT_EQ(
descriptor_pool.FindMessageTypeByName("google.protobuf.UInt64Value"),
nullptr);
ASSERT_EQ(descriptor_pool.FindMessageTypeByName("google.protobuf.Value"),
nullptr);
ASSERT_EQ(descriptor_pool.FindMessageTypeByName("google.protobuf.FieldMask"),
nullptr);
ASSERT_OK(AddStandardMessageTypesToDescriptorPool(descriptor_pool));
EXPECT_NE(descriptor_pool.FindMessageTypeByName("google.protobuf.Any"),
nullptr);
EXPECT_NE(descriptor_pool.FindMessageTypeByName("google.protobuf.BoolValue"),
nullptr);
EXPECT_NE(descriptor_pool.FindMessageTypeByName("google.protobuf.BytesValue"),
nullptr);
EXPECT_NE(
descriptor_pool.FindMessageTypeByName("google.protobuf.DoubleValue"),
nullptr);
EXPECT_NE(descriptor_pool.FindMessageTypeByName("google.protobuf.Duration"),
nullptr);
EXPECT_NE(descriptor_pool.FindMessageTypeByName("google.protobuf.FloatValue"),
nullptr);
EXPECT_NE(descriptor_pool.FindMessageTypeByName("google.protobuf.Int32Value"),
nullptr);
EXPECT_NE(descriptor_pool.FindMessageTypeByName("google.protobuf.Int64Value"),
nullptr);
EXPECT_NE(descriptor_pool.FindMessageTypeByName("google.protobuf.ListValue"),
nullptr);
EXPECT_NE(
descriptor_pool.FindMessageTypeByName("google.protobuf.StringValue"),
nullptr);
EXPECT_NE(descriptor_pool.FindMessageTypeByName("google.protobuf.Struct"),
nullptr);
EXPECT_NE(descriptor_pool.FindMessageTypeByName("google.protobuf.Timestamp"),
nullptr);
EXPECT_NE(
descriptor_pool.FindMessageTypeByName("google.protobuf.UInt32Value"),
nullptr);
EXPECT_NE(
descriptor_pool.FindMessageTypeByName("google.protobuf.UInt64Value"),
nullptr);
EXPECT_NE(descriptor_pool.FindMessageTypeByName("google.protobuf.Value"),
nullptr);
EXPECT_NE(descriptor_pool.FindMessageTypeByName("google.protobuf.FieldMask"),
nullptr);
EXPECT_NE(descriptor_pool.FindMessageTypeByName("google.protobuf.Empty"),
nullptr);
}
TEST(DescriptorPoolUtilsTest, AcceptsPreAddedStandardTypes) {
google::protobuf::DescriptorPool descriptor_pool;
for (auto proto_name : std::vector<std::string>{
"google.protobuf.Any", "google.protobuf.BoolValue",
"google.protobuf.BytesValue", "google.protobuf.DoubleValue",
"google.protobuf.Duration", "google.protobuf.FloatValue",
"google.protobuf.Int32Value", "google.protobuf.Int64Value",
"google.protobuf.ListValue", "google.protobuf.StringValue",
"google.protobuf.Struct", "google.protobuf.Timestamp",
"google.protobuf.UInt32Value", "google.protobuf.UInt64Value",
"google.protobuf.Value", "google.protobuf.FieldMask",
"google.protobuf.Empty"}) {
const google::protobuf::Descriptor* descriptor =
google::protobuf::DescriptorPool::generated_pool()->FindMessageTypeByName(
proto_name);
ASSERT_NE(descriptor, nullptr);
google::protobuf::FileDescriptorProto file_descriptor_proto;
descriptor->file()->CopyTo(&file_descriptor_proto);
ASSERT_NE(descriptor_pool.BuildFile(file_descriptor_proto), nullptr);
}
EXPECT_OK(AddStandardMessageTypesToDescriptorPool(descriptor_pool));
}
TEST(DescriptorPoolUtilsTest, RejectsModifiedStandardType) {
google::protobuf::DescriptorPool descriptor_pool;
const google::protobuf::Descriptor* descriptor =
google::protobuf::DescriptorPool::generated_pool()->FindMessageTypeByName(
"google.protobuf.Duration");
ASSERT_NE(descriptor, nullptr);
google::protobuf::FileDescriptorProto file_descriptor_proto;
descriptor->file()->CopyTo(&file_descriptor_proto);
google::protobuf::FieldDescriptorProto seconds_desc_proto;
google::protobuf::FieldDescriptorProto nanos_desc_proto;
descriptor->FindFieldByName("seconds")->CopyTo(&seconds_desc_proto);
descriptor->FindFieldByName("nanos")->CopyTo(&nanos_desc_proto);
nanos_desc_proto.set_name("millis");
file_descriptor_proto.mutable_message_type(0)->clear_field();
*file_descriptor_proto.mutable_message_type(0)->add_field() =
seconds_desc_proto;
*file_descriptor_proto.mutable_message_type(0)->add_field() =
nanos_desc_proto;
descriptor_pool.BuildFile(file_descriptor_proto);
EXPECT_THAT(
AddStandardMessageTypesToDescriptorPool(descriptor_pool),
StatusIs(absl::StatusCode::kFailedPrecondition, HasSubstr("differs")));
}
TEST(DescriptorPoolUtilsTest, GetStandardMessageTypesFileDescriptorSet) {
google::protobuf::FileDescriptorSet fdset = GetStandardMessageTypesFileDescriptorSet();
std::vector<std::string> file_names;
for (int i = 0; i < fdset.file_size(); ++i) {
file_names.push_back(fdset.file(i).name());
}
EXPECT_THAT(
file_names,
UnorderedElementsAre(
"google/protobuf/any.proto", "google/protobuf/struct.proto",
"google/protobuf/wrappers.proto", "google/protobuf/timestamp.proto",
"google/protobuf/duration.proto", "google/protobuf/field_mask.proto",
"google/protobuf/empty.proto"));
}
}
} |
357 | #ifndef THIRD_PARTY_CEL_CPP_COMMON_TYPES_LIST_TYPE_H_
#define THIRD_PARTY_CEL_CPP_COMMON_TYPES_LIST_TYPE_H_
#include <ostream>
#include <string>
#include <utility>
#include "absl/base/attributes.h"
#include "absl/strings/string_view.h"
#include "absl/types/span.h"
#include "common/memory.h"
#include "common/native_type.h"
#include "common/type_kind.h"
namespace cel {
class Type;
class TypeView;
class ListType;
class ListTypeView;
namespace common_internal {
struct ListTypeData;
}
class ListType final {
public:
using view_alternative_type = ListTypeView;
static constexpr TypeKind kKind = TypeKind::kList;
static constexpr absl::string_view kName = "list";
explicit ListType(ListTypeView other);
ListType(MemoryManagerRef memory_manager, Type element);
ListType();
ListType(const ListType&) = default;
ListType(ListType&&) = default;
ListType& operator=(const ListType&) = default;
ListType& operator=(ListType&&) = default;
constexpr TypeKind kind() const { return kKind; }
constexpr absl::string_view name() const ABSL_ATTRIBUTE_LIFETIME_BOUND {
return kName;
}
std::string DebugString() const;
absl::Span<const Type> parameters() const ABSL_ATTRIBUTE_LIFETIME_BOUND;
void swap(ListType& other) noexcept {
using std::swap;
swap(data_, other.data_);
}
const Type& element() const ABSL_ATTRIBUTE_LIFETIME_BOUND;
private:
friend class ListTypeView;
friend struct NativeTypeTraits<ListType>;
Shared<const common_internal::ListTypeData> data_;
};
inline void swap(ListType& lhs, ListType& rhs) noexcept { lhs.swap(rhs); }
bool operator==(const ListType& lhs, const ListType& rhs);
inline bool operator!=(const ListType& lhs, const ListType& rhs) {
return !operator==(lhs, rhs);
}
template <typename H>
H AbslHashValue(H state, const ListType& type);
inline std::ostream& operator<<(std::ostream& out, const ListType& type) {
return out << type.DebugString();
}
template <>
struct NativeTypeTraits<ListType> final {
static bool SkipDestructor(const ListType& type) {
return NativeType::SkipDestructor(type.data_);
}
};
class ListTypeView final {
public:
using alternative_type = ListType;
static constexpr TypeKind kKind = ListType::kKind;
static constexpr absl::string_view kName = ListType::kName;
ListTypeView(const ListType& type ABSL_ATTRIBUTE_LIFETIME_BOUND) noexcept;
ListTypeView& operator=(const ListType& type ABSL_ATTRIBUTE_LIFETIME_BOUND) {
data_ = type.data_;
return *this;
}
ListTypeView& operator=(ListType&&) = delete;
ListTypeView();
ListTypeView(const ListTypeView&) = default;
ListTypeView(ListTypeView&&) = default;
ListTypeView& operator=(const ListTypeView&) = default;
ListTypeView& operator=(ListTypeView&&) = default;
constexpr TypeKind kind() const { return kKind; }
constexpr absl::string_view name() const { return kName; }
std::string DebugString() const;
absl::Span<const Type> parameters() const;
void swap(ListTypeView& other) noexcept {
using std::swap;
swap(data_, other.data_);
}
const Type& element() const;
private:
friend class ListType;
SharedView<const common_internal::ListTypeData> data_;
};
inline void swap(ListTypeView& lhs, ListTypeView& rhs) noexcept {
lhs.swap(rhs);
}
bool operator==(ListTypeView lhs, ListTypeView rhs);
inline bool operator!=(ListTypeView lhs, ListTypeView rhs) {
return !operator==(lhs, rhs);
}
template <typename H>
H AbslHashValue(H state, ListTypeView type);
inline std::ostream& operator<<(std::ostream& out, ListTypeView type) {
return out << type.DebugString();
}
}
#endif
#include <string>
#include "absl/strings/str_cat.h"
#include "common/type.h"
namespace cel {
std::string ListType::DebugString() const {
return absl::StrCat("list<", element().DebugString(), ">");
}
std::string ListTypeView::DebugString() const {
return absl::StrCat("list<", element().DebugString(), ">");
}
} | #include <sstream>
#include <string>
#include "absl/hash/hash.h"
#include "absl/types/optional.h"
#include "common/casting.h"
#include "common/memory.h"
#include "common/memory_testing.h"
#include "common/native_type.h"
#include "common/type.h"
#include "internal/testing.h"
namespace cel {
namespace {
using testing::An;
using testing::Ne;
using testing::TestParamInfo;
using testing::TestWithParam;
TEST(ListType, Default) {
ListType list_type;
EXPECT_EQ(list_type.element(), DynType());
}
TEST(ListTypeView, Default) {
ListTypeView list_type;
EXPECT_EQ(list_type.element(), DynType());
}
class ListTypeTest : public common_internal::ThreadCompatibleMemoryTest<> {};
TEST_P(ListTypeTest, Kind) {
EXPECT_EQ(ListType(memory_manager(), BoolType()).kind(), ListType::kKind);
EXPECT_EQ(Type(ListType(memory_manager(), BoolType())).kind(),
ListType::kKind);
}
TEST_P(ListTypeTest, Name) {
EXPECT_EQ(ListType(memory_manager(), BoolType()).name(), ListType::kName);
EXPECT_EQ(Type(ListType(memory_manager(), BoolType())).name(),
ListType::kName);
}
TEST_P(ListTypeTest, DebugString) {
{
std::ostringstream out;
out << ListType(memory_manager(), BoolType());
EXPECT_EQ(out.str(), "list<bool>");
}
{
std::ostringstream out;
out << Type(ListType(memory_manager(), BoolType()));
EXPECT_EQ(out.str(), "list<bool>");
}
}
TEST_P(ListTypeTest, Hash) {
EXPECT_EQ(absl::HashOf(ListType(memory_manager(), BoolType())),
absl::HashOf(ListType(memory_manager(), BoolType())));
}
TEST_P(ListTypeTest, Equal) {
EXPECT_EQ(ListType(memory_manager(), BoolType()),
ListType(memory_manager(), BoolType()));
EXPECT_EQ(Type(ListType(memory_manager(), BoolType())),
ListType(memory_manager(), BoolType()));
EXPECT_EQ(ListType(memory_manager(), BoolType()),
Type(ListType(memory_manager(), BoolType())));
EXPECT_EQ(Type(ListType(memory_manager(), BoolType())),
Type(ListType(memory_manager(), BoolType())));
}
TEST_P(ListTypeTest, NativeTypeId) {
EXPECT_EQ(NativeTypeId::Of(ListType(memory_manager(), BoolType())),
NativeTypeId::For<ListType>());
EXPECT_EQ(NativeTypeId::Of(Type(ListType(memory_manager(), BoolType()))),
NativeTypeId::For<ListType>());
}
TEST_P(ListTypeTest, InstanceOf) {
EXPECT_TRUE(InstanceOf<ListType>(ListType(memory_manager(), BoolType())));
EXPECT_TRUE(
InstanceOf<ListType>(Type(ListType(memory_manager(), BoolType()))));
}
TEST_P(ListTypeTest, Cast) {
EXPECT_THAT(Cast<ListType>(ListType(memory_manager(), BoolType())),
An<ListType>());
EXPECT_THAT(Cast<ListType>(Type(ListType(memory_manager(), BoolType()))),
An<ListType>());
}
TEST_P(ListTypeTest, As) {
EXPECT_THAT(As<ListType>(ListType(memory_manager(), BoolType())),
Ne(absl::nullopt));
EXPECT_THAT(As<ListType>(Type(ListType(memory_manager(), BoolType()))),
Ne(absl::nullopt));
}
INSTANTIATE_TEST_SUITE_P(
ListTypeTest, ListTypeTest,
::testing::Values(MemoryManagement::kPooling,
MemoryManagement::kReferenceCounting),
ListTypeTest::ToString);
class ListTypeViewTest : public common_internal::ThreadCompatibleMemoryTest<> {
};
TEST_P(ListTypeViewTest, Kind) {
auto type = ListType(memory_manager(), BoolType());
EXPECT_EQ(ListTypeView(type).kind(), ListTypeView::kKind);
EXPECT_EQ(TypeView(ListTypeView(type)).kind(), ListTypeView::kKind);
}
TEST_P(ListTypeViewTest, Name) {
auto type = ListType(memory_manager(), BoolType());
EXPECT_EQ(ListTypeView(type).name(), ListTypeView::kName);
EXPECT_EQ(TypeView(ListTypeView(type)).name(), ListTypeView::kName);
}
TEST_P(ListTypeViewTest, DebugString) {
auto type = ListType(memory_manager(), BoolType());
{
std::ostringstream out;
out << ListTypeView(type);
EXPECT_EQ(out.str(), "list<bool>");
}
{
std::ostringstream out;
out << TypeView(ListTypeView(type));
EXPECT_EQ(out.str(), "list<bool>");
}
}
TEST_P(ListTypeViewTest, Hash) {
auto type = ListType(memory_manager(), BoolType());
EXPECT_EQ(absl::HashOf(ListTypeView(type)), absl::HashOf(ListTypeView(type)));
EXPECT_EQ(absl::HashOf(ListTypeView(type)), absl::HashOf(ListType(type)));
}
TEST_P(ListTypeViewTest, Equal) {
auto type = ListType(memory_manager(), BoolType());
EXPECT_EQ(ListTypeView(type), ListTypeView(type));
EXPECT_EQ(TypeView(ListTypeView(type)), ListTypeView(type));
EXPECT_EQ(ListTypeView(type), TypeView(ListTypeView(type)));
EXPECT_EQ(TypeView(ListTypeView(type)), TypeView(ListTypeView(type)));
EXPECT_EQ(ListTypeView(type), ListType(type));
EXPECT_EQ(TypeView(ListTypeView(type)), ListType(type));
EXPECT_EQ(TypeView(ListTypeView(type)), Type(ListType(type)));
EXPECT_EQ(ListType(type), ListTypeView(type));
EXPECT_EQ(ListType(type), ListTypeView(type));
EXPECT_EQ(ListType(type), TypeView(ListTypeView(type)));
EXPECT_EQ(Type(ListType(type)), TypeView(ListTypeView(type)));
EXPECT_EQ(ListTypeView(type), ListType(type));
}
TEST_P(ListTypeViewTest, NativeTypeId) {
auto type = ListType(memory_manager(), BoolType());
EXPECT_EQ(NativeTypeId::Of(ListTypeView(type)),
NativeTypeId::For<ListTypeView>());
EXPECT_EQ(NativeTypeId::Of(TypeView(ListTypeView(type))),
NativeTypeId::For<ListTypeView>());
}
TEST_P(ListTypeViewTest, InstanceOf) {
auto type = ListType(memory_manager(), BoolType());
EXPECT_TRUE(InstanceOf<ListTypeView>(ListTypeView(type)));
EXPECT_TRUE(InstanceOf<ListTypeView>(TypeView(ListTypeView(type))));
}
TEST_P(ListTypeViewTest, Cast) {
auto type = ListType(memory_manager(), BoolType());
EXPECT_THAT(Cast<ListTypeView>(ListTypeView(type)), An<ListTypeView>());
EXPECT_THAT(Cast<ListTypeView>(TypeView(ListTypeView(type))),
An<ListTypeView>());
}
TEST_P(ListTypeViewTest, As) {
auto type = ListType(memory_manager(), BoolType());
EXPECT_THAT(As<ListTypeView>(ListTypeView(type)), Ne(absl::nullopt));
EXPECT_THAT(As<ListTypeView>(TypeView(ListTypeView(type))),
Ne(absl::nullopt));
}
INSTANTIATE_TEST_SUITE_P(
ListTypeViewTest, ListTypeViewTest,
::testing::Values(MemoryManagement::kPooling,
MemoryManagement::kReferenceCounting),
ListTypeViewTest::ToString);
}
} |
358 | #ifndef TENSORFLOW_CC_EXPERIMENTAL_LIBTF_MODULE_H_
#define TENSORFLOW_CC_EXPERIMENTAL_LIBTF_MODULE_H_
#include "tensorflow/cc/experimental/libexport/load.h"
#include "tensorflow/cc/experimental/libtf/runtime/runtime.h"
#include "tensorflow/core/platform/statusor.h"
#include "tensorflow/core/protobuf/saved_object_graph.pb.h"
namespace tf {
namespace libtf {
namespace impl {
tensorflow::StatusOr<Handle> BuildSavedUserObject(
tensorflow::SavedObject saved_object_proto);
tensorflow::StatusOr<std::vector<Handle>> BuildObjects(
tensorflow::libexport::TFPackage& tf_package);
tensorflow::StatusOr<Handle> BuildProgram(
runtime::Runtime runtime, tensorflow::libexport::TFPackage& tf_package);
}
}
}
#endif
#include "tensorflow/cc/experimental/libtf/module.h"
#include <string>
#include "tensorflow/core/platform/errors.h"
#include "tensorflow/core/protobuf/saved_object_graph.pb.h"
namespace tf {
namespace libtf {
namespace impl {
using tensorflow::libexport::TFPackage;
using tf::libtf::runtime::Runtime;
tensorflow::StatusOr<std::vector<Handle>> BuildObjects(TFPackage& tf_package) {
std::vector<Handle> objects;
const tensorflow::SavedObjectGraph object_graph = tf_package.GetObjectGraph();
for (auto& node : object_graph.nodes()) {
if (node.kind_case() == tensorflow::SavedObject::kUserObject) {
tensorflow::StatusOr<Handle> result = BuildSavedUserObject(node);
if (result.ok()) {
objects.push_back(*result);
} else {
return result.status();
}
}
}
return objects;
}
tensorflow::StatusOr<Handle> BuildSavedUserObject(
tensorflow::SavedObject saved_object_proto) {
if (saved_object_proto.kind_case() != tensorflow::SavedObject::kUserObject) {
return tensorflow::errors::InvalidArgument("Not a UserObject.");
}
std::string identifier = saved_object_proto.user_object().identifier();
if (identifier == "trackable_list_wrapper") {
tf::libtf::List user_list;
return user_list;
}
if (identifier == "trackable_dict_wrapper") {
tf::libtf::Dictionary user_dict;
return user_dict;
}
if (identifier == "signature_map") {
tf::libtf::Dictionary signature_map;
return signature_map;
}
if (identifier == "_generic_user_object") {
tf::libtf::Dictionary user_object;
return user_object;
}
return tensorflow::errors::Unimplemented(absl::StrCat(
"UserObject with identifier '", identifier, "' not implemented."));
}
tensorflow::Status RegisterConcreteFunctions(Runtime runtime,
TFPackage tf_package) {
return tensorflow::errors::Unimplemented("Not implemented.");
}
tensorflow::Status InitializeVariables(Runtime runtime, TFPackage tf_package,
std::vector<Handle> objects) {
return tensorflow::errors::Unimplemented("Not implemented.");
}
tensorflow::Status SetupPolymorphicFunctions(Runtime runtime,
TFPackage tf_package,
std::vector<Handle> objects) {
return tensorflow::errors::Unimplemented("Not implemented.");
}
tensorflow::Status SetupFunctionCaptures(Runtime runtime, TFPackage tf_package,
std::vector<Handle> objects) {
return tensorflow::errors::Unimplemented("Not implemented.");
}
tensorflow::StatusOr<Handle> BuildObjectHierarchy(TFPackage tf_package,
std::vector<Handle> objects) {
return tensorflow::errors::Unimplemented("Not implemented.");
}
tensorflow::StatusOr<Handle> BuildProgram(Runtime runtime,
TFPackage& tf_package) {
return tensorflow::errors::Unimplemented("Not implemented.");
}
}
}
} | #include "tensorflow/cc/experimental/libtf/module.h"
#include <string>
#include "tensorflow/cc/experimental/libtf/runtime/core/core.h"
#include "tensorflow/core/lib/core/status_test_util.h"
#include "tensorflow/core/platform/resource_loader.h"
#include "tensorflow/core/platform/status_matchers.h"
#include "tensorflow/core/platform/statusor.h"
#include "tensorflow/core/platform/test.h"
#include "tensorflow/core/protobuf/error_codes.pb.h"
#include "tensorflow/core/protobuf/saved_object_graph.pb.h"
namespace tf {
namespace libtf {
namespace impl {
using ::tensorflow::libexport::TFPackage;
using ::tensorflow::testing::StatusIs;
using ::tf::libtf::runtime::Runtime;
TEST(ModuleTest, TestStubbedFunctions) {
Runtime runtime = runtime::core::Runtime();
TFPackage tf_package;
tensorflow::StatusOr<Handle> result = BuildProgram(runtime, tf_package);
ASSERT_FALSE(result.status().ok());
}
TEST(ModuleTest, TestBuildObjectsDataStructures) {
const std::string path = tensorflow::GetDataDependencyFilepath(
"tensorflow/cc/experimental/libtf/tests/testdata/data-structure-model");
TF_ASSERT_OK_AND_ASSIGN(TFPackage tf_package, TFPackage::Load(path));
TF_ASSERT_OK_AND_ASSIGN(std::vector<Handle> objects,
BuildObjects(tf_package));
EXPECT_EQ(objects.size(), 7);
TF_ASSERT_OK_AND_ASSIGN(tf::libtf::Dictionary node,
Cast<tf::libtf::Dictionary>(objects.front()));
for (unsigned int i = 1; i < 4; i++) {
TF_ASSERT_OK_AND_ASSIGN(tf::libtf::List node,
Cast<tf::libtf::List>(objects.at(i)));
}
for (unsigned int i = 4; i < 7; i++) {
TF_ASSERT_OK_AND_ASSIGN(tf::libtf::Dictionary node,
Cast<tf::libtf::Dictionary>(objects.at(i)));
}
}
TEST(ModuleTest, TestBuildEmptyList) {
tensorflow::SavedObject saved_object_proto;
const std::string pb_txt = R"pb(
user_object {
identifier: "trackable_list_wrapper"
version { producer: 1 min_consumer: 1 }
}
)pb";
ASSERT_TRUE(::tensorflow::protobuf::TextFormat::ParseFromString(
pb_txt, &saved_object_proto));
TF_ASSERT_OK_AND_ASSIGN(Handle result,
BuildSavedUserObject(saved_object_proto));
EXPECT_EQ(Cast<tf::libtf::List>(result)->size(), 0);
}
TEST(ModuleTest, TestBuildEmptyDict) {
tensorflow::SavedObject saved_object_proto;
const std::string pb_txt = R"pb(
user_object {
identifier: "trackable_dict_wrapper"
version { producer: 1 min_consumer: 1 }
}
)pb";
ASSERT_TRUE(::tensorflow::protobuf::TextFormat::ParseFromString(
pb_txt, &saved_object_proto));
TF_ASSERT_OK_AND_ASSIGN(Handle result,
BuildSavedUserObject(saved_object_proto));
EXPECT_EQ(Cast<tf::libtf::Dictionary>(result)->size(), 0);
}
TEST(ModuleTest, TestBuildSignatureMap) {
tensorflow::SavedObject saved_object_proto;
const std::string pb_txt = R"pb(
user_object {
identifier: "signature_map"
version { producer: 1 min_consumer: 1 }
}
)pb";
ASSERT_TRUE(::tensorflow::protobuf::TextFormat::ParseFromString(
pb_txt, &saved_object_proto));
TF_ASSERT_OK_AND_ASSIGN(Handle result,
BuildSavedUserObject(saved_object_proto));
EXPECT_EQ(Cast<tf::libtf::Dictionary>(result)->size(), 0);
}
TEST(ModuleTest, TestUnimplementedUserObject) {
tensorflow::SavedObject saved_object_proto;
const std::string pb_txt = R"pb(
user_object {
identifier: "foo"
version { producer: 1 min_consumer: 1 }
}
)pb";
ASSERT_TRUE(::tensorflow::protobuf::TextFormat::ParseFromString(
pb_txt, &saved_object_proto));
EXPECT_THAT(
BuildSavedUserObject(saved_object_proto),
StatusIs(tensorflow::error::UNIMPLEMENTED, ::testing::HasSubstr("foo")));
}
}
}
} |
359 | #ifndef TENSORFLOW_CORE_PLATFORM_TENSOR_CODING_H_
#define TENSORFLOW_CORE_PLATFORM_TENSOR_CODING_H_
#include <string>
#include "tensorflow/core/platform/platform.h"
#include "tensorflow/core/platform/protobuf.h"
#include "tensorflow/core/platform/refcount.h"
#include "tensorflow/core/platform/stringpiece.h"
#include "tensorflow/core/platform/types.h"
namespace tensorflow {
namespace port {
void AssignRefCounted(StringPiece src, core::RefCounted* obj, std::string* out);
inline void CopyToArray(const std::string& src, char* dst) {
memcpy(dst, src.data(), src.size());
}
inline void CopySubrangeToArray(const std::string& src, size_t pos, size_t n,
char* dst) {
if (pos >= src.size()) return;
memcpy(dst, src.data() + pos, std::min(n, src.size() - pos));
}
void EncodeStringList(const tstring* strings, int64_t n, std::string* out);
bool DecodeStringList(const std::string& src, tstring* strings, int64_t n);
void CopyFromArray(std::string* s, const char* base, size_t bytes);
class StringListEncoder {
public:
virtual ~StringListEncoder() = default;
virtual void Append(const protobuf::MessageLite& m) = 0;
virtual void Append(const std::string& s) = 0;
virtual void Finalize() = 0;
};
class StringListDecoder {
public:
virtual ~StringListDecoder() = default;
virtual bool ReadSizes(std::vector<uint32>* sizes) = 0;
virtual const char* Data(uint32 size) = 0;
};
std::unique_ptr<StringListEncoder> NewStringListEncoder(string* out);
std::unique_ptr<StringListDecoder> NewStringListDecoder(const string& in);
#if defined(TENSORFLOW_PROTOBUF_USES_CORD)
void AssignRefCounted(StringPiece src, core::RefCounted* obj, absl::Cord* out);
inline void CopyToArray(const absl::Cord& src, char* dst) {
src.CopyToArray(dst);
}
inline void CopySubrangeToArray(const absl::Cord& src, int64_t pos, int64_t n,
char* dst) {
src.Subcord(pos, n).CopyToArray(dst);
}
void EncodeStringList(const tstring* strings, int64_t n, absl::Cord* out);
bool DecodeStringList(const absl::Cord& src, std::string* strings, int64_t n);
bool DecodeStringList(const absl::Cord& src, tstring* strings, int64_t n);
void CopyFromArray(absl::Cord* c, const char* base, size_t bytes);
std::unique_ptr<StringListEncoder> NewStringListEncoder(absl::Cord* out);
std::unique_ptr<StringListDecoder> NewStringListDecoder(const absl::Cord& in);
#endif
}
}
#endif
#include "tensorflow/core/platform/tensor_coding.h"
#include <vector>
#include "tensorflow/core/platform/coding.h"
#include "tensorflow/core/platform/protobuf.h"
#include "tensorflow/core/platform/strcat.h"
#include "tensorflow/core/platform/stringpiece.h"
#if defined(TENSORFLOW_PROTOBUF_USES_CORD)
#include "strings/cord_varint.h"
#endif
namespace tensorflow {
namespace port {
void AssignRefCounted(StringPiece src, core::RefCounted* obj, string* out) {
out->assign(src.data(), src.size());
}
void EncodeStringList(const tstring* strings, int64_t n, string* out) {
out->clear();
for (int i = 0; i < n; ++i) {
core::PutVarint32(out, strings[i].size());
}
for (int i = 0; i < n; ++i) {
out->append(strings[i]);
}
}
bool DecodeStringList(const string& src, tstring* strings, int64_t n) {
std::vector<uint32> sizes(n);
StringPiece reader(src);
int64_t tot = 0;
for (auto& v : sizes) {
if (!core::GetVarint32(&reader, &v)) return false;
tot += v;
}
if (tot != static_cast<int64_t>(reader.size())) {
return false;
}
tstring* data = strings;
for (int64_t i = 0; i < n; ++i, ++data) {
auto size = sizes[i];
if (size > reader.size()) {
return false;
}
data->assign(reader.data(), size);
reader.remove_prefix(size);
}
return true;
}
void CopyFromArray(string* s, const char* base, size_t bytes) {
s->assign(base, bytes);
}
class StringListEncoderImpl : public StringListEncoder {
public:
explicit StringListEncoderImpl(string* out) : out_(out) {}
~StringListEncoderImpl() override = default;
void Append(const protobuf::MessageLite& m) override {
core::PutVarint32(out_, m.ByteSizeLong());
tensorflow::string serialized_message;
m.AppendToString(&serialized_message);
strings::StrAppend(&rest_, serialized_message);
}
void Append(const string& s) override {
core::PutVarint32(out_, s.length());
strings::StrAppend(&rest_, s);
}
void Finalize() override { strings::StrAppend(out_, rest_); }
private:
string* out_;
string rest_;
};
class StringListDecoderImpl : public StringListDecoder {
public:
explicit StringListDecoderImpl(const string& in) : reader_(in) {}
~StringListDecoderImpl() override = default;
bool ReadSizes(std::vector<uint32>* sizes) override {
int64_t total = 0;
for (auto& size : *sizes) {
if (!core::GetVarint32(&reader_, &size)) return false;
total += size;
}
if (total != static_cast<int64_t>(reader_.size())) {
return false;
}
return true;
}
const char* Data(uint32 size) override {
const char* data = reader_.data();
reader_.remove_prefix(size);
return data;
}
private:
StringPiece reader_;
};
std::unique_ptr<StringListEncoder> NewStringListEncoder(string* out) {
return std::unique_ptr<StringListEncoder>(new StringListEncoderImpl(out));
}
std::unique_ptr<StringListDecoder> NewStringListDecoder(const string& in) {
return std::unique_ptr<StringListDecoder>(new StringListDecoderImpl(in));
}
#if defined(TENSORFLOW_PROTOBUF_USES_CORD)
void AssignRefCounted(StringPiece src, core::RefCounted* obj, absl::Cord* out) {
obj->Ref();
*out = absl::MakeCordFromExternal(src, [obj] { obj->Unref(); });
}
void EncodeStringList(const tstring* strings, int64_t n, absl::Cord* out) {
out->Clear();
for (int i = 0; i < n; ++i) {
::strings::CordAppendVarint(strings[i].size(), out);
}
for (int i = 0; i < n; ++i) {
out->Append(strings[i]);
}
}
bool DecodeStringList(const absl::Cord& src, string* strings, int64_t n) {
std::vector<uint32> sizes(n);
CordReader reader(src);
int64_t tot = 0;
for (auto& v : sizes) {
if (!::strings::CordReaderReadVarint(&reader, &v)) return false;
tot += v;
}
if (tot != reader.Available()) {
return false;
}
string* data = strings;
for (int i = 0; i < n; ++i, ++data) {
auto size = sizes[i];
if (size > reader.Available()) {
return false;
}
gtl::STLStringResizeUninitialized(data, size);
reader.ReadN(size, gtl::string_as_array(data));
}
return true;
}
bool DecodeStringList(const absl::Cord& src, tstring* strings, int64_t n) {
std::vector<uint32> sizes(n);
CordReader reader(src);
int64_t tot = 0;
for (auto& v : sizes) {
if (!::strings::CordReaderReadVarint(&reader, &v)) return false;
tot += v;
}
if (tot != reader.Available()) {
return false;
}
tstring* data = strings;
for (int i = 0; i < n; ++i, ++data) {
auto size = sizes[i];
if (size > reader.Available()) {
return false;
}
data->resize_uninitialized(size);
reader.ReadN(size, data->data());
}
return true;
}
void CopyFromArray(absl::Cord* c, const char* base, size_t bytes) {
*c = absl::string_view(base, bytes);
}
class CordStringListEncoderImpl : public StringListEncoder {
public:
explicit CordStringListEncoderImpl(absl::Cord* out) : out_(out) {}
~CordStringListEncoderImpl() override = default;
void Append(const protobuf::MessageLite& m) override {
::strings::CordAppendVarint(m.ByteSizeLong(), out_);
m.AppendToString(&rest_);
}
void Append(const string& s) override {
::strings::CordAppendVarint(s.length(), out_);
rest_.append(s.data(), s.size());
}
void Finalize() override { out_->Append(rest_); }
private:
absl::Cord* out_;
string rest_;
};
class CordStringListDecoderImpl : public StringListDecoder {
public:
explicit CordStringListDecoderImpl(const absl::Cord& in) : reader_(in) {}
~CordStringListDecoderImpl() override = default;
bool ReadSizes(std::vector<uint32>* sizes) override {
int64_t total = 0;
for (auto& size : *sizes) {
if (!::strings::CordReaderReadVarint(&reader_, &size)) return false;
total += size;
}
if (total != static_cast<int64_t>(reader_.Available())) {
return false;
}
return true;
}
const char* Data(uint32 size) override {
tmp_.resize(size);
reader_.ReadN(size, tmp_.data());
return tmp_.data();
}
private:
CordReader reader_;
std::vector<char> tmp_;
};
std::unique_ptr<StringListEncoder> NewStringListEncoder(absl::Cord* out) {
return std::unique_ptr<StringListEncoder>(new CordStringListEncoderImpl(out));
}
std::unique_ptr<StringListDecoder> NewStringListDecoder(const absl::Cord& in) {
return std::unique_ptr<StringListDecoder>(new CordStringListDecoderImpl(in));
}
#endif
}
} | #include "tensorflow/core/distributed_runtime/tensor_coding.h"
#include "tensorflow/core/framework/device_attributes.pb.h"
#include "tensorflow/core/framework/device_base.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor_testutil.h"
#include "tensorflow/core/lib/gtl/inlined_vector.h"
#include "tensorflow/core/lib/strings/strcat.h"
#include "tensorflow/core/platform/env.h"
#include "tensorflow/core/platform/protobuf.h"
#include "tensorflow/core/platform/test.h"
#include "tensorflow/core/platform/test_benchmark.h"
#include "tensorflow/core/protobuf/worker.pb.h"
#include "tensorflow/core/public/session_options.h"
namespace tensorflow {
class DummyDevice : public DeviceBase {
public:
explicit DummyDevice(Env* env) : DeviceBase(env) {
attr_.set_device_type("CPU");
}
const DeviceAttributes& attributes() const override { return attr_; }
Allocator* GetAllocator(AllocatorAttributes attr) override {
return cpu_allocator();
}
private:
DeviceAttributes attr_;
};
class StringSource : public TensorResponse::Source {
public:
explicit StringSource(const string* s, int block_size)
: s_(s), stream_(nullptr), block_size_(block_size) {}
~StringSource() override { DeleteStream(); }
protobuf::io::ZeroCopyInputStream* contents() override {
DeleteStream();
stream_ = new (&space_)
protobuf::io::ArrayInputStream(s_->data(), s_->size(), block_size_);
return stream_;
}
void DeleteStream() {
if (stream_) {
stream_->~ArrayInputStream();
}
}
private:
const string* s_;
protobuf::io::ArrayInputStream* stream_;
char space_[sizeof(protobuf::io::ArrayInputStream)];
int block_size_;
};
class TensorResponseTest : public ::testing::Test {
public:
void Validate(const Tensor& src, bool is_dead, bool use_tensor_content) {
RecvTensorResponse proto;
proto.set_is_dead(is_dead);
proto.set_send_start_micros(123456);
if (use_tensor_content) {
src.AsProtoTensorContent(proto.mutable_tensor());
} else {
src.AsProtoField(proto.mutable_tensor());
}
string encoded;
proto.AppendToString(&encoded);
StringSource source(&encoded, 1024);
TensorResponse response;
DummyDevice cpu_device(Env::Default());
response.InitAlloc(&cpu_device, AllocatorAttributes());
for (int i = 0; i < 2; i++) {
Status s = response.ParseFrom(&source);
EXPECT_TRUE(s.ok());
const RecvTensorResponse& meta = response.metadata();
EXPECT_EQ(meta.is_dead(), is_dead);
EXPECT_EQ(meta.send_start_micros(), 123456);
const Tensor& result = response.tensor();
EXPECT_EQ(result.dtype(), src.dtype());
EXPECT_EQ(result.shape().DebugString(), src.shape().DebugString());
EXPECT_EQ(result.DebugString(), src.DebugString());
}
}
template <typename T>
void DoTest(DataType dt) {
gtl::InlinedVector<T, 4> v;
LOG(ERROR) << "DT: " << static_cast<int>(dt);
for (int elems = 0; elems <= 10000; elems++) {
if (elems < 100 || (elems % 1000 == 0)) {
Tensor a(dt, TensorShape({1, static_cast<int64_t>(v.size())}));
test::FillValues<T>(&a, v);
Validate(a, (elems == 0), true);
}
v.push_back(static_cast<T>(elems));
}
}
void DoTestForStrings(DataType dt) {
gtl::InlinedVector<tstring, 4> v;
LOG(ERROR) << "DT: string";
for (int elems = 0; elems <= 10000; elems++) {
if (elems < 100 || (elems % 1000 == 0)) {
Tensor a(dt, TensorShape({1, static_cast<int64_t>(v.size())}));
test::FillValues<tstring>(&a, v);
Validate(a, (elems == 0), true);
}
v.push_back(strings::StrCat("This is string ", elems));
}
}
};
TEST_F(TensorResponseTest, Simple) {
DoTest<float>(DT_FLOAT);
DoTest<double>(DT_DOUBLE);
DoTest<int32>(DT_INT32);
DoTest<uint16>(DT_UINT16);
DoTest<uint8>(DT_UINT8);
DoTest<int16>(DT_INT16);
DoTest<int8>(DT_INT8);
DoTest<complex64>(DT_COMPLEX64);
DoTest<complex128>(DT_COMPLEX128);
DoTest<int64_t>(DT_INT64);
DoTest<bool>(DT_BOOL);
DoTest<qint8>(DT_QINT8);
DoTest<quint8>(DT_QUINT8);
DoTest<qint16>(DT_QINT16);
DoTest<quint16>(DT_QUINT16);
DoTest<qint32>(DT_QINT32);
DoTest<bfloat16>(DT_BFLOAT16);
DoTest<Eigen::half>(DT_HALF);
}
TEST_F(TensorResponseTest, StringTensor) { DoTestForStrings(DT_STRING); }
string MakeFloatTensorTestCase(int num_elems) {
std::vector<int8> v(num_elems);
for (int i = 0; i < num_elems; i++) {
v[i] = i % 10;
}
Tensor src(DT_INT8, TensorShape({1, static_cast<int64_t>(v.size())}));
test::FillValues<int8>(&src, v);
RecvTensorResponse proto;
proto.set_is_dead(false);
proto.set_send_start_micros(123456);
src.AsProtoTensorContent(proto.mutable_tensor());
string encoded;
proto.AppendToString(&encoded);
return encoded;
}
static void BM_TensorResponse(::testing::benchmark::State& state) {
const int arg = state.range(0);
string encoded = MakeFloatTensorTestCase(arg);
DummyDevice cpu_device(Env::Default());
size_t bytes = 0;
for (auto i : state) {
TensorResponse response;
response.InitAlloc(&cpu_device, AllocatorAttributes());
StringSource source(&encoded, -1);
Status s = response.ParseFrom(&source);
bytes = response.tensor().TotalBytes();
}
state.SetLabel(strings::StrCat("Bytes: ", bytes));
}
BENCHMARK(BM_TensorResponse)->Arg(0)->Arg(1000)->Arg(100000);
static void BM_TensorViaTensorProto(::testing::benchmark::State& state) {
const int arg = state.range(0);
std::string encoded = MakeFloatTensorTestCase(arg);
size_t bytes = 0;
for (auto s : state) {
RecvTensorResponse r;
r.ParseFromString(encoded);
Tensor t;
CHECK(t.FromProto(r.tensor()));
bytes = t.TotalBytes();
}
state.SetLabel(strings::StrCat("Bytes: ", bytes));
}
BENCHMARK(BM_TensorViaTensorProto)->Arg(0)->Arg(1000)->Arg(100000);
} |
360 | #ifndef TENSORFLOW_CORE_GRAPPLER_OPTIMIZERS_DATA_SHUFFLE_AND_REPEAT_FUSION_H_
#define TENSORFLOW_CORE_GRAPPLER_OPTIMIZERS_DATA_SHUFFLE_AND_REPEAT_FUSION_H_
#include "tensorflow/core/grappler/optimizers/data/optimizer_base.h"
namespace tensorflow {
namespace grappler {
class ShuffleAndRepeatFusion : public TFDataOptimizerBase {
public:
ShuffleAndRepeatFusion() = default;
~ShuffleAndRepeatFusion() override = default;
string name() const override { return "shuffle_and_repeat_fusion"; };
bool UsesFunctionLibrary() const override { return false; }
Status Init(
const tensorflow::RewriterConfig_CustomGraphOptimizer* config) override {
return absl::OkStatus();
}
Status OptimizeAndCollectStats(Cluster* cluster, const GrapplerItem& item,
GraphDef* output,
OptimizationStats* stats) override;
};
}
}
#endif
#include "tensorflow/core/grappler/optimizers/data/shuffle_and_repeat_fusion.h"
#include "absl/container/flat_hash_set.h"
#include "tensorflow/core/framework/node_def.pb.h"
#include "tensorflow/core/framework/node_def_util.h"
#include "tensorflow/core/grappler/clusters/cluster.h"
#include "tensorflow/core/grappler/grappler_item.h"
#include "tensorflow/core/grappler/mutable_graph_view.h"
#include "tensorflow/core/grappler/op_types.h"
#include "tensorflow/core/grappler/optimizers/custom_graph_optimizer_registry.h"
#include "tensorflow/core/grappler/optimizers/data/graph_utils.h"
#include "tensorflow/core/grappler/utils.h"
#include "tensorflow/core/platform/protobuf.h"
#include "tensorflow/core/platform/strcat.h"
namespace tensorflow {
namespace grappler {
namespace {
constexpr char kShuffleDataset[] = "ShuffleDataset";
constexpr char kShuffleDatasetV2[] = "ShuffleDatasetV2";
constexpr char kShuffleDatasetV3[] = "ShuffleDatasetV3";
constexpr char kRepeatDataset[] = "RepeatDataset";
constexpr char kShuffleAndRepeatDataset[] = "ShuffleAndRepeatDataset";
constexpr char kShuffleAndRepeatDatasetV2[] = "ShuffleAndRepeatDatasetV2";
constexpr char kReshuffleEachIteration[] = "reshuffle_each_iteration";
Status FuseShuffleV1AndRepeat(const NodeDef& shuffle_node,
const NodeDef& repeat_node,
MutableGraphView* graph, GraphDef* output,
NodeDef* fused_node) {
fused_node->set_op(kShuffleAndRepeatDataset);
graph_utils::SetUniqueGraphNodeName(kShuffleAndRepeatDataset, output,
fused_node);
fused_node->add_input(shuffle_node.input(0));
fused_node->add_input(shuffle_node.input(1));
fused_node->add_input(shuffle_node.input(2));
fused_node->add_input(shuffle_node.input(3));
fused_node->add_input(repeat_node.input(1));
graph_utils::CopyShapesAndTypesAttrs(shuffle_node, fused_node);
graph_utils::CopyAttribute(kReshuffleEachIteration, shuffle_node, fused_node);
graph_utils::MaybeSetFusedMetadata(shuffle_node, repeat_node, fused_node);
return absl::OkStatus();
}
Status FuseShuffleV2AndRepeat(const NodeDef& shuffle_node,
const NodeDef& repeat_node,
MutableGraphView* graph, GraphDef* output,
NodeDef* fused_node) {
fused_node->set_op(kShuffleAndRepeatDatasetV2);
graph_utils::SetUniqueGraphNodeName(kShuffleAndRepeatDatasetV2, output,
fused_node);
NodeDef zero_node = *graph_utils::AddScalarConstNode<int64_t>(0, graph);
fused_node->add_input(shuffle_node.input(0));
fused_node->add_input(shuffle_node.input(1));
fused_node->add_input(zero_node.name());
fused_node->add_input(zero_node.name());
fused_node->add_input(repeat_node.input(1));
fused_node->add_input(shuffle_node.input(2));
graph_utils::CopyShapesAndTypesAttrs(shuffle_node, fused_node);
(*fused_node->mutable_attr())[kReshuffleEachIteration].set_b(true);
graph_utils::MaybeSetFusedMetadata(shuffle_node, repeat_node, fused_node);
return absl::OkStatus();
}
Status FuseShuffleV3AndRepeat(const NodeDef& shuffle_node,
const NodeDef& repeat_node,
MutableGraphView* graph, GraphDef* output,
NodeDef* fused_node) {
fused_node->set_op(kShuffleAndRepeatDatasetV2);
graph_utils::SetUniqueGraphNodeName(kShuffleAndRepeatDataset, output,
fused_node);
fused_node->add_input(shuffle_node.input(0));
fused_node->add_input(shuffle_node.input(1));
fused_node->add_input(shuffle_node.input(2));
fused_node->add_input(shuffle_node.input(3));
fused_node->add_input(repeat_node.input(1));
fused_node->add_input(shuffle_node.input(4));
graph_utils::CopyShapesAndTypesAttrs(shuffle_node, fused_node);
graph_utils::CopyAttribute(kReshuffleEachIteration, shuffle_node, fused_node);
graph_utils::MaybeSetFusedMetadata(shuffle_node, repeat_node, fused_node);
return absl::OkStatus();
}
}
Status ShuffleAndRepeatFusion::OptimizeAndCollectStats(
Cluster* cluster, const GrapplerItem& item, GraphDef* output,
OptimizationStats* stats) {
*output = item.graph;
MutableGraphView graph(output);
absl::flat_hash_set<string> nodes_to_delete;
for (const NodeDef& repeat_node : item.graph.node()) {
if (repeat_node.op() != kRepeatDataset) {
continue;
}
const NodeDef& shuffle_node =
*graph_utils::GetInputNode(repeat_node, graph);
NodeDef fused_node;
if (shuffle_node.op() == kShuffleDataset) {
TF_RETURN_IF_ERROR(FuseShuffleV1AndRepeat(shuffle_node, repeat_node,
&graph, output, &fused_node));
} else if (shuffle_node.op() == kShuffleDatasetV2) {
TF_RETURN_IF_ERROR(FuseShuffleV2AndRepeat(shuffle_node, repeat_node,
&graph, output, &fused_node));
} else if (shuffle_node.op() == kShuffleDatasetV3) {
TF_RETURN_IF_ERROR(FuseShuffleV3AndRepeat(shuffle_node, repeat_node,
&graph, output, &fused_node));
} else {
continue;
}
NodeDef& shuffle_and_repeat_node = *graph.AddNode(std::move(fused_node));
TF_RETURN_IF_ERROR(graph.UpdateFanouts(repeat_node.name(),
shuffle_and_repeat_node.name()));
TF_RETURN_IF_ERROR(graph.UpdateFanouts(shuffle_node.name(),
shuffle_and_repeat_node.name()));
const auto nodes_to_preserve = item.NodesToPreserve();
if (nodes_to_preserve.find(shuffle_node.name()) ==
nodes_to_preserve.end() &&
nodes_to_preserve.find(repeat_node.name()) == nodes_to_preserve.end()) {
nodes_to_delete.insert(shuffle_node.name());
nodes_to_delete.insert(repeat_node.name());
}
stats->num_changes++;
}
TF_RETURN_IF_ERROR(graph.DeleteNodes(nodes_to_delete));
return absl::OkStatus();
}
REGISTER_GRAPH_OPTIMIZER_AS(ShuffleAndRepeatFusion,
"shuffle_and_repeat_fusion");
}
} | #include "tensorflow/core/grappler/optimizers/data/shuffle_and_repeat_fusion.h"
#include "tensorflow/core/framework/attr_value_util.h"
#include "tensorflow/core/grappler/grappler_item.h"
#include "tensorflow/core/grappler/optimizers/data/graph_utils.h"
#include "tensorflow/core/lib/core/status_test_util.h"
#include "tensorflow/core/platform/test.h"
namespace tensorflow {
namespace grappler {
namespace {
constexpr char kOutputShapes[] = "output_shapes";
constexpr char kOutputTypes[] = "output_types";
constexpr char kReshuffleEachIteration[] = "reshuffle_each_iteration";
TEST(ShuffleAndRepeatFusionTest, FuseShuffleV1AndRepeat) {
GrapplerItem item;
MutableGraphView graph(&item.graph);
std::vector<std::pair<string, AttrValue>> common_attrs(2);
AttrValue shapes_attr;
SetAttrValue(kOutputShapes, &shapes_attr);
common_attrs[0] = std::make_pair(kOutputShapes, shapes_attr);
AttrValue types_attr;
SetAttrValue(kOutputTypes, &types_attr);
common_attrs[1] = std::make_pair(kOutputTypes, types_attr);
NodeDef *start_node = graph_utils::AddScalarConstNode<int64_t>(0, &graph);
NodeDef *stop_node = graph_utils::AddScalarConstNode<int64_t>(10, &graph);
NodeDef *step_node = graph_utils::AddScalarConstNode<int64_t>(1, &graph);
std::vector<string> range_inputs(3);
range_inputs[0] = start_node->name();
range_inputs[1] = stop_node->name();
range_inputs[2] = step_node->name();
NodeDef *range_node = graph_utils::AddNode("", "RangeDataset", range_inputs,
common_attrs, &graph);
NodeDef *buffer_size_node =
graph_utils::AddScalarConstNode<int64_t>(128, &graph);
NodeDef *seed_node = graph_utils::AddScalarConstNode<int64_t>(-1, &graph);
NodeDef *seed2_node = graph_utils::AddScalarConstNode<int64_t>(-1, &graph);
std::vector<string> shuffle_inputs(4);
shuffle_inputs[0] = range_node->name();
shuffle_inputs[1] = buffer_size_node->name();
shuffle_inputs[2] = seed_node->name();
shuffle_inputs[3] = seed2_node->name();
NodeDef *shuffle_node = graph_utils::AddNode(
"", "ShuffleDataset", shuffle_inputs, common_attrs, &graph);
(*shuffle_node->mutable_attr())[kReshuffleEachIteration].set_b(true);
NodeDef *count_node = graph_utils::AddScalarConstNode<int64_t>(-1, &graph);
std::vector<string> repeat_inputs(2);
repeat_inputs[0] = shuffle_node->name();
repeat_inputs[1] = count_node->name();
NodeDef *repeat_node = graph_utils::AddNode(
"", "RepeatDataset", repeat_inputs, common_attrs, &graph);
ShuffleAndRepeatFusion optimizer;
GraphDef output;
TF_ASSERT_OK(optimizer.Optimize(nullptr, item, &output));
EXPECT_FALSE(
graph_utils::ContainsGraphNodeWithName(shuffle_node->name(), output));
EXPECT_FALSE(
graph_utils::ContainsGraphNodeWithName(repeat_node->name(), output));
EXPECT_TRUE(
graph_utils::ContainsNodeWithOp("ShuffleAndRepeatDataset", output));
NodeDef shuffle_and_repeat_node = output.node(
graph_utils::FindGraphNodeWithOp("ShuffleAndRepeatDataset", output));
EXPECT_EQ(shuffle_and_repeat_node.input_size(), 5);
EXPECT_EQ(shuffle_and_repeat_node.input(0), shuffle_node->input(0));
EXPECT_EQ(shuffle_and_repeat_node.input(1), shuffle_node->input(1));
EXPECT_EQ(shuffle_and_repeat_node.input(2), shuffle_node->input(2));
EXPECT_EQ(shuffle_and_repeat_node.input(3), shuffle_node->input(3));
EXPECT_EQ(shuffle_and_repeat_node.input(4), repeat_node->input(1));
for (const auto &attr :
{kOutputShapes, kOutputTypes, kReshuffleEachIteration}) {
EXPECT_TRUE(AreAttrValuesEqual(shuffle_and_repeat_node.attr().at(attr),
shuffle_node->attr().at(attr)));
}
}
TEST(ShuffleAndRepeatFusionTest, FuseShuffleV2AndRepeat) {
GrapplerItem item;
MutableGraphView graph(&item.graph);
std::vector<std::pair<string, AttrValue>> common_attrs(2);
AttrValue shapes_attr;
SetAttrValue(kOutputShapes, &shapes_attr);
common_attrs[0] = std::make_pair(kOutputShapes, shapes_attr);
AttrValue types_attr;
SetAttrValue(kOutputTypes, &types_attr);
common_attrs[1] = std::make_pair(kOutputTypes, types_attr);
NodeDef *start_node = graph_utils::AddScalarConstNode<int64_t>(0, &graph);
NodeDef *stop_node = graph_utils::AddScalarConstNode<int64_t>(10, &graph);
NodeDef *step_node = graph_utils::AddScalarConstNode<int64_t>(1, &graph);
std::vector<string> range_inputs(3);
range_inputs[0] = start_node->name();
range_inputs[1] = stop_node->name();
range_inputs[2] = step_node->name();
NodeDef *range_node = graph_utils::AddNode("", "RangeDataset", range_inputs,
common_attrs, &graph);
NodeDef *buffer_size_node =
graph_utils::AddScalarConstNode<int64_t>(128, &graph);
NodeDef *seed_generator_node =
graph_utils::AddScalarConstNode<StringPiece>("dummy_resource", &graph);
std::vector<string> shuffle_inputs(3);
shuffle_inputs[0] = range_node->name();
shuffle_inputs[1] = buffer_size_node->name();
shuffle_inputs[2] = seed_generator_node->name();
NodeDef *shuffle_node = graph_utils::AddNode(
"", "ShuffleDatasetV2", shuffle_inputs, common_attrs, &graph);
NodeDef *count_node = graph_utils::AddScalarConstNode<int64_t>(-1, &graph);
std::vector<string> repeat_inputs(2);
repeat_inputs[0] = shuffle_node->name();
repeat_inputs[1] = count_node->name();
NodeDef *repeat_node = graph_utils::AddNode(
"", "RepeatDataset", repeat_inputs, common_attrs, &graph);
ShuffleAndRepeatFusion optimizer;
GraphDef output;
TF_ASSERT_OK(optimizer.Optimize(nullptr, item, &output));
EXPECT_FALSE(
graph_utils::ContainsGraphNodeWithName(shuffle_node->name(), output));
EXPECT_FALSE(
graph_utils::ContainsGraphNodeWithName(repeat_node->name(), output));
EXPECT_TRUE(
graph_utils::ContainsNodeWithOp("ShuffleAndRepeatDatasetV2", output));
NodeDef shuffle_and_repeat_node = output.node(
graph_utils::FindGraphNodeWithOp("ShuffleAndRepeatDatasetV2", output));
EXPECT_EQ(shuffle_and_repeat_node.input_size(), 6);
EXPECT_EQ(shuffle_and_repeat_node.input(0), shuffle_node->input(0));
EXPECT_EQ(shuffle_and_repeat_node.input(1), shuffle_node->input(1));
EXPECT_EQ(shuffle_and_repeat_node.input(4), repeat_node->input(1));
EXPECT_EQ(shuffle_and_repeat_node.input(5), shuffle_node->input(2));
for (const auto &attr : {kOutputShapes, kOutputTypes}) {
EXPECT_TRUE(AreAttrValuesEqual(shuffle_and_repeat_node.attr().at(attr),
shuffle_node->attr().at(attr)));
}
EXPECT_TRUE(shuffle_and_repeat_node.attr().at(kReshuffleEachIteration).b());
}
TEST(ShuffleAndRepeatFusionTest, FuseShuffleV3AndRepeat) {
GrapplerItem item;
MutableGraphView graph(&item.graph);
std::vector<std::pair<string, AttrValue>> common_attrs(2);
AttrValue shapes_attr;
SetAttrValue(kOutputShapes, &shapes_attr);
common_attrs[0] = std::make_pair(kOutputShapes, shapes_attr);
AttrValue types_attr;
SetAttrValue(kOutputTypes, &types_attr);
common_attrs[1] = std::make_pair(kOutputTypes, types_attr);
NodeDef *start_node = graph_utils::AddScalarConstNode<int64_t>(0, &graph);
NodeDef *stop_node = graph_utils::AddScalarConstNode<int64_t>(10, &graph);
NodeDef *step_node = graph_utils::AddScalarConstNode<int64_t>(1, &graph);
std::vector<string> range_inputs(3);
range_inputs[0] = start_node->name();
range_inputs[1] = stop_node->name();
range_inputs[2] = step_node->name();
NodeDef *range_node = graph_utils::AddNode("", "RangeDataset", range_inputs,
common_attrs, &graph);
NodeDef *buffer_size_node =
graph_utils::AddScalarConstNode<int64_t>(128, &graph);
NodeDef *seed_node = graph_utils::AddScalarConstNode<int64_t>(-1, &graph);
NodeDef *seed2_node = graph_utils::AddScalarConstNode<int64_t>(-1, &graph);
NodeDef *seed_generator_node =
graph_utils::AddScalarConstNode<StringPiece>("dummy_resource", &graph);
std::vector<string> shuffle_inputs(5);
shuffle_inputs[0] = range_node->name();
shuffle_inputs[1] = buffer_size_node->name();
shuffle_inputs[2] = seed_node->name();
shuffle_inputs[3] = seed2_node->name();
shuffle_inputs[4] = seed_generator_node->name();
NodeDef *shuffle_node = graph_utils::AddNode(
"", "ShuffleDatasetV3", shuffle_inputs, common_attrs, &graph);
(*shuffle_node->mutable_attr())[kReshuffleEachIteration].set_b(true);
NodeDef *count_node = graph_utils::AddScalarConstNode<int64_t>(-1, &graph);
std::vector<string> repeat_inputs(2);
repeat_inputs[0] = shuffle_node->name();
repeat_inputs[1] = count_node->name();
NodeDef *repeat_node = graph_utils::AddNode(
"", "RepeatDataset", repeat_inputs, common_attrs, &graph);
ShuffleAndRepeatFusion optimizer;
GraphDef output;
TF_ASSERT_OK(optimizer.Optimize(nullptr, item, &output));
EXPECT_FALSE(
graph_utils::ContainsGraphNodeWithName(shuffle_node->name(), output));
EXPECT_FALSE(
graph_utils::ContainsGraphNodeWithName(repeat_node->name(), output));
EXPECT_TRUE(
graph_utils::ContainsNodeWithOp("ShuffleAndRepeatDatasetV2", output));
NodeDef shuffle_and_repeat_node = output.node(
graph_utils::FindGraphNodeWithOp("ShuffleAndRepeatDatasetV2", output));
EXPECT_EQ(shuffle_and_repeat_node.input_size(), 6);
EXPECT_EQ(shuffle_and_repeat_node.input(0), shuffle_node->input(0));
EXPECT_EQ(shuffle_and_repeat_node.input(1), shuffle_node->input(1));
EXPECT_EQ(shuffle_and_repeat_node.input(2), shuffle_node->input(2));
EXPECT_EQ(shuffle_and_repeat_node.input(3), shuffle_node->input(3));
EXPECT_EQ(shuffle_and_repeat_node.input(4), repeat_node->input(1));
EXPECT_EQ(shuffle_and_repeat_node.input(5), shuffle_node->input(4));
for (const auto &attr :
{kOutputShapes, kOutputTypes, kReshuffleEachIteration}) {
EXPECT_TRUE(AreAttrValuesEqual(shuffle_and_repeat_node.attr().at(attr),
shuffle_node->attr().at(attr)));
}
}
TEST(ShuffleAndRepeatFusionTest, NoChange) {
GrapplerItem item;
MutableGraphView graph(&item.graph);
std::vector<std::pair<string, AttrValue>> common_attrs(2);
AttrValue shapes_attr;
SetAttrValue(kOutputShapes, &shapes_attr);
common_attrs[0] = std::make_pair(kOutputShapes, shapes_attr);
AttrValue types_attr;
SetAttrValue(kOutputTypes, &types_attr);
common_attrs[1] = std::make_pair(kOutputTypes, types_attr);
NodeDef *start_node = graph_utils::AddScalarConstNode<int64_t>(0, &graph);
NodeDef *stop_node = graph_utils::AddScalarConstNode<int64_t>(10, &graph);
NodeDef *step_node = graph_utils::AddScalarConstNode<int64_t>(1, &graph);
std::vector<string> range_inputs(3);
range_inputs[0] = start_node->name();
range_inputs[1] = stop_node->name();
range_inputs[2] = step_node->name();
NodeDef *range_node = graph_utils::AddNode("", "RangeDataset", range_inputs,
common_attrs, &graph);
NodeDef *count_node = graph_utils::AddScalarConstNode<int64_t>(-1, &graph);
std::vector<string> repeat_inputs(2);
repeat_inputs[0] = range_node->name();
repeat_inputs[1] = count_node->name();
graph_utils::AddNode("", "RepeatDataset", repeat_inputs, common_attrs,
&graph);
ShuffleAndRepeatFusion optimizer;
GraphDef output;
TF_ASSERT_OK(optimizer.Optimize(nullptr, item, &output));
EXPECT_TRUE(graph_utils::Compare(*graph.graph(), output));
}
}
}
} |
361 | #ifndef TENSORFLOW_COMPILER_JIT_XLA_PLATFORM_INFO_H_
#define TENSORFLOW_COMPILER_JIT_XLA_PLATFORM_INFO_H_
#include <memory>
#include <optional>
#include <string>
#include "tensorflow/compiler/jit/device_compiler.h"
#include "tensorflow/compiler/jit/pjrt_base_device.h"
#include "tensorflow/compiler/jit/xla_device.h"
#include "xla/stream_executor/integrations/tf_allocator_adapter.h"
#include "tensorflow/core/framework/op_kernel.h"
namespace tensorflow {
class XlaPlatformInfo {
public:
XlaPlatformInfo() : device_type_("") {}
XlaPlatformInfo(XlaPlatformInfo&&) = default;
explicit XlaPlatformInfo(
const DeviceType device_type, se::Platform::Id platform_id,
const XlaDevice::Metadata* xla_device_metadata,
const PjRtBaseDevice::Metadata* pjrt_device_metadata,
std::shared_ptr<se::DeviceMemoryAllocator> device_allocator)
: device_type_(device_type),
platform_id_(platform_id),
xla_device_metadata_(xla_device_metadata),
pjrt_device_metadata_(pjrt_device_metadata),
device_allocator_(device_allocator) {}
XlaPlatformInfo& operator=(XlaPlatformInfo&& other) = default;
bool UseMultipleStreams() const {
return xla_device_metadata_ && xla_device_metadata_->UseMultipleStreams();
}
std::shared_ptr<se::DeviceMemoryAllocator> custom_allocator() const {
return device_allocator_;
}
DeviceType device_type() const { return device_type_; }
se::Platform::Id platform_id() const { return platform_id_; }
const XlaDevice::Metadata* xla_device_metadata() const {
return xla_device_metadata_;
}
bool is_on_xla_device() const { return xla_device_metadata() != nullptr; }
const PjRtBaseDevice::Metadata* pjrt_device_metadata() const {
return pjrt_device_metadata_;
}
private:
DeviceType device_type_;
se::Platform::Id platform_id_;
const XlaDevice::Metadata* xla_device_metadata_;
const PjRtBaseDevice::Metadata* pjrt_device_metadata_;
std::shared_ptr<se::DeviceMemoryAllocator> device_allocator_;
XlaPlatformInfo(const XlaPlatformInfo&) = delete;
void operator=(const XlaPlatformInfo&) = delete;
};
absl::StatusOr<std::optional<std::set<int>>> ParseVisibleDeviceList(
absl::string_view visible_device_list);
absl::StatusOr<DeviceType> GetCompilationDeviceType(
const DeviceType& platform_device_type);
Status BuildXlaDeviceCompiler(
DeviceBase* dev, FunctionLibraryRuntime* flr,
const XlaPlatformInfo& platform_info, DeviceType compilation_device_type,
DeviceCompiler<xla::LocalExecutable, xla::LocalClient>**
xla_device_compiler);
Status GetOrCreatePjRtDeviceCompilerAndProfiler(
const OpKernelContext& ctx, const XlaPlatformInfo& platform_info,
FunctionLibraryRuntime* flr,
DeviceCompiler<xla::PjRtLoadedExecutable, xla::PjRtClient>**
pjrt_device_compiler,
DeviceCompilationProfiler** profiler);
Status GetOrCreatePjRtDeviceCompilerAndProfiler(
const XlaPlatformInfo& platform_info, ResourceMgr* rm,
FunctionLibraryRuntime* flr,
DeviceCompiler<xla::PjRtLoadedExecutable, xla::PjRtClient>**
pjrt_device_compiler,
DeviceCompilationProfiler** profiler);
XlaPlatformInfo XlaPlatformInfoFromDevice(DeviceBase* device);
std::string GetPersistentCacheDirectory(
const DeviceType& compilation_device_type);
std::shared_ptr<se::DeviceMemoryAllocator> GetAllocator(
DeviceBase* device, se::Stream* stream,
const XlaPlatformInfo& platform_info);
}
#endif
#include "tensorflow/compiler/jit/xla_platform_info.h"
#include <memory>
#include <optional>
#include <set>
#include <string>
#include <utility>
#include <vector>
#include "absl/algorithm/container.h"
#include "absl/status/status.h"
#include "absl/strings/str_split.h"
#include "absl/strings/string_view.h"
#include "tensorflow/compiler/jit/device_executable_persistor.h"
#include "tensorflow/compiler/jit/flags.h"
#include "tensorflow/compiler/jit/pjrt_device_compiler_client.h"
#include "tensorflow/compiler/jit/xla_compile_util.h"
#include "tensorflow/compiler/jit/xla_device_compiler_client.h"
#include "xla/client/client_library.h"
#include "xla/client/local_client.h"
#include "xla/pjrt/pjrt_client.h"
#include "xla/service/compiler.h"
#include "xla/stream_executor/platform_manager.h"
#include "xla/tsl/framework/device_type.h"
#include "tensorflow/core/framework/function.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/resource_mgr.h"
#include "tensorflow/core/framework/types.h"
#include "tensorflow/core/platform/errors.h"
#include "tensorflow/core/platform/status.h"
#include "tensorflow/core/tfrt/common/create_pjrt_client_util.h"
#include "tensorflow/core/tfrt/common/global_state.h"
#include "tensorflow/core/tfrt/common/pjrt_util.h"
#include "tensorflow/core/tpu/tpu_defs.h"
namespace tensorflow {
namespace {
using XlaDeviceCompiler =
DeviceCompiler<xla::LocalExecutable, xla::LocalClient>;
using PjRtDeviceCompiler =
DeviceCompiler<xla::PjRtLoadedExecutable, xla::PjRtClient>;
using XlaDeviceExecutablePersistor =
DeviceExecutablePersistor<xla::LocalExecutable, xla::LocalClient>;
using PjRtDeviceExecutablePersistor =
DeviceExecutablePersistor<xla::PjRtLoadedExecutable, xla::PjRtClient>;
XlaDeviceCompiler* CreateXlaDeviceCompiler(
const XlaDeviceExecutablePersistor::Config& persistor_config,
DeviceType compilation_device_type, xla::LocalClient* local_client) {
return new XlaDeviceCompiler(
std::make_unique<XlaDeviceExecutablePersistor>(
std::move(persistor_config), compilation_device_type),
std::make_unique<XlaDeviceCompilerClient>(local_client));
}
PjRtDeviceCompiler* CreatePjRtDeviceCompiler(DeviceType compilation_device_type,
xla::PjRtClient* pjrt_client) {
std::string persistent_cache_directory =
GetPersistentCacheDirectory(compilation_device_type);
PjRtDeviceExecutablePersistor::Config persistor_config(
persistent_cache_directory,
GetMarkForCompilationPassFlags()->tf_xla_disable_strict_signature_checks,
GetMarkForCompilationPassFlags()->tf_xla_persistent_cache_prefix,
GetMarkForCompilationPassFlags()->tf_xla_persistent_cache_read_only);
return new PjRtDeviceCompiler(
std::make_unique<PjRtDeviceExecutablePersistor>(
std::move(persistor_config), compilation_device_type),
std::make_unique<PjRtDeviceCompilerClient>(pjrt_client));
}
absl::StatusOr<std::optional<std::set<int>>> GetAllowedGpus(
FunctionLibraryRuntime* flr) {
std::optional<std::set<int>> gpu_ids = std::nullopt;
if (flr->config_proto()) {
string allowed_gpus =
flr->config_proto()->gpu_options().visible_device_list();
TF_ASSIGN_OR_RETURN(gpu_ids, ParseVisibleDeviceList(allowed_gpus));
}
return gpu_ids;
}
Status GetCompilationDeviceTypeAndPjRtClient(
const XlaPlatformInfo& platform_info, FunctionLibraryRuntime* flr,
DeviceType* compilation_device_type, xla::PjRtClient** pjrt_client) {
DeviceType device_type = platform_info.device_type();
if (platform_info.xla_device_metadata()) {
VLOG(2) << "Building PjRtDeviceCompiler using "
"platform_info.xla_device_metadata().";
*compilation_device_type =
platform_info.xla_device_metadata()->jit_device_type();
TF_ASSIGN_OR_RETURN(*pjrt_client, GetOrCreatePjRtClient(device_type));
return absl::OkStatus();
}
if (platform_info.pjrt_device_metadata()) {
VLOG(2) << "Building PjRtDeviceCompiler using "
"platform_info.pjrt_device_metadata().";
*compilation_device_type =
platform_info.pjrt_device_metadata()->jit_device_type();
TF_ASSIGN_OR_RETURN(*pjrt_client, GetOrCreatePjRtClient(device_type));
return absl::OkStatus();
}
if (device_type == DEVICE_TPU) {
*compilation_device_type = DeviceType(DEVICE_TPU_XLA_JIT);
TF_ASSIGN_OR_RETURN(*pjrt_client, GetOrCreatePjRtClient(device_type));
return absl::OkStatus();
}
VLOG(2) << "platform_info.xla_device_metadata not found and "
"platform_info.device_type() != DEVICE_TPU. Building "
"PjRtDeviceCompiler for non-XLA device.";
const XlaOpRegistry::DeviceRegistration* registration;
if (!XlaOpRegistry::GetCompilationDevice(device_type.type(), ®istration)) {
return errors::InvalidArgument("No JIT device registered for ",
device_type.type());
}
*compilation_device_type = DeviceType(registration->compilation_device_name);
TF_ASSIGN_OR_RETURN(auto allowed_gpus, GetAllowedGpus(flr));
TF_ASSIGN_OR_RETURN(*pjrt_client,
GetOrCreatePjRtClient(device_type, allowed_gpus));
return absl::OkStatus();
}
}
std::string GetPersistentCacheDirectory(
const DeviceType& compilation_device_type) {
if (!GetMarkForCompilationPassFlags()
->tf_xla_persistent_cache_device_types.empty() &&
!absl::c_any_of(absl::StrSplit(GetMarkForCompilationPassFlags()
->tf_xla_persistent_cache_device_types,
','),
[&](absl::string_view device) {
return compilation_device_type == DeviceType(device);
})) {
return "";
}
return GetMarkForCompilationPassFlags()->tf_xla_persistent_cache_directory;
}
absl::StatusOr<std::optional<std::set<int>>> ParseVisibleDeviceList(
absl::string_view visible_device_list) {
std::set<int> gpu_ids;
if (visible_device_list.empty()) {
return {{std::nullopt}};
}
const std::vector<string> visible_devices =
absl::StrSplit(visible_device_list, ',');
for (const string& platform_device_id_str : visible_devices) {
int32_t platform_device_id;
if (!absl::SimpleAtoi(platform_device_id_str, &platform_device_id)) {
return errors::InvalidArgument(
"Could not parse entry in 'visible_device_list': '",
platform_device_id_str,
"'. visible_device_list = ", visible_device_list);
}
gpu_ids.insert(platform_device_id);
}
return {{gpu_ids}};
}
absl::StatusOr<DeviceType> GetCompilationDeviceType(
const DeviceType& platform_device_type) {
DeviceType compilation_device_type = platform_device_type;
const XlaOpRegistry::DeviceRegistration* registration = nullptr;
if (!XlaOpRegistry::GetCompilationDevice(platform_device_type.type(),
®istration)) {
return errors::InvalidArgument("No JIT device registered for ",
platform_device_type.type());
}
compilation_device_type = DeviceType(registration->compilation_device_name);
return compilation_device_type;
}
Status BuildXlaDeviceCompiler(DeviceBase* device, FunctionLibraryRuntime* flr,
const XlaPlatformInfo& platform_info,
DeviceType compilation_device_type,
XlaDeviceCompiler** xla_device_compiler) {
if (platform_info.platform_id() == nullptr &&
platform_info.device_type() == DEVICE_GPU) {
*xla_device_compiler = new XlaDeviceCompiler(nullptr,
nullptr);
return absl::OkStatus();
}
std::string persistent_cache_directory =
GetPersistentCacheDirectory(platform_info.device_type());
XlaDeviceExecutablePersistor::Config persistor_config(
persistent_cache_directory,
GetMarkForCompilationPassFlags()->tf_xla_disable_strict_signature_checks,
GetMarkForCompilationPassFlags()->tf_xla_persistent_cache_prefix,
GetMarkForCompilationPassFlags()->tf_xla_persistent_cache_read_only);
if (platform_info.xla_device_metadata()) {
*xla_device_compiler = CreateXlaDeviceCompiler(
persistor_config,
platform_info.xla_device_metadata()->jit_device_type(),
platform_info.xla_device_metadata()->client());
return absl::OkStatus();
}
if (platform_info.device_type() == DEVICE_TPU) {
*xla_device_compiler = CreateXlaDeviceCompiler(
persistor_config, DeviceType(DEVICE_TPU_XLA_JIT), nullptr);
return absl::OkStatus();
}
if (platform_info.platform_id() == nullptr) {
return errors::InvalidArgument("platform_id is null.");
}
auto platform =
se::PlatformManager::PlatformWithId(platform_info.platform_id());
if (!platform.ok()) {
return platform.status();
}
absl::StatusOr<xla::Compiler*> compiler_for_platform =
xla::Compiler::GetForPlatform(platform.value());
if (!compiler_for_platform.ok()) {
const Status& status = compiler_for_platform.status();
if (status.code() == error::NOT_FOUND) {
return errors::Unimplemented("Could not find compiler for platform ",
platform.value()->Name(), ": ",
status.ToString());
}
}
xla::LocalClientOptions client_options;
client_options.set_platform(platform.value());
if (device != nullptr) {
client_options.set_intra_op_parallelism_threads(
device->tensorflow_cpu_worker_threads()->num_threads);
}
if (flr != nullptr) {
TF_ASSIGN_OR_RETURN(auto allowed_gpus, GetAllowedGpus(flr));
client_options.set_allowed_devices(allowed_gpus);
}
TF_ASSIGN_OR_RETURN(
auto client, xla::ClientLibrary::GetOrCreateLocalClient(client_options));
*xla_device_compiler = CreateXlaDeviceCompiler(
persistor_config, compilation_device_type, client);
return absl::OkStatus();
}
Status GetOrCreatePjRtDeviceCompilerAndProfiler(
const XlaPlatformInfo& platform_info, ResourceMgr* rm,
FunctionLibraryRuntime* flr, PjRtDeviceCompiler** pjrt_device_compiler,
DeviceCompilationProfiler** profiler) {
const auto& device_type = platform_info.device_type();
const std::string& compiler_name =
GetPjRtDeviceCompilerResourceName(device_type);
const std::string& profiler_name =
GetPjRtDeviceCompilationProfilerResourceName(device_type);
bool deleted_old_device_compiler = false;
Status s = rm->Lookup<PjRtDeviceCompiler>(
rm->default_container(), compiler_name, pjrt_device_compiler);
if (s.ok() && device_type == DEVICE_TPU) {
auto* existing_pjrt_client = (*pjrt_device_compiler)->client();
TF_ASSIGN_OR_RETURN(auto* latest_pjrt_client, GetPjRtClient(device_type));
if (existing_pjrt_client != latest_pjrt_client) {
TF_RETURN_IF_ERROR(rm->Delete<PjRtDeviceCompiler>(rm->default_container(),
compiler_name));
TF_RETURN_IF_ERROR(rm->Delete<DeviceCompilationProfiler>(
rm->default_container(), profiler_name));
deleted_old_device_compiler = true;
}
}
if (!s.ok() || deleted_old_device_compiler) {
DeviceType compilation_device_type("");
xla::PjRtClient* pjrt_client = nullptr;
TF_RETURN_IF_ERROR(GetCompilationDeviceTypeAndPjRtClient(
platform_info, flr, &compilation_device_type, &pjrt_client));
TF_RETURN_IF_ERROR(rm->LookupOrCreate<PjRtDeviceCompiler>(
rm->default_container(), compiler_name, pjrt_device_compiler,
[&](PjRtDeviceCompiler** pjrt_device_compiler) {
*pjrt_device_compiler =
CreatePjRtDeviceCompiler(compilation_device_type, pjrt_client);
return absl::OkStatus();
}));
}
TF_RETURN_IF_ERROR(rm->LookupOrCreate<DeviceCompilationProfiler>(
rm->default_container(), profiler_name, profiler,
[](DeviceCompilationProfiler** profiler) {
*profiler = new DeviceCompilationProfiler();
return absl::OkStatus();
}));
return absl::OkStatus();
}
Status GetOrCreatePjRtDeviceCompilerAndProfiler(
const OpKernelContext& ctx, const XlaPlatformInfo& platform_info,
FunctionLibraryRuntime* flr,
DeviceCompiler<xla::PjRtLoadedExecutable, xla::PjRtClient>**
pjrt_device_compiler,
DeviceCompilationProfiler** profiler) {
TF_ASSIGN_OR_RETURN(ResourceMgr * rm, GetResourceMgrForDeviceCompiler(
ctx, platform_info.device_type()));
return GetOrCreatePjRtDeviceCompilerAndProfiler(
platform_info, rm, flr, pjrt_device_compiler, profiler);
}
XlaPlatformInfo XlaPlatformInfoFromDevice(DeviceBase* device_base) {
se::Platform::Id platform_id = nullptr;
const XlaDevice::Metadata* xla_device_metadata = nullptr;
const PjRtBaseDevice::Metadata* pjrt_device_metadata = nullptr;
std::shared_ptr<se::DeviceMemoryAllocator> custom_allocator;
const std::string& device_type = device_base->device_type();
if (device_type == DEVICE_CPU) {
platform_id = se::host::kHostPlatformId;
} else if (device_type == DEVICE_GPU) {
auto device = static_cast<Device*>(device_base);
platform_id = device->tensorflow_accelerator_device_info()
->stream->parent()
->GetPlatform()
->id();
} else if (XlaDevice::GetMetadataFromDevice(device_base, &xla_device_metadata)
.ok()) {
platform_id = xla_device_metadata->platform()->id();
custom_allocator =
xla_device_metadata->client()->backend().shared_memory_allocator();
} else if (auto metadata = PjRtBaseDevice::GetMetadataFromDevice(device_base);
metadata.ok()) {
pjrt_device_metadata = *metadata;
}
return XlaPlatformInfo(DeviceType(device_type), platform_id,
xla_device_metadata, pjrt_device_metadata,
custom_allocator);
}
std::shared_ptr<se::DeviceMemoryAllocator> GetAllocator(
DeviceBase* device, se::Stream* stream,
const XlaPlatformInfo& platform_info) {
if (platform_info.custom_allocator()) {
return platform_info.custom_allocator();
}
auto* alloc = device->GetAllocator({});
if (!stream) {
se::Platform* platform =
se::PlatformManager::PlatformWithId(platform_info.platform_id())
.value();
return std::make_shared<se::TfAllocatorAdapter>(alloc, platform);
}
return std::make_shared<se::TfAllocatorAdapter>(alloc, stream);
}
} | #include "tensorflow/compiler/jit/xla_platform_info.h"
#include <memory>
#include <vector>
#include <gtest/gtest.h>
#include "tensorflow/compiler/jit/flags.h"
#include "tensorflow/compiler/jit/test_util.h"
#include "xla/pjrt/tfrt_cpu_pjrt_client.h"
#include "tensorflow/core/framework/device_base.h"
#include "tensorflow/core/framework/types.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/lib/core/status_test_util.h"
#include "tensorflow/core/platform/refcount.h"
#include "tensorflow/core/platform/status_matchers.h"
#include "tensorflow/core/platform/statusor.h"
#include "tensorflow/core/protobuf/error_codes.pb.h"
#include "tensorflow/core/tfrt/common/create_pjrt_client_util.h"
#include "tensorflow/core/tfrt/common/pjrt_util.h"
#include "tensorflow/core/tpu/tpu_defs.h"
namespace tensorflow {
namespace {
using XlaDeviceCompiler =
DeviceCompiler<xla::LocalExecutable, xla::LocalClient>;
using PjRtDeviceCompiler =
DeviceCompiler<xla::PjRtLoadedExecutable, xla::PjRtClient>;
class XlaPlatformInfoTest : public ::testing::Test {
protected:
void SetUp() override {
tensorflow::GetXlaDeviceFlags()->tf_xla_enable_xla_devices = true;
tensorflow::GetMarkForCompilationPassFlags()
->tf_xla_persistent_cache_directory = "";
tensorflow::GetMarkForCompilationPassFlags()
->tf_xla_persistent_cache_device_types = "";
}
DeviceSetup device_setup_;
};
class StubDevice : public DeviceBase {
public:
StubDevice() : DeviceBase(nullptr) {}
};
#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM
TEST_F(XlaPlatformInfoTest, BuildXlaDeviceCompilerXlaDeviceMetadata) {
device_setup_.AddDevicesAndSetUp({DEVICE_XLA_GPU});
Device* device = device_setup_.GetDevice(DEVICE_XLA_GPU);
const XlaDevice::Metadata* metadata = nullptr;
TF_CHECK_OK(XlaDevice::GetMetadataFromDevice(device, &metadata));
XlaPlatformInfo platform_info = XlaPlatformInfoFromDevice(device);
TF_ASSERT_OK_AND_ASSIGN(
DeviceType compilation_device_type,
GetCompilationDeviceType(platform_info.device_type()));
XlaDeviceCompiler* xla_device_compiler = nullptr;
TF_EXPECT_OK(BuildXlaDeviceCompiler(device, device_setup_.flr(),
platform_info, compilation_device_type,
&xla_device_compiler));
core::ScopedUnref xla_device_compiler_ref(xla_device_compiler);
EXPECT_EQ(xla_device_compiler->device_type(), metadata->jit_device_type());
EXPECT_EQ(xla_device_compiler->client(), metadata->client());
}
TEST_F(XlaPlatformInfoTest, BuildXlaDeviceCompilerXlaDeviceCacheEnabled) {
tensorflow::GetMarkForCompilationPassFlags()
->tf_xla_persistent_cache_directory = "/tmp/xla_cache";
tensorflow::GetMarkForCompilationPassFlags()
->tf_xla_persistent_cache_device_types = DEVICE_XLA_GPU;
device_setup_.AddDevicesAndSetUp({DEVICE_XLA_GPU});
Device* device = device_setup_.GetDevice(DEVICE_XLA_GPU);
const XlaDevice::Metadata* metadata = nullptr;
TF_CHECK_OK(XlaDevice::GetMetadataFromDevice(device, &metadata));
XlaPlatformInfo platform_info = XlaPlatformInfoFromDevice(device);
TF_ASSERT_OK_AND_ASSIGN(
DeviceType compilation_device_type,
GetCompilationDeviceType(platform_info.device_type()));
XlaDeviceCompiler* xla_device_compiler = nullptr;
TF_EXPECT_OK(BuildXlaDeviceCompiler(device, device_setup_.flr(),
platform_info, compilation_device_type,
&xla_device_compiler));
core::ScopedUnref xla_device_compiler_ref(xla_device_compiler);
EXPECT_EQ(xla_device_compiler->device_type(), metadata->jit_device_type());
EXPECT_EQ(xla_device_compiler->client(), metadata->client());
EXPECT_EQ(xla_device_compiler->persistor()->persistent_cache_directory(),
"/tmp/xla_cache");
}
TEST_F(XlaPlatformInfoTest, BuildXlaDeviceCompilerNonXlaDevice) {
device_setup_.AddDevicesAndSetUp({DEVICE_GPU});
Device* device = device_setup_.GetDevice(DEVICE_GPU);
XlaPlatformInfo platform_info = XlaPlatformInfoFromDevice(device);
TF_ASSERT_OK_AND_ASSIGN(
DeviceType compilation_device_type,
GetCompilationDeviceType(platform_info.device_type()));
XlaDeviceCompiler* xla_device_compiler = nullptr;
TF_EXPECT_OK(BuildXlaDeviceCompiler(device, device_setup_.flr(),
platform_info, compilation_device_type,
&xla_device_compiler));
core::ScopedUnref xla_device_compiler_ref(xla_device_compiler);
EXPECT_EQ(xla_device_compiler->device_type(), DeviceType(DEVICE_GPU_XLA_JIT));
EXPECT_TRUE(xla_device_compiler->client() != nullptr);
}
TEST_F(XlaPlatformInfoTest, GetOrCreatePjRtDeviceCompilerAndProfilerXlaDevice) {
DeviceType device_type = DeviceType(DEVICE_XLA_GPU);
device_setup_.AddDevicesAndSetUp({device_type.type()});
Device* device = device_setup_.GetDevice(device_type.type());
const XlaDevice::Metadata* metadata = nullptr;
TF_CHECK_OK(XlaDevice::GetMetadataFromDevice(device, &metadata));
XlaPlatformInfo platform_info = XlaPlatformInfoFromDevice(device);
ResourceMgr resource_mgr("");
OpKernelContext::Params params;
params.resource_manager = &resource_mgr;
params.device = device;
OpKernelContext ctx(¶ms, 0);
PjRtDeviceCompiler* pjrt_device_compiler = nullptr;
DeviceCompilationProfiler* profiler = nullptr;
TF_EXPECT_OK(GetOrCreatePjRtDeviceCompilerAndProfiler(
ctx, platform_info, device_setup_.flr(), &pjrt_device_compiler,
&profiler));
core::ScopedUnref pjrt_device_compiler_ref(pjrt_device_compiler);
core::ScopedUnref profiler_ref(profiler);
TF_ASSERT_OK_AND_ASSIGN(auto pjrt_client, GetOrCreatePjRtClient(device_type));
EXPECT_EQ(pjrt_device_compiler->device_type(), metadata->jit_device_type());
EXPECT_EQ(pjrt_device_compiler->client(), pjrt_client);
}
TEST_F(XlaPlatformInfoTest,
GetOrCreatePjRtDeviceCompilerAndProfilerGpuDeviceCacheEnabled) {
tensorflow::GetMarkForCompilationPassFlags()
->tf_xla_persistent_cache_directory = "/tmp/xla_cache";
tensorflow::GetMarkForCompilationPassFlags()
->tf_xla_persistent_cache_device_types = DEVICE_GPU_XLA_JIT;
device_setup_.AddDevicesAndSetUp({DEVICE_GPU});
Device* device = device_setup_.GetDevice(DEVICE_GPU);
XlaPlatformInfo platform_info = XlaPlatformInfoFromDevice(device);
ResourceMgr resource_mgr("");
OpKernelContext::Params params;
params.resource_manager = &resource_mgr;
params.device = device;
OpKernelContext ctx(¶ms, 0);
PjRtDeviceCompiler* pjrt_device_compiler = nullptr;
DeviceCompilationProfiler* profiler = nullptr;
TF_EXPECT_OK(GetOrCreatePjRtDeviceCompilerAndProfiler(
ctx, platform_info, device_setup_.flr(), &pjrt_device_compiler,
&profiler));
EXPECT_EQ(pjrt_device_compiler->persistor()->persistent_cache_directory(),
"/tmp/xla_cache");
core::ScopedUnref pjrt_device_compiler_ref(pjrt_device_compiler);
core::ScopedUnref profiler_ref(profiler);
}
#endif
TEST_F(XlaPlatformInfoTest, BuildXlaDeviceCompilerTpuDevice) {
DeviceType compilation_device_type = DeviceType(DEVICE_TPU_XLA_JIT);
Device* device = nullptr;
XlaPlatformInfo platform_info(DeviceType(DEVICE_TPU), nullptr,
nullptr,
nullptr,
nullptr);
XlaDeviceCompiler* xla_device_compiler = nullptr;
TF_EXPECT_OK(BuildXlaDeviceCompiler(device, nullptr, platform_info,
compilation_device_type,
&xla_device_compiler));
core::ScopedUnref xla_device_compiler_ref(xla_device_compiler);
EXPECT_EQ(xla_device_compiler->device_type(), compilation_device_type);
EXPECT_EQ(xla_device_compiler->client(), nullptr);
}
TEST_F(XlaPlatformInfoTest, BuildXlaDeviceCompilerNoCompilationCache) {
DeviceType compilation_device_type = DeviceType(DEVICE_TPU_XLA_JIT);
tensorflow::GetMarkForCompilationPassFlags()
->tf_xla_persistent_cache_directory = "/tmp/xla_cache";
tensorflow::GetMarkForCompilationPassFlags()
->tf_xla_persistent_cache_device_types = DEVICE_XLA_GPU;
Device* device = nullptr;
XlaPlatformInfo platform_info(DeviceType(DEVICE_TPU), nullptr,
nullptr,
nullptr,
nullptr);
XlaDeviceCompiler* xla_device_compiler = nullptr;
TF_EXPECT_OK(BuildXlaDeviceCompiler(device, nullptr, platform_info,
compilation_device_type,
&xla_device_compiler));
core::ScopedUnref xla_device_compiler_ref(xla_device_compiler);
EXPECT_EQ(xla_device_compiler->device_type(), compilation_device_type);
EXPECT_TRUE(
xla_device_compiler->persistor()->persistent_cache_directory().empty());
}
TEST_F(XlaPlatformInfoTest,
GetOrCreatePjRtDeviceCompilerAndProfilerTpuDeviceNoCompilationCache) {
tensorflow::GetMarkForCompilationPassFlags()
->tf_xla_persistent_cache_directory = "/tmp/xla_cache";
tensorflow::GetMarkForCompilationPassFlags()
->tf_xla_persistent_cache_device_types = DEVICE_GPU_XLA_JIT;
DeviceType device_type = DeviceType(DEVICE_TPU);
DeviceType compilation_device_type = DeviceType(DEVICE_TPU_XLA_JIT);
TF_CHECK_OK(SetPjRtClientInTFGlobalResourceManager(
device_type,
xla::GetTfrtCpuClient(true, 1)
.value()));
TF_ASSERT_OK_AND_ASSIGN(auto pjrt_client, GetOrCreatePjRtClient(device_type));
XlaPlatformInfo platform_info(device_type, nullptr,
nullptr,
nullptr,
nullptr);
OpKernelContext::Params params;
StubDevice stub_device;
params.device = &stub_device;
OpKernelContext ctx(¶ms, 0);
PjRtDeviceCompiler* pjrt_device_compiler = nullptr;
DeviceCompilationProfiler* profiler = nullptr;
TF_EXPECT_OK(GetOrCreatePjRtDeviceCompilerAndProfiler(
ctx, platform_info, nullptr, &pjrt_device_compiler, &profiler));
core::ScopedUnref pjrt_device_compiler_ref(pjrt_device_compiler);
core::ScopedUnref profiler_ref(profiler);
EXPECT_EQ(pjrt_device_compiler->device_type(), compilation_device_type);
EXPECT_EQ(pjrt_device_compiler->client(), pjrt_client);
EXPECT_TRUE(
pjrt_device_compiler->persistor()->persistent_cache_directory().empty());
}
TEST_F(XlaPlatformInfoTest, GetPersistentCacheDirectoryMultiple) {
tensorflow::GetMarkForCompilationPassFlags()
->tf_xla_persistent_cache_directory = "/tmp/xla_cache";
tensorflow::GetMarkForCompilationPassFlags()
->tf_xla_persistent_cache_device_types = "GPU,CPU";
DeviceType device_gpu = DeviceType(DEVICE_GPU);
EXPECT_EQ(GetPersistentCacheDirectory(device_gpu), "/tmp/xla_cache");
DeviceType device_cpu = DeviceType(DEVICE_CPU);
EXPECT_EQ(GetPersistentCacheDirectory(device_cpu), "/tmp/xla_cache");
DeviceType device_tpu = DeviceType(DEVICE_TPU);
EXPECT_TRUE(GetPersistentCacheDirectory(device_tpu).empty());
}
TEST_F(XlaPlatformInfoTest, GetPersistentCacheDirectoryNoDeviceTypes) {
tensorflow::GetMarkForCompilationPassFlags()
->tf_xla_persistent_cache_directory = "/tmp/xla_cache";
tensorflow::GetMarkForCompilationPassFlags()
->tf_xla_persistent_cache_device_types = "";
DeviceType device_gpu = DeviceType(DEVICE_GPU);
EXPECT_EQ(GetPersistentCacheDirectory(device_gpu), "/tmp/xla_cache");
DeviceType device_cpu = DeviceType(DEVICE_CPU);
EXPECT_EQ(GetPersistentCacheDirectory(device_cpu), "/tmp/xla_cache");
DeviceType device_tpu = DeviceType(DEVICE_TPU);
EXPECT_EQ(GetPersistentCacheDirectory(device_tpu), "/tmp/xla_cache");
}
}
} |
362 | #ifndef TENSORSTORE_KVSTORE_S3_CREDENTIALS_DEFAULT_CREDENTIAL_PROVIDER_H_
#define TENSORSTORE_KVSTORE_S3_CREDENTIALS_DEFAULT_CREDENTIAL_PROVIDER_H_
#include <functional>
#include <memory>
#include <string>
#include <string_view>
#include "absl/base/thread_annotations.h"
#include "absl/functional/function_ref.h"
#include "absl/synchronization/mutex.h"
#include "absl/time/clock.h"
#include "absl/time/time.h"
#include "tensorstore/internal/http/curl_transport.h"
#include "tensorstore/internal/http/http_transport.h"
#include "tensorstore/kvstore/s3/credentials/aws_credentials.h"
#include "tensorstore/util/result.h"
namespace tensorstore {
namespace internal_kvstore_s3 {
class DefaultAwsCredentialsProvider : public AwsCredentialProvider {
public:
struct Options {
std::string filename;
std::string profile;
std::string endpoint;
std::shared_ptr<internal_http::HttpTransport> transport;
};
DefaultAwsCredentialsProvider(
Options options = {{}, {}, {}, internal_http::GetDefaultHttpTransport()},
absl::FunctionRef<absl::Time()> clock = absl::Now);
Result<AwsCredentials> GetCredentials() override;
private:
Options options_;
absl::FunctionRef<absl::Time()> clock_;
absl::Mutex mutex_;
std::unique_ptr<AwsCredentialProvider> provider_ ABSL_GUARDED_BY(mutex_);
AwsCredentials credentials_ ABSL_GUARDED_BY(mutex_);
};
using AwsCredentialProviderFn =
std::function<Result<std::unique_ptr<AwsCredentialProvider>>()>;
void RegisterAwsCredentialProviderProvider(AwsCredentialProviderFn provider,
int priority);
Result<std::unique_ptr<AwsCredentialProvider>> GetAwsCredentialProvider(
std::string_view filename, std::string_view profile,
std::string_view metadata_endpoint,
std::shared_ptr<internal_http::HttpTransport> transport);
}
}
#endif
#include "tensorstore/kvstore/s3/credentials/default_credential_provider.h"
#include <algorithm>
#include <memory>
#include <string>
#include <string_view>
#include <utility>
#include <vector>
#include "absl/base/attributes.h"
#include "absl/base/no_destructor.h"
#include "absl/functional/function_ref.h"
#include "absl/log/absl_log.h"
#include "absl/synchronization/mutex.h"
#include "absl/time/time.h"
#include "tensorstore/internal/http/http_transport.h"
#include "tensorstore/internal/log/verbose_flag.h"
#include "tensorstore/kvstore/s3/credentials/aws_credentials.h"
#include "tensorstore/kvstore/s3/credentials/ec2_credential_provider.h"
#include "tensorstore/kvstore/s3/credentials/environment_credential_provider.h"
#include "tensorstore/kvstore/s3/credentials/file_credential_provider.h"
#include "tensorstore/util/result.h"
namespace tensorstore {
namespace internal_kvstore_s3 {
namespace {
ABSL_CONST_INIT internal_log::VerboseFlag s3_logging("s3");
struct AwsCredentialProviderRegistry {
std::vector<std::pair<int, AwsCredentialProviderFn>> providers;
absl::Mutex mutex;
};
AwsCredentialProviderRegistry& GetAwsProviderRegistry() {
static absl::NoDestructor<AwsCredentialProviderRegistry> registry;
return *registry;
}
}
void RegisterAwsCredentialProviderProvider(AwsCredentialProviderFn provider,
int priority) {
auto& registry = GetAwsProviderRegistry();
absl::WriterMutexLock lock(®istry.mutex);
registry.providers.emplace_back(priority, std::move(provider));
std::sort(registry.providers.begin(), registry.providers.end(),
[](const auto& a, const auto& b) { return a.first < b.first; });
}
Result<std::unique_ptr<AwsCredentialProvider>> GetAwsCredentialProvider(
std::string_view filename, std::string_view profile,
std::string_view metadata_endpoint,
std::shared_ptr<internal_http::HttpTransport> transport) {
auto& registry = GetAwsProviderRegistry();
absl::WriterMutexLock lock(®istry.mutex);
for (const auto& provider : registry.providers) {
auto credentials = provider.second();
if (credentials.ok()) return credentials;
}
return std::make_unique<DefaultAwsCredentialsProvider>(
DefaultAwsCredentialsProvider::Options{
std::string{filename}, std::string{profile},
std::string{metadata_endpoint}, transport});
}
DefaultAwsCredentialsProvider::DefaultAwsCredentialsProvider(
Options options, absl::FunctionRef<absl::Time()> clock)
: options_(std::move(options)),
clock_(clock),
credentials_{{}, {}, {}, absl::InfinitePast()} {}
Result<AwsCredentials> DefaultAwsCredentialsProvider::GetCredentials() {
{
absl::ReaderMutexLock lock(&mutex_);
if (credentials_.expires_at > clock_()) {
return credentials_;
}
}
absl::WriterMutexLock lock(&mutex_);
if (provider_) {
auto credentials_result = provider_->GetCredentials();
if (credentials_result.ok()) {
credentials_ = credentials_result.value();
return credentials_;
}
}
bool only_default_options = options_.filename.empty() &&
options_.profile.empty() &&
options_.endpoint.empty();
if (only_default_options) {
provider_ = std::make_unique<EnvironmentCredentialProvider>();
if (auto credentials_result = provider_->GetCredentials();
credentials_result.ok()) {
credentials_ = std::move(credentials_result).value();
return credentials_;
} else if (s3_logging) {
ABSL_LOG_FIRST_N(INFO, 1)
<< "Could not acquire credentials from environment: "
<< credentials_result.status();
}
}
if (only_default_options || !options_.filename.empty() ||
!options_.profile.empty()) {
provider_ = std::make_unique<FileCredentialProvider>(options_.filename,
options_.profile);
if (auto credentials_result = provider_->GetCredentials();
credentials_result.ok()) {
credentials_ = std::move(credentials_result).value();
return credentials_;
} else if (s3_logging) {
ABSL_LOG_FIRST_N(INFO, 1)
<< "Could not acquire credentials from file/profile: "
<< credentials_result.status();
}
}
if (only_default_options || !options_.endpoint.empty()) {
provider_ = std::make_unique<EC2MetadataCredentialProvider>(
options_.endpoint, options_.transport);
if (auto credentials_result = provider_->GetCredentials();
credentials_result.ok()) {
credentials_ = std::move(credentials_result).value();
return credentials_;
} else if (s3_logging) {
ABSL_LOG(INFO)
<< "Could not acquire credentials from EC2 Metadata Server "
<< options_.endpoint << ": " << credentials_result.status();
}
}
provider_ = nullptr;
credentials_ = AwsCredentials::Anonymous();
return credentials_;
}
}
} | #include "tensorstore/kvstore/s3/credentials/default_credential_provider.h"
#include <fstream>
#include <memory>
#include <string>
#include <gtest/gtest.h>
#include "absl/container/flat_hash_map.h"
#include "absl/strings/cord.h"
#include "absl/time/clock.h"
#include "absl/time/time.h"
#include "tensorstore/internal/env.h"
#include "tensorstore/internal/http/http_response.h"
#include "tensorstore/internal/http/mock_http_transport.h"
#include "tensorstore/internal/path.h"
#include "tensorstore/internal/testing/scoped_directory.h"
#include "tensorstore/kvstore/s3/credentials/test_utils.h"
#include "tensorstore/util/status_testutil.h"
namespace {
using ::tensorstore::internal::JoinPath;
using ::tensorstore::internal::SetEnv;
using ::tensorstore::internal::UnsetEnv;
using ::tensorstore::internal_http::DefaultMockHttpTransport;
using ::tensorstore::internal_http::HttpResponse;
using ::tensorstore::internal_kvstore_s3::DefaultAwsCredentialsProvider;
using ::tensorstore::internal_kvstore_s3::DefaultEC2MetadataFlow;
using Options =
::tensorstore::internal_kvstore_s3::DefaultAwsCredentialsProvider::Options;
static constexpr char kEndpoint[] = "http:
class CredentialFileFactory
: public tensorstore::internal_testing::ScopedTemporaryDirectory {
public:
std::string WriteCredentialsFile() {
auto p = JoinPath(path(), "aws_config");
std::ofstream ofs(p);
ofs << "[alice]\n"
"aws_access_key_id = AKIAIOSFODNN6EXAMPLE\n"
"aws_secret_access_key = "
"wJalrXUtnFEMI/K7MDENG/bPxRfiCZEXAMPLEKEY\n"
"aws_session_token = abcdef1234567890\n"
"\n";
ofs.close();
return p;
}
};
class DefaultCredentialProviderTest : public ::testing::Test {
protected:
void SetUp() override {
UnsetEnv("AWS_ACCESS_KEY_ID");
UnsetEnv("AWS_SECRET_ACCESS_KEY");
UnsetEnv("AWS_SESSION_TOKEN");
}
};
TEST_F(DefaultCredentialProviderTest, AnonymousCredentials) {
auto mock_transport = std::make_shared<DefaultMockHttpTransport>(
absl::flat_hash_map<std::string, HttpResponse>());
auto provider = std::make_unique<DefaultAwsCredentialsProvider>(
Options{{}, {}, {}, mock_transport});
TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto credentials,
provider->GetCredentials());
EXPECT_TRUE(credentials.IsAnonymous());
EXPECT_EQ(credentials.expires_at, absl::InfiniteFuture());
TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto credentials2,
provider->GetCredentials());
EXPECT_TRUE(credentials2.IsAnonymous());
EXPECT_EQ(credentials2.expires_at, absl::InfiniteFuture());
}
TEST_F(DefaultCredentialProviderTest, EnvironmentCredentialIdempotency) {
SetEnv("AWS_ACCESS_KEY_ID", "access");
SetEnv("AWS_SECRET_ACCESS_KEY", "secret");
SetEnv("AWS_SESSION_TOKEN", "token");
auto provider = std::make_unique<DefaultAwsCredentialsProvider>();
TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto credentials,
provider->GetCredentials());
EXPECT_EQ(credentials.access_key, "access");
EXPECT_EQ(credentials.secret_key, "secret");
EXPECT_EQ(credentials.session_token, "token");
EXPECT_EQ(credentials.expires_at, absl::InfiniteFuture());
TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto credentials2,
provider->GetCredentials());
EXPECT_EQ(credentials.access_key, credentials2.access_key);
EXPECT_EQ(credentials.secret_key, credentials2.secret_key);
EXPECT_EQ(credentials.session_token, credentials2.session_token);
EXPECT_EQ(credentials.expires_at, credentials2.expires_at);
}
TEST_F(DefaultCredentialProviderTest, ConfigureFileProviderFromOptions) {
auto factory = CredentialFileFactory{};
auto credentials_file = factory.WriteCredentialsFile();
auto provider = std::make_unique<DefaultAwsCredentialsProvider>(
Options{credentials_file, "alice"});
TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto credentials,
provider->GetCredentials());
EXPECT_EQ(credentials.access_key, "AKIAIOSFODNN6EXAMPLE");
EXPECT_EQ(credentials.secret_key, "wJalrXUtnFEMI/K7MDENG/bPxRfiCZEXAMPLEKEY");
EXPECT_EQ(credentials.session_token, "abcdef1234567890");
EXPECT_EQ(credentials.expires_at, absl::InfiniteFuture());
TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto credentials2,
provider->GetCredentials());
EXPECT_EQ(credentials.access_key, credentials2.access_key);
EXPECT_EQ(credentials.secret_key, credentials2.secret_key);
EXPECT_EQ(credentials.session_token, credentials2.session_token);
EXPECT_EQ(credentials.expires_at, credentials2.expires_at);
}
TEST_F(DefaultCredentialProviderTest, ConfigureEC2ProviderFromOptions) {
auto now = absl::Now();
auto stuck_clock = [&]() -> absl::Time { return now; };
auto expiry = now + absl::Seconds(200);
auto mock_transport = std::make_shared<DefaultMockHttpTransport>(
DefaultEC2MetadataFlow(kEndpoint, "1234", "ASIA1234567890",
"1234567890abcdef", "token", expiry));
auto provider = std::make_unique<DefaultAwsCredentialsProvider>(
Options{{}, {}, kEndpoint, mock_transport}, stuck_clock);
TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto credentials,
provider->GetCredentials());
EXPECT_EQ(credentials.access_key, "ASIA1234567890");
EXPECT_EQ(credentials.secret_key, "1234567890abcdef");
EXPECT_EQ(credentials.session_token, "token");
EXPECT_EQ(credentials.expires_at, expiry - absl::Seconds(60));
mock_transport->Reset(absl::flat_hash_map<std::string, HttpResponse>{
{"POST http:
HttpResponse{404, absl::Cord{""}}},
});
TENSORSTORE_ASSERT_OK_AND_ASSIGN(credentials, provider->GetCredentials());
EXPECT_EQ(credentials.access_key, "ASIA1234567890");
EXPECT_EQ(credentials.secret_key, "1234567890abcdef");
EXPECT_EQ(credentials.session_token, "token");
EXPECT_EQ(credentials.expires_at, expiry - absl::Seconds(60));
now += absl::Seconds(300);
mock_transport->Reset(
DefaultEC2MetadataFlow(kEndpoint, "1234", "ASIA1234567890",
"1234567890abcdef", "TOKEN", expiry));
TENSORSTORE_ASSERT_OK_AND_ASSIGN(credentials, provider->GetCredentials());
EXPECT_EQ(credentials.access_key, "ASIA1234567890");
EXPECT_EQ(credentials.secret_key, "1234567890abcdef");
EXPECT_EQ(credentials.session_token, "TOKEN");
EXPECT_EQ(credentials.expires_at, expiry - absl::Seconds(60));
mock_transport->Reset(absl::flat_hash_map<std::string, HttpResponse>{
{"POST http:
HttpResponse{404, absl::Cord{""}}},
});
TENSORSTORE_ASSERT_OK_AND_ASSIGN(credentials, provider->GetCredentials());
EXPECT_EQ(credentials.access_key, "");
EXPECT_EQ(credentials.secret_key, "");
EXPECT_EQ(credentials.session_token, "");
EXPECT_EQ(credentials.expires_at, absl::InfiniteFuture());
}
} |
363 | #ifndef TENSORSTORE_INTERNAL_OAUTH2_GOOGLE_SERVICE_ACCOUNT_AUTH_PROVIDER_H_
#define TENSORSTORE_INTERNAL_OAUTH2_GOOGLE_SERVICE_ACCOUNT_AUTH_PROVIDER_H_
#include <functional>
#include <memory>
#include <string>
#include <string_view>
#include "absl/strings/cord.h"
#include "absl/time/time.h"
#include "tensorstore/internal/http/http_response.h"
#include "tensorstore/internal/http/http_transport.h"
#include "tensorstore/internal/oauth2/bearer_token.h"
#include "tensorstore/internal/oauth2/oauth_utils.h"
#include "tensorstore/internal/oauth2/refreshable_auth_provider.h"
#include "tensorstore/util/result.h"
namespace tensorstore {
namespace internal_oauth2 {
class GoogleServiceAccountAuthProvider : public RefreshableAuthProvider {
public:
using AccountCredentials = internal_oauth2::GoogleServiceAccountCredentials;
~GoogleServiceAccountAuthProvider() override = default;
GoogleServiceAccountAuthProvider(
const AccountCredentials& creds,
std::shared_ptr<internal_http::HttpTransport> transport,
std::function<absl::Time()> clock = {});
protected:
virtual Result<internal_http::HttpResponse> IssueRequest(
std::string_view method, std::string_view uri, absl::Cord payload);
private:
Result<BearerTokenWithExpiration> Refresh() override;
const AccountCredentials creds_;
std::string uri_;
std::string scope_;
std::shared_ptr<internal_http::HttpTransport> transport_;
};
}
}
#endif
#include "tensorstore/internal/oauth2/google_service_account_auth_provider.h"
#include <functional>
#include <memory>
#include <string>
#include <string_view>
#include <utility>
#include "absl/strings/cord.h"
#include "absl/time/time.h"
#include "tensorstore/internal/http/http_request.h"
#include "tensorstore/internal/http/http_response.h"
#include "tensorstore/internal/http/http_transport.h"
#include "tensorstore/internal/oauth2/bearer_token.h"
#include "tensorstore/internal/oauth2/oauth_utils.h"
#include "tensorstore/internal/oauth2/refreshable_auth_provider.h"
#include "tensorstore/util/result.h"
#include "tensorstore/util/status.h"
namespace tensorstore {
namespace internal_oauth2 {
using ::tensorstore::Result;
using ::tensorstore::internal_http::HttpRequestBuilder;
using ::tensorstore::internal_http::HttpResponse;
constexpr char kOAuthV4Url[] = "https:
constexpr char kOAuthScope[] = "https:
GoogleServiceAccountAuthProvider::GoogleServiceAccountAuthProvider(
const AccountCredentials& creds,
std::shared_ptr<internal_http::HttpTransport> transport,
std::function<absl::Time()> clock)
: RefreshableAuthProvider(std::move(clock)),
creds_(creds),
uri_(kOAuthV4Url),
scope_(kOAuthScope),
transport_(std::move(transport)) {}
Result<HttpResponse> GoogleServiceAccountAuthProvider::IssueRequest(
std::string_view method, std::string_view uri, absl::Cord payload) {
return transport_
->IssueRequest(
HttpRequestBuilder(method, std::string{uri})
.AddHeader("Content-Type: application/x-www-form-urlencoded")
.BuildRequest(),
internal_http::IssueRequestOptions(std::move(payload)))
.result();
}
Result<BearerTokenWithExpiration> GoogleServiceAccountAuthProvider::Refresh() {
const auto now = GetCurrentTime();
TENSORSTORE_ASSIGN_OR_RETURN(
auto body,
internal_oauth2::BuildSignedJWTRequest(
creds_.private_key,
internal_oauth2::BuildJWTHeader(creds_.private_key_id),
internal_oauth2::BuildJWTClaimBody(creds_.client_email, scope_, uri_,
now, 3600 )));
TENSORSTORE_ASSIGN_OR_RETURN(
auto response, IssueRequest("POST", uri_, absl::Cord(std::move(body))));
TENSORSTORE_RETURN_IF_ERROR(HttpResponseCodeToStatus(response));
TENSORSTORE_ASSIGN_OR_RETURN(auto result, internal_oauth2::ParseOAuthResponse(
response.payload.Flatten()));
return BearerTokenWithExpiration{std::move(result.access_token),
now + absl::Seconds(result.expires_in)};
}
}
} | #include "tensorstore/internal/oauth2/google_service_account_auth_provider.h"
#include <memory>
#include <utility>
#include <vector>
#include <gtest/gtest.h>
#include "absl/container/flat_hash_map.h"
#include "tensorstore/internal/oauth2/fake_private_key.h"
#include "tensorstore/util/result.h"
#include "tensorstore/util/status.h"
namespace {
using ::tensorstore::Result;
using ::tensorstore::internal_http::HttpResponse;
using ::tensorstore::internal_oauth2::GetFakePrivateKey;
using ::tensorstore::internal_oauth2::GoogleServiceAccountAuthProvider;
using ::tensorstore::internal_oauth2::GoogleServiceAccountCredentials;
const char kServiceAccountInfo[] = R"({
"token_type" : "123",
"access_token": "abc",
"expires_in": 456
})";
const GoogleServiceAccountCredentials kCreds{
"a1a111aa1111a11a11a11aa111a111a1a1111111",
GetFakePrivateKey(),
"https:
"foo-email@foo-project.iam.gserviceaccount.com",
};
constexpr char kBody[] =
"grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer&"
"assertion="
"eyJhbGciOiJSUzI1NiIsImtpZCI6ImExYTExMWFhMTExMWExMWExMWExMWFhMTExYTExMWExYT"
"ExMTExMTEiLCJ0eXAiOiJKV1QifQ."
"eyJhdWQiOiJodHRwczovL3d3dy5nb29nbGVhcGlzLmNvbS9vYXV0aDIvdjQvdG9rZW4iLCJleH"
"AiOjE1NDc2Njk3MDMsImlhdCI6MTU0NzY2NjEwMywiaXNzIjoiZm9vLWVtYWlsQGZvby1wcm9q"
"ZWN0LmlhbS5nc2VydmljZWFjY291bnQuY29tIiwic2NvcGUiOiJodHRwczovL3d3dy5nb29nbG"
"VhcGlzLmNvbS9hdXRoL2Nsb3VkLXBsYXRmb3JtIn0.gvM1sjnFXwQkBTTqobnTJqE8ZCrAR-"
"SEevEZB4Quqxd836v7iHjnWBiOkUCZl_o5wQouz5pFuhkQ1BlhhAZNih_Ko2yxBi0W_NuhI-"
"18We8gSMhi8pwfNu6WqNqXkHlQAJebhJQH23yP_A2dxU3Z50maUJaAl9G0e60CIynsaeW-"
"o7QneaPxPEWjOi--XMvkOu-z8eD0CXx1dUrlzINDxWzJFoXzCk2_NZ9-"
"UPzHWai68qKo2FjbtTT3fEPA-L1IN908OWhuN2UHdvPrg_"
"h13GO7kY3K7TsWotsgsLon2KxWYaDpasaY_ZqCIXCeS4jW89gVtsOB3E6B-xdR1Gq-9g";
class TestAuthProvider : public GoogleServiceAccountAuthProvider {
public:
TestAuthProvider(const GoogleServiceAccountCredentials& creds)
: GoogleServiceAccountAuthProvider(creds, nullptr,
[this] { return this->time; }),
time(absl::FromUnixSeconds(1547666103)),
idx(0) {}
virtual Result<HttpResponse> IssueRequest(std::string_view method,
std::string_view uri,
absl::Cord body) {
request.push_back(std::make_pair(std::string(uri), std::string(body)));
if (responses.count(idx) != 0) {
return responses[idx++];
}
return HttpResponse{};
}
absl::Time time;
int idx;
absl::flat_hash_map<int, HttpResponse> responses;
std::vector<std::pair<std::string, std::string>> request;
};
TEST(GoogleServiceAccountAuthProviderTest, InitialState) {
TestAuthProvider auth({"a", "b", "c", "d"});
EXPECT_FALSE(auth.IsValid());
EXPECT_TRUE(auth.IsExpired());
}
TEST(GoogleServiceAccountAuthProviderTest, BadKeys) {
TestAuthProvider auth({"a", "b", "c", "d"});
auto result = auth.GetToken();
EXPECT_FALSE(result.ok()) << result.status();
EXPECT_EQ(0, auth.request.size());
}
TEST(OAuth2AuthProviderTest, NoResponse) {
TestAuthProvider auth(kCreds);
auto result = auth.GetToken();
EXPECT_FALSE(result.ok()) << result.status();
ASSERT_EQ(1, auth.request.size());
EXPECT_EQ("https:
auth.request[0].first);
EXPECT_EQ(kBody, auth.request[0].second);
}
TEST(GoogleServiceAccountAuthProviderTest, Status200) {
TestAuthProvider auth(kCreds);
auth.responses = {
{0,
{200,
absl::Cord(kServiceAccountInfo),
{}}},
{1,
{200,
absl::Cord(kServiceAccountInfo),
{}}},
};
{
auto result = auth.GetToken();
EXPECT_EQ(1, auth.idx);
EXPECT_TRUE(result.ok()) << result.status();
EXPECT_EQ(1, auth.request.size());
EXPECT_EQ(auth.time + absl::Seconds(456), result->expiration);
EXPECT_EQ("abc", result->token);
}
EXPECT_FALSE(auth.IsExpired());
EXPECT_TRUE(auth.IsValid());
auth.time += absl::Seconds(600);
{
auto result = auth.GetToken();
EXPECT_EQ(2, auth.idx);
EXPECT_TRUE(result.ok()) << result.status();
EXPECT_EQ(2, auth.request.size());
EXPECT_EQ(auth.time + absl::Seconds(456), result->expiration);
EXPECT_EQ("abc", result->token);
}
}
} |
364 | #ifndef TENSORFLOW_COMPILER_MLIR_QUANTIZATION_STABLEHLO_CC_SAVED_MODEL_IMPORT_H_
#define TENSORFLOW_COMPILER_MLIR_QUANTIZATION_STABLEHLO_CC_SAVED_MODEL_IMPORT_H_
#include <string>
#include <unordered_set>
#include <vector>
#include "absl/base/attributes.h"
#include "absl/container/flat_hash_map.h"
#include "absl/status/statusor.h"
#include "absl/strings/string_view.h"
#include "mlir/IR/BuiltinOps.h"
#include "mlir/IR/MLIRContext.h"
#include "mlir/IR/OwningOpRef.h"
#include "tensorflow/cc/saved_model/loader.h"
#include "tensorflow/compiler/mlir/quantization/stablehlo/cc/types.h"
#include "tensorflow/compiler/mlir/quantization/stablehlo/quantization_config.pb.h"
namespace mlir::quant::stablehlo {
using ImportedMlirModuleOp =
std::pair<OwningOpRef<ModuleOp>,
std::unique_ptr<::tensorflow::SavedModelBundle>>;
absl::StatusOr<ImportedMlirModuleOp> SavedModelToMlirModuleOp(
absl::string_view saved_model_path,
const std::unordered_set<std::string>& tags,
const std::vector<std::string>& signature_keys,
MLIRContext& ctx ABSL_ATTRIBUTE_LIFETIME_BOUND);
absl::StatusOr<absl::flat_hash_map<FunctionName, FunctionAlias>>
GetFunctionAliases(absl::string_view saved_model_path,
const std::unordered_set<std::string>& tags);
void UpdateFunctionAliases(
absl::flat_hash_map<FunctionName, FunctionAlias>& function_aliases,
ModuleOp module_op);
absl::StatusOr<OwningOpRef<ModuleOp>> ImportSavedModel(
absl::string_view saved_model_path,
const std::vector<std::string>& signature_keys,
const std::unordered_set<std::string>& tags,
const ::stablehlo::quantization::QuantizationConfig& quantization_config,
absl::string_view mlir_dump_file_prefix,
absl::flat_hash_map<FunctionName, FunctionAlias>& function_aliases,
MLIRContext& ctx ABSL_ATTRIBUTE_LIFETIME_BOUND);
}
#endif
#include "tensorflow/compiler/mlir/quantization/stablehlo/cc/saved_model_import.h"
#include <memory>
#include <string>
#include <unordered_set>
#include <utility>
#include <vector>
#include "absl/algorithm/container.h"
#include "absl/base/attributes.h"
#include "absl/container/flat_hash_map.h"
#include "absl/container/flat_hash_set.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/string_view.h"
#include "absl/types/span.h"
#include "mlir/Dialect/Func/IR/FuncOps.h"
#include "mlir/IR/BuiltinAttributes.h"
#include "mlir/IR/BuiltinOps.h"
#include "mlir/IR/MLIRContext.h"
#include "mlir/IR/OwningOpRef.h"
#include "tensorflow/cc/saved_model/loader.h"
#include "tensorflow/cc/saved_model/reader.h"
#include "tensorflow/compiler/mlir/quantization/stablehlo/cc/types.h"
#include "tensorflow/compiler/mlir/quantization/stablehlo/quantization_config.pb.h"
#include "tensorflow/compiler/mlir/quantization/tensorflow/quantize_preprocess.h"
#include "tensorflow/compiler/mlir/tensorflow/translate/mlir_import_options.h"
#include "tensorflow/compiler/mlir/tensorflow/translate/tf_mlir_translate.h"
#include "tensorflow/core/protobuf/meta_graph.pb.h"
#include "tsl/platform/errors.h"
#include "tsl/platform/statusor.h"
namespace mlir::quant::stablehlo {
using ::stablehlo::quantization::QuantizationConfig;
using ::tensorflow::MLIRImportOptions;
using ::tensorflow::SavedModelBundle;
using ::tensorflow::SavedModelSignatureDefsToMlirImport;
using ::tensorflow::quantization::PreprocessAndFreezeGraph;
absl::StatusOr<ImportedMlirModuleOp> SavedModelToMlirModuleOp(
const absl::string_view saved_model_path,
const std::unordered_set<std::string>& tags,
const std::vector<std::string>& signature_keys,
MLIRContext& ctx ABSL_ATTRIBUTE_LIFETIME_BOUND) {
MLIRImportOptions import_options;
import_options.upgrade_legacy = true;
import_options.lift_variables = false;
import_options.include_variables_in_initializers = true;
auto bundle = std::make_unique<SavedModelBundle>();
std::vector<std::string> exported_names = signature_keys;
absl::StatusOr<OwningOpRef<ModuleOp>> module_op =
SavedModelSignatureDefsToMlirImport(saved_model_path, tags,
absl::MakeSpan(exported_names), &ctx,
import_options, &bundle);
if (!module_op.status().ok()) {
return absl::InternalError(absl::StrCat("Failed to import SavedModel: ",
module_op.status().ToString()));
}
return std::make_pair(std::move(*module_op), std::move(bundle));
}
absl::StatusOr<absl::flat_hash_map<FunctionName, FunctionAlias>>
GetFunctionAliases(absl::string_view saved_model_path,
const std::unordered_set<std::string>& tags) {
tensorflow::MetaGraphDef meta_graph;
TF_RETURN_IF_ERROR(tensorflow::ReadMetaGraphDefFromSavedModel(
saved_model_path, tags, &meta_graph));
absl::flat_hash_map<FunctionName, FunctionAlias> function_aliases(
meta_graph.meta_info_def().function_aliases().begin(),
meta_graph.meta_info_def().function_aliases().end());
return function_aliases;
}
void UpdateFunctionAliases(
absl::flat_hash_map<FunctionName, FunctionAlias>& function_aliases,
ModuleOp module_op) {
absl::flat_hash_set<FunctionName> existing_func_names;
module_op->walk([&](func::FuncOp func_op) {
FunctionName func_name = func_op.getSymName().str();
existing_func_names.insert(func_name);
auto original_func_name =
func_op->getAttrOfType<StringAttr>("tf._original_func_name");
if (original_func_name) {
if (auto alias_itr = function_aliases.find(original_func_name.str());
alias_itr != function_aliases.end()) {
const FunctionAlias alias = alias_itr->second;
function_aliases[func_name] = alias;
}
}
});
absl::erase_if(function_aliases, [&existing_func_names](const auto& item) {
return !existing_func_names.contains(item.first);
});
}
absl::StatusOr<OwningOpRef<ModuleOp>> ImportSavedModel(
const absl::string_view saved_model_path,
const std::vector<std::string>& signature_keys,
const std::unordered_set<std::string>& tags,
const QuantizationConfig& quantization_config,
const absl::string_view mlir_dump_file_prefix,
absl::flat_hash_map<FunctionName, FunctionAlias>& function_aliases,
MLIRContext& ctx ABSL_ATTRIBUTE_LIFETIME_BOUND) {
TF_ASSIGN_OR_RETURN(
ImportedMlirModuleOp imported_module,
SavedModelToMlirModuleOp(saved_model_path, tags, signature_keys, ctx));
auto [module_op, saved_model_bundle] = std::move(imported_module);
UpdateFunctionAliases(function_aliases, *module_op);
absl::flat_hash_set<std::string> aliased_function_names;
absl::c_for_each(function_aliases, [&](const auto& aliases) {
return aliased_function_names.insert(aliases.first);
});
TF_RETURN_IF_ERROR(PreprocessAndFreezeGraph(
mlir_dump_file_prefix, true,
aliased_function_names, *module_op, &ctx,
saved_model_bundle == nullptr ? nullptr
: saved_model_bundle->GetSession(),
true, false));
return std::move(module_op);
}
} | #include "tensorflow/compiler/mlir/quantization/stablehlo/cc/saved_model_import.h"
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "absl/container/flat_hash_map.h"
#include "mlir/IR/BuiltinOps.h"
#include "mlir/IR/OwningOpRef.h"
#include "tensorflow/compiler/mlir/quantization/common/test_base.h"
#include "tensorflow/compiler/mlir/quantization/stablehlo/cc/types.h"
namespace mlir::quant::stablehlo {
namespace {
using ::testing::IsEmpty;
using ::testing::Pair;
using ::testing::UnorderedElementsAre;
using UpdateFunctionAliasesTest = ::mlir::quant::QuantizationTestBase;
TEST_F(UpdateFunctionAliasesTest, NoAliasesReturnsEmptyMap) {
OwningOpRef<ModuleOp> module_op = ParseModuleOpString(R"mlir(
func.func private @main(%arg: tensor<1x2xf32>) -> (tensor<1x2xf32>) attributes {tf._original_func_name = "main_original"} {
return %arg : tensor<1x2xf32>
}
)mlir");
ASSERT_TRUE(module_op);
absl::flat_hash_map<FunctionName, FunctionAlias> function_aliases;
UpdateFunctionAliases(function_aliases, *module_op);
EXPECT_THAT(function_aliases, IsEmpty());
}
TEST_F(UpdateFunctionAliasesTest, AliasUpdatedByMlirFunctionName) {
OwningOpRef<ModuleOp> module_op = ParseModuleOpString(R"mlir(
func.func private @main(%arg: tensor<1x2xf32>) -> (tensor<1x2xf32>) attributes {tf._original_func_name = "main_original"} {
return %arg : tensor<1x2xf32>
}
)mlir");
ASSERT_TRUE(module_op);
absl::flat_hash_map<FunctionName, FunctionAlias> function_aliases{
{"main_original", "main_alias"}};
UpdateFunctionAliases(function_aliases, *module_op);
EXPECT_THAT(function_aliases,
UnorderedElementsAre(Pair("main", "main_alias")));
}
TEST_F(UpdateFunctionAliasesTest, IgnoresUnmatchedFunctions) {
OwningOpRef<ModuleOp> module_op = ParseModuleOpString(R"mlir(
func.func private @main(%arg: tensor<1x2xf32>) -> (tensor<1x2xf32>) attributes {tf._original_func_name = "main_original"} {
return %arg : tensor<1x2xf32>
}
)mlir");
ASSERT_TRUE(module_op);
absl::flat_hash_map<FunctionName, FunctionAlias> function_aliases{
{"not_main", "not_main_alias"}};
UpdateFunctionAliases(function_aliases, *module_op);
EXPECT_THAT(function_aliases, IsEmpty());
}
TEST_F(UpdateFunctionAliasesTest,
SkipsFunctionsWithNoOriginalFuncNameAttribute) {
OwningOpRef<ModuleOp> module_op = ParseModuleOpString(R"mlir(
func.func private @main(%arg: tensor<1x2xf32>) -> (tensor<1x2xf32>) {
return %arg : tensor<1x2xf32>
}
)mlir");
ASSERT_TRUE(module_op);
absl::flat_hash_map<FunctionName, FunctionAlias> function_aliases{
{"main_original", "main_alias"}};
UpdateFunctionAliases(function_aliases, *module_op);
EXPECT_THAT(function_aliases, IsEmpty());
}
TEST_F(UpdateFunctionAliasesTest, FunctionNameNotChanged) {
OwningOpRef<ModuleOp> module_op = ParseModuleOpString(R"mlir(
func.func private @main_original(%arg: tensor<1x2xf32>) -> (tensor<1x2xf32>) {
return %arg : tensor<1x2xf32>
}
)mlir");
ASSERT_TRUE(module_op);
absl::flat_hash_map<FunctionName, FunctionAlias> function_aliases{
{"main_original", "main_alias"}};
UpdateFunctionAliases(function_aliases, *module_op);
EXPECT_THAT(function_aliases,
UnorderedElementsAre(Pair("main_original", "main_alias")));
}
}
} |
365 | #ifndef XLA_SERVICE_GPU_MODEL_GPU_PERFORMANCE_MODEL_BASE_H_
#define XLA_SERVICE_GPU_MODEL_GPU_PERFORMANCE_MODEL_BASE_H_
#include <cstdint>
#include <optional>
#include <string>
#include "absl/container/flat_hash_map.h"
#include "absl/strings/str_format.h"
#include "absl/synchronization/mutex.h"
#include "absl/time/time.h"
#include "xla/hlo/ir/hlo_instruction.h"
#include "xla/service/gpu/hlo_fusion_analysis.h"
#include "xla/service/gpu/launch_dimensions.h"
#include "xla/service/gpu/model/fusion_analysis_cache.h"
#include "xla/service/gpu/model/gpu_hlo_cost_analysis.h"
#include "xla/stream_executor/device_description.h"
namespace xla {
namespace gpu {
struct EstimateRunTimeData {
int64_t flops;
int64_t bytes_read;
int64_t bytes_written;
absl::Duration read_time;
absl::Duration write_time;
absl::Duration compute_time;
absl::Duration exec_time;
std::string ToString() const {
return absl::StrFormat(
"EstimateRunTimeData{\n"
" flops: %d\n"
" bytes_read: %d\n"
" bytes_written: %d\n"
" read_time: %s\n"
" write_time: %s\n"
" compute_time: %s\n"
" exec_time: %s\n"
"}",
flops, bytes_read, bytes_written, absl::FormatDuration(read_time),
absl::FormatDuration(write_time), absl::FormatDuration(compute_time),
absl::FormatDuration(exec_time));
}
};
class GpuPerformanceModelCache {
public:
std::optional<EstimateRunTimeData> Get(const HloInstruction& instruction);
std::optional<absl::Duration> Get(const HloInstruction& producer,
const HloInstruction& consumer);
void Set(const HloInstruction& instruction,
const EstimateRunTimeData& runtime_data);
void Set(const HloInstruction& producer, const HloInstruction& consumer,
absl::Duration runtime);
void Invalidate(const HloInstruction& instruction);
private:
absl::Mutex mutex_;
absl::flat_hash_map<const HloInstruction*, EstimateRunTimeData>
instruction_runtime_data_;
absl::flat_hash_map<
const HloInstruction*,
absl::flat_hash_map<const HloInstruction*, absl::Duration>>
fusion_runtime_data_;
};
struct GpuPerformanceModelOptions {
double memory_compute_parallelism = 1.0;
HloFusionAnalysisCache* fusion_analysis_cache = nullptr;
GpuPerformanceModelCache* gpu_performance_model_cache = nullptr;
static GpuPerformanceModelOptions Default() {
return GpuPerformanceModelOptions();
}
static GpuPerformanceModelOptions PriorityFusion(
HloFusionAnalysisCache* fusion_analysis_cache = nullptr,
GpuPerformanceModelCache* gpu_performance_model_cache = nullptr) {
GpuPerformanceModelOptions config;
config.fusion_analysis_cache = fusion_analysis_cache;
config.gpu_performance_model_cache = gpu_performance_model_cache;
config.memory_compute_parallelism = 0.95;
return config;
}
static GpuPerformanceModelOptions ForModule(const HloModule* module) {
return module->config().debug_options().xla_gpu_enable_priority_fusion()
? PriorityFusion()
: Default();
}
};
class GpuPerformanceModelBase {
public:
struct RunTimes {
absl::Duration time_unfused;
absl::Duration time_fused;
};
static constexpr absl::Duration kKernelLaunchOverhead = absl::Microseconds(1);
static constexpr absl::Duration kNcclKernelLaunchOverhead =
absl::Microseconds(5);
static constexpr float kL2CacheSpeedup = 2.5;
static constexpr float kL1CacheSpeedup = 8;
static LaunchDimensions EstimateFusionLaunchDimensions(
const HloFusionAnalysis& fusion_analysis);
static int64_t GetOperandBytesAccessed(
const GpuHloCostAnalysis* cost_analysis, const HloInstruction* instr,
const HloInstruction* operand);
static float GetOperandUtilization(const GpuHloCostAnalysis* cost_analysis,
const HloInstruction* instr,
const HloInstruction* operand);
static float GetCommonUtilization(const GpuHloCostAnalysis* cost_analysis,
const HloInstruction* producer,
int64_t producer_idx_of_operand,
const HloInstruction* consumer);
static int64_t GetSharedOperandBytesAccessed(
const GpuHloCostAnalysis* cost_analysis, const HloInstruction* producer,
const HloInstruction* consumer, const HloInstruction* operand);
static absl::Duration ReadTime(const se::DeviceDescription& gpu_device_info,
int64_t num_blocks, int64_t n_bytes_net,
int64_t n_bytes_total);
static absl::Duration ReadTimeWithDRAMHeuristic(
const se::DeviceDescription& gpu_device_info, int64_t num_blocks,
int64_t n_bytes_net, int64_t n_bytes_total, PrimitiveType element_type,
bool coalesced);
static absl::Duration ProducerInputAccessTime(
const GpuHloCostAnalysis* cost_analysis,
const se::DeviceDescription& gpu_device_info, int64_t num_blocks,
const HloInstruction* producer, const HloFusionAnalysis& fusion_analysis,
const GpuPerformanceModelOptions& config,
const HloInstruction* fused_consumer = nullptr);
static absl::Duration WriteTime(const se::DeviceDescription& gpu_device_info,
int64_t bytes_written);
static absl::Duration ComputeTime(
const se::DeviceDescription& gpu_device_info, int64_t flops,
int64_t num_blocks, int64_t num_threads_per_block);
static absl::Duration CombineComputeAndMemoryAccessTime(
absl::Duration compute_time, absl::Duration memory_access_time,
const GpuPerformanceModelOptions& config);
static void VLogOperandRead(const HloInstruction* operand,
int64_t n_bytes_total, int64_t n_bytes_net,
bool coalesced);
};
}
}
#endif
#include "xla/service/gpu/model/gpu_performance_model_base.h"
#include <algorithm>
#include <cmath>
#include <cstdint>
#include <optional>
#include <vector>
#include "absl/container/flat_hash_set.h"
#include "absl/log/check.h"
#include "absl/log/log.h"
#include "absl/synchronization/mutex.h"
#include "absl/time/time.h"
#include "xla/hlo/ir/hlo_instruction.h"
#include "xla/hlo/ir/hlo_opcode.h"
#include "xla/service/gpu/backend_configs.pb.h"
#include "xla/service/gpu/fusions/fusion_emitter.h"
#include "xla/service/gpu/fusions/fusions.h"
#include "xla/service/gpu/fusions/triton.h"
#include "xla/service/gpu/hlo_fusion_analysis.h"
#include "xla/service/gpu/hlo_traversal.h"
#include "xla/service/gpu/launch_dimensions.h"
#include "xla/service/gpu/model/gpu_hlo_cost_analysis.h"
#include "xla/shape_util.h"
#include "xla/stream_executor/device_description.h"
#include "xla/util.h"
namespace xla {
namespace gpu {
namespace {
bool FusionUsesParameterElementwiseFromRoot(
const HloInstruction* fusion, int parameter_index,
const GpuHloCostAnalysis* cost_analysis) {
return cost_analysis->CommonElementwiseUtilization(
fusion->fused_parameter(parameter_index),
fusion->fused_expression_root()) == 1.f;
}
int GetCoalescingWasteFactor(PrimitiveType element_type,
const se::DeviceDescription& gpu_device_info) {
int64_t element_size_bytes =
element_type == PrimitiveType::TUPLE ||
element_type == PrimitiveType::TOKEN
? 4
: ShapeUtil::ByteSizeOfPrimitiveType(element_type);
return gpu_device_info.dram_to_l2_transaction_size_bytes() /
element_size_bytes;
}
float AdjustBandwidth(const se::DeviceDescription& gpu_device_info,
float bandwidth, int64_t num_blocks) {
float per_block_bandwidth = gpu_device_info.clock_rate_ghz() * 1.0e9f *
gpu_device_info.memory_transactions_per_clock();
float max_bandwidth = num_blocks * per_block_bandwidth;
return std::min(bandwidth, max_bandwidth);
}
}
std::optional<EstimateRunTimeData> GpuPerformanceModelCache::Get(
const HloInstruction& instruction) {
absl::MutexLock lock(&mutex_);
auto it = instruction_runtime_data_.find(&instruction);
if (it != instruction_runtime_data_.end()) {
return it->second;
}
return std::nullopt;
}
std::optional<absl::Duration> GpuPerformanceModelCache::Get(
const HloInstruction& producer, const HloInstruction& consumer) {
absl::MutexLock lock(&mutex_);
auto it = fusion_runtime_data_.find(&producer);
if (it != fusion_runtime_data_.end()) {
auto jt = it->second.find(&consumer);
if (jt != it->second.end()) {
return jt->second;
}
}
return std::nullopt;
}
void GpuPerformanceModelCache::Set(const HloInstruction& instruction,
const EstimateRunTimeData& runtime_data) {
absl::MutexLock lock(&mutex_);
instruction_runtime_data_[&instruction] = runtime_data;
}
void GpuPerformanceModelCache::Set(const HloInstruction& producer,
const HloInstruction& consumer,
absl::Duration runtime) {
absl::MutexLock lock(&mutex_);
fusion_runtime_data_[&producer][&consumer] = runtime;
}
void GpuPerformanceModelCache::Invalidate(const HloInstruction& instruction) {
absl::MutexLock lock(&mutex_);
instruction_runtime_data_.erase(&instruction);
fusion_runtime_data_.erase(&instruction);
for (auto* operand : instruction.operands()) {
if (operand->opcode() == HloOpcode::kGetTupleElement) {
operand = operand->mutable_operand(0);
}
auto it = fusion_runtime_data_.find(operand);
if (it != fusion_runtime_data_.end()) {
it->second.erase(&instruction);
}
}
}
LaunchDimensions GpuPerformanceModelBase::EstimateFusionLaunchDimensions(
const HloFusionAnalysis& fusion_analysis) {
auto emitter =
GetFusionEmitter(PreBufferAssignmentFusionInfo{fusion_analysis});
if (const auto* kernel_emitter =
dynamic_cast<const KernelFusionInterface*>(emitter.get())) {
return kernel_emitter->launch_dimensions();
}
if (const auto* triton_emitter =
dynamic_cast<const TritonFusion*>(emitter.get())) {
if (auto launch_config = triton_emitter->launch_config()) {
return launch_config->launch_dimensions;
}
}
VLOG(5) << "Using fallback launch dimensions estimate for "
<< fusion_analysis.fusion().ToString();
int64_t num_threads_per_block = 128;
int64_t estimated_num_threads =
ShapeUtil::ElementsInRecursive(fusion_analysis.fusion_root(0).shape());
int64_t num_blocks =
CeilOfRatio(estimated_num_threads, num_threads_per_block);
return LaunchDimensions(num_blocks, num_threads_per_block);
}
int64_t GpuPerformanceModelBase::GetOperandBytesAccessed(
const GpuHloCostAnalysis* cost_analysis, const HloInstruction* instr,
const HloInstruction* operand) {
if (!instr->IsUserOf(operand)) {
return 0;
}
return cost_analysis->operand_bytes_accessed(*instr,
instr->operand_index(operand));
}
float GpuPerformanceModelBase::GetOperandUtilization(
const GpuHloCostAnalysis* cost_analysis, const HloInstruction* instr,
const HloInstruction* operand) {
if (operand->IsMultiOutputFusion()) {
float res = 0.f;
for (int64_t i = 0; i < instr->operand_count(); ++i) {
if (instr->operand(i)->opcode() == HloOpcode::kGetTupleElement &&
instr->operand(i)->operand(0) == operand) {
res += cost_analysis->operand_utilization(*instr, i);
}
}
return res;
}
if (!instr->IsUserOf(operand)) {
return 0.f;
}
return cost_analysis->operand_utilization(*instr,
instr->operand_index(operand));
}
float GpuPerformanceModelBase::GetCommonUtilization(
const GpuHloCostAnalysis* cost_analysis, const HloInstruction* producer,
int64_t producer_idx_of_operand, const HloInstruction* consumer) {
const auto* operand = producer->operand(producer_idx_of_operand);
if (!consumer || !consumer->IsUserOf(operand)) {
return 0.f;
}
if (producer->IsElementwise() ||
(producer->opcode() == HloOpcode::kFusion &&
FusionUsesParameterElementwiseFromRoot(producer, producer_idx_of_operand,
cost_analysis))) {
if (consumer->opcode() == HloOpcode::kFusion) {
int64_t consumer_idx_of_common_operand = consumer->operand_index(operand);
float res = 0.f;
std::vector<int64_t> consumer_indices_of_producer;
if (producer->IsMultiOutputFusion()) {
for (int64_t i = 0; i < consumer->operand_count(); ++i) {
if (consumer->operand(i)->opcode() == HloOpcode::kGetTupleElement &&
consumer->operand(i)->operand(0) == producer) {
consumer_indices_of_producer.push_back(i);
}
}
} else {
consumer_indices_of_producer.push_back(
consumer->operand_index(producer));
}
for (int64_t consumer_idx_of_producer : consumer_indices_of_producer) {
res += cost_analysis->CommonElementwiseUtilization(
consumer->fused_parameter(consumer_idx_of_common_operand),
consumer->fused_parameter(consumer_idx_of_producer));
}
return res;
} else if (consumer->IsElementwise()) {
return 1.f;
}
}
return 0.f;
}
int64_t GpuPerformanceModelBase::GetSharedOperandBytesAccessed(
const GpuHloCostAnalysis* cost_analysis, const HloInstruction* producer,
const HloInstruction* consumer, const HloInstruction* operand) {
float producer_utilization_by_consumer =
GetOperandUtilization(cost_analysis, consumer, producer);
int64_t bytes_accessed_by_producer =
GetOperandBytesAccessed(cost_analysis, producer, operand);
int64_t bytes_accessed_by_consumer =
GetOperandBytesAccessed(cost_analysis, consumer, operand);
float common_utilization =
producer->IsUserOf(operand)
? GetCommonUtilization(cost_analysis, producer,
producer->operand_index(operand), consumer)
: 0.f;
int64_t operand_size = cost_analysis->GetShapeSize(operand->shape());
int64_t common_bytes_accessed =
std::llround(operand_size * common_utilization);
return std::llround(bytes_accessed_by_producer *
producer_utilization_by_consumer) +
bytes_accessed_by_consumer - common_bytes_accessed;
}
absl::Duration GpuPerformanceModelBase::ReadTime(
const se::DeviceDescription& gpu_device_info, int64_t num_blocks,
int64_t n_bytes_net, int64_t n_bytes_total) {
float bandwidth = gpu_device_info.memory_bandwidth();
if (n_bytes_net < gpu_device_info.l2_cache_size()) {
bandwidth *= kL2CacheSpeedup;
if (n_bytes_net <
gpu_device_info.l1_cache_size_per_SM() * gpu_device_info.core_count()) {
bandwidth *= kL1CacheSpeedup;
}
}
bandwidth = AdjustBandwidth(gpu_device_info, bandwidth, num_blocks);
return absl::Seconds(n_bytes_total / bandwidth);
}
absl::Duration GpuPerformanceModelBase::ReadTimeWithDRAMHeuristic(
const se::DeviceDescription& gpu_device_info, int64_t num_blocks,
int64_t n_bytes_net, int64_t n_bytes_total, PrimitiveType element_type,
bool coalesced) {
int waste_factor =
coalesced ? 1 : GetCoalescingWasteFactor(element_type, gpu_device_info);
float dram_bandwidth = gpu_device_info.memory_bandwidth() / waste_factor;
float rest_bandwidth = gpu_device_info.memory_bandwidth();
if (n_bytes_net < gpu_device_info.l2_cache_size()) {
rest_bandwidth *= kL2CacheSpeedup;
if (n_bytes_net <
gpu_device_info.l1_cache_size_per_SM() * gpu_device_info.core_count()) {
rest_bandwidth *= kL1CacheSpeedup;
}
} else {
rest_bandwidth /= waste_factor;
}
dram_bandwidth = AdjustBandwidth(gpu_device_info, dram_bandwidth, num_blocks);
rest_bandwidth = AdjustBandwidth(gpu_device_info, rest_bandwidth, num_blocks);
int64_t n_bytes_read_dram = std::min(n_bytes_net, n_bytes_total);
int64_t n_bytes_read_cache = n_bytes_total - n_bytes_read_dram;
return absl::Seconds(n_bytes_read_dram / dram_bandwidth) +
absl::Seconds(n_bytes_read_cache / rest_bandwidth);
}
absl::Duration GpuPerformanceModelBase::ProducerInputAccessTime(
const GpuHloCostAnalysis* cost_analysis,
const se::DeviceDescription& gpu_device_info, int64_t num_blocks,
const HloInstruction* producer, const HloFusionAnalysis& fusion_analysis,
const GpuPerformanceModelOptions& config,
const HloInstruction* fused_consumer) {
absl::Duration ret = absl::ZeroDuration();
float producer_output_utilization =
fused_consumer
? GetOperandUtilization(cost_analysis, fused_consumer, producer)
: 1.f;
for (int i = 0; i < producer->operand_count(); ++i) {
int64_t operand_bytes_accessed =
cost_analysis->operand_bytes_accessed(*producer, i);
float operand_utilization =
cost_analysis->operand_utilization(*producer, i);
int64_t n_bytes_net = std::llround(operand_bytes_accessed /
std::max(operand_utilization, 1.0f));
float common_utilization = GetCommonUtilization(
cost_analysis, producer, i, fused_consumer);
CHECK_LE(common_utilization, producer_output_utilization);
float n_bytes_total = operand_bytes_accessed *
(producer_output_utilization - common_utilization);
ret += ReadTime(gpu_device_info, num_blocks, n_bytes_net, n_bytes_total);
}
return ret;
}
absl::Duration GpuPerformanceModelBase::WriteTime(
const se::DeviceDescription& gpu_device_info, int64_t bytes_written) {
return absl::Seconds(1.0f * bytes_written /
gpu_device_info.memory_bandwidth());
}
absl::Duration GpuPerformanceModelBase::ComputeTime(
const se::DeviceDescription& gpu_device_info, int64_t flops,
int64_t num_blocks, int64_t num_threads_per_block) {
int64_t n_active_fpus_per_core =
std::min<int64_t>(num_threads_per_block, gpu_device_info.fpus_per_core());
int64_t n_active_core =
std::min<int64_t>(num_blocks, gpu_device_info.core_count());
int64_t fpu_count = n_active_core * n_active_fpus_per_core;
int64_t flop_per_ns_per_fpu = gpu_device_info.clock_rate_ghz() * 2;
int64_t flop_per_ns_effective = flop_per_ns_per_fpu * fpu_count;
return absl::Nanoseconds(1.0f * flops / flop_per_ns_effective);
}
absl::Duration GpuPerformanceModelBase::CombineComputeAndMemoryAccessTime(
absl::Duration compute_time, absl::Duration memory_access_time,
const GpuPerformanceModelOptions& config) {
return compute_time + memory_access_time -
std::min(compute_time, memory_access_time) *
config.memory_compute_parallelism;
}
void GpuPerformanceModelBase::VLogOperandRead(const HloInstruction* operand,
int64_t n_bytes_total,
int64_t n_bytes_net,
bool coalesced) {
VLOG(8) << "operand " << operand->name()
<< ", n_bytes_total: " << n_bytes_total
<< ", n_bytes_net: " << n_bytes_net << ", coalesced: " << coalesced;
}
}
} | #include "xla/service/gpu/model/gpu_performance_model_base.h"
#include <cstdint>
#include <gtest/gtest.h>
#include "absl/strings/string_view.h"
#include "xla/hlo/ir/hlo_computation.h"
#include "xla/hlo/ir/hlo_instruction.h"
#include "xla/service/gpu/backend_configs.pb.h"
#include "xla/service/gpu/gpu_device_info_for_tests.h"
#include "xla/service/gpu/hlo_fusion_analysis.h"
#include "xla/service/gpu/model/gpu_hlo_cost_analysis.h"
#include "xla/shape.h"
#include "xla/shape_util.h"
#include "xla/stream_executor/device_description.h"
#include "xla/test_helpers.h"
#include "xla/tests/hlo_test_base.h"
#include "tsl/platform/statusor.h"
namespace xla {
namespace gpu {
namespace {
class GpuPerformanceModelBaseTest : public HloTestBase {
public:
GpuHloCostAnalysis::ShapeSizeFunction ShapeSizeBytesFunction() const {
return [&](const Shape& shape) {
constexpr int64_t kPointerSize = 8;
return ShapeUtil::ByteSizeOf(shape, kPointerSize);
};
}
GpuHloCostAnalysis::Options options_{ShapeSizeBytesFunction(),
{},
true};
se::DeviceDescription device_info_{TestGpuDeviceInfo::RTXA6000DeviceInfo()};
GpuHloCostAnalysis analysis_{options_, &device_info_};
GpuPerformanceModelBaseTest() : HloTestBase() {}
};
TEST_F(GpuPerformanceModelBaseTest, SharedOperandBytesAccessed_InPlaceDUS) {
absl::string_view hlo_string = R"(
HloModule m
ENTRY entry_computation {
param_0 = f32[8,16] parameter(0)
param_1 = f32[4,4] parameter(1)
c_0 = s32[] constant(0)
log = f32[4,4] log(param_1)
ROOT dynamic-update-slice = f32[8,16] dynamic-update-slice(param_0, log, c_0, c_0)
}
)";
TF_ASSERT_OK_AND_ASSIGN(auto module,
ParseAndReturnVerifiedModule(hlo_string));
auto computation = module->entry_computation();
ASSERT_IS_OK(computation->Accept(&analysis_));
auto dus_consumer = computation->root_instruction();
auto log_producer = dus_consumer->mutable_operand(1);
auto get_shared_operand_bytes_accessed = [&](const HloInstruction* operand) {
return GpuPerformanceModelBase::GetSharedOperandBytesAccessed(
&analysis_, log_producer, dus_consumer, operand);
};
EXPECT_EQ(get_shared_operand_bytes_accessed(dus_consumer->operand(0)), 0);
EXPECT_EQ(get_shared_operand_bytes_accessed(log_producer->operand(0)), 64);
}
TEST_F(GpuPerformanceModelBaseTest, SharedOperandBytesAccessed_DUS) {
absl::string_view hlo_string = R"(
HloModule m
ENTRY entry_computation {
param_0 = f32[8,16] parameter(0)
param_1 = f32[4,4] parameter(1)
c_0 = s32[] constant(0)
log = f32[8,16] log(param_0)
ROOT dynamic-update-slice = f32[8,16] dynamic-update-slice(log, param_1, c_0, c_0)
}
)";
TF_ASSERT_OK_AND_ASSIGN(auto module,
ParseAndReturnVerifiedModule(hlo_string));
auto computation = module->entry_computation();
ASSERT_IS_OK(computation->Accept(&analysis_));
auto dus_consumer = computation->root_instruction();
auto log_producer = dus_consumer->mutable_operand(0);
auto get_shared_operand_bytes_accessed = [&](const HloInstruction* operand) {
return GpuPerformanceModelBase::GetSharedOperandBytesAccessed(
&analysis_, log_producer, dus_consumer, operand);
};
EXPECT_EQ(get_shared_operand_bytes_accessed(dus_consumer->operand(1)), 64);
EXPECT_EQ(get_shared_operand_bytes_accessed(log_producer->operand(0)), 448);
}
TEST_F(GpuPerformanceModelBaseTest,
ReduceBroadcastedDim_IncorrectBytesAccessed) {
absl::string_view hlo_string = R"(
HloModule m
add {
p0 = f32[] parameter(0)
p1 = f32[] parameter(1)
ROOT add = f32[] add(p0, p1)
}
f1 {
p0 = f32[128] parameter(0)
c0 = f32[] constant(0)
broadcast = f32[128,256] broadcast(p0), dimensions={0}
ROOT reduce = f32[128] reduce(broadcast, c0), dimensions={1}, to_apply=add
}
ENTRY entry_computation {
param_0 = f32[128] parameter(0)
param_1 = f32[4,4] parameter(1)
ROOT fusion = f32[128] fusion(param_0), kind=kLoop, calls=f1
}
)";
TF_ASSERT_OK_AND_ASSIGN(auto module,
ParseAndReturnVerifiedModule(hlo_string));
auto computation = module->entry_computation();
ASSERT_IS_OK(computation->Accept(&analysis_));
auto root = computation->root_instruction();
EXPECT_EQ(GpuPerformanceModelBase::GetOperandBytesAccessed(&analysis_, root,
root->operand(0)),
131072);
}
TEST_F(GpuPerformanceModelBaseTest, ElementwiseBitcast_IncorrectBytesAccessed) {
absl::string_view hlo_string = R"(
HloModule m
f1 {
p0 = f32[128] parameter(0)
bitcast.1 = f32[8,16] bitcast(p0)
log = f32[128] log(p0)
bitcast.2 = f32[8,16] bitcast(log)
ROOT add = f32[8,16] add(bitcast.1, bitcast.2)
}
ENTRY entry_computation {
param_0 = f32[128] parameter(0)
ROOT fusion = f32[8,16] fusion(param_0), kind=kLoop, calls=f1
}
)";
TF_ASSERT_OK_AND_ASSIGN(auto module,
ParseAndReturnVerifiedModule(hlo_string));
auto computation = module->entry_computation();
ASSERT_IS_OK(computation->Accept(&analysis_));
auto root = computation->root_instruction();
EXPECT_EQ(GpuPerformanceModelBase::GetOperandBytesAccessed(&analysis_, root,
root->operand(0)),
1024);
}
TEST_F(GpuPerformanceModelBaseTest, EstimateFusionLaunchDimensions_LoopFusion) {
absl::string_view hlo_string = R"(
HloModule m
f1 {
p0 = f32[8,16,128] parameter(0)
log = f32[8,16,128] log(p0)
ROOT add = f32[8,16,128] add(p0, log)
}
ENTRY entry_computation {
param_0 = f32[8,16,128] parameter(0)
ROOT fusion = f32[8,16,128] fusion(param_0), kind=kLoop, calls=f1
}
)";
TF_ASSERT_OK_AND_ASSIGN(auto module,
ParseAndReturnVerifiedModule(hlo_string));
auto fusion_analysis = AnalyzeFusion(
*module->entry_computation()->root_instruction(), device_info_);
auto launch_dimensions =
GpuPerformanceModelBase::EstimateFusionLaunchDimensions(fusion_analysis);
EXPECT_EQ(launch_dimensions.num_blocks(), 16);
EXPECT_EQ(launch_dimensions.num_threads_per_block(), 1024);
}
TEST_F(GpuPerformanceModelBaseTest,
EstimateFusionLaunchDimensions_TritonSoftMaxFusion) {
absl::string_view hlo_string = R"(
max {
p1 = f32[] parameter(1)
p0 = f32[] parameter(0)
ROOT m = f32[] maximum(p0, p1)
}
triton_softmax_computation {
p0 = f32[16,970] parameter(0)
constant = f32[] constant(-inf)
reduce = f32[16] reduce(p0, constant), dimensions={1}, to_apply=max
broadcast = f32[16,970] broadcast(reduce), dimensions={0}
ROOT subtract = f32[16,970] subtract(p0, broadcast)
}
ENTRY e {
p0 = f32[16,970]{1,0} parameter(0)
ROOT r = f32[16,970]{1,0} fusion(p0), kind=kCustom,
calls=triton_softmax_computation,
backend_config={"fusion_backend_config": {kind: "__triton","block_level_fusion_config":{"output_tile_sizes":["1","970"],"num_warps":"2"}}}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
ParseAndReturnVerifiedModule(hlo_string));
auto fusion_analysis = AnalyzeFusion(
*module->entry_computation()->root_instruction(), device_info_);
auto launch_dimensions =
GpuPerformanceModelBase::EstimateFusionLaunchDimensions(fusion_analysis);
EXPECT_EQ(launch_dimensions.num_blocks(), 16);
EXPECT_EQ(launch_dimensions.num_threads_per_block(), 64);
}
TEST_F(GpuPerformanceModelBaseTest,
EstimateFusionLaunchDimensions_CudnnFusion) {
absl::string_view hlo_string = R"(
fusion1 {
p0 = f32[32,96] parameter(0)
p1 = f32[96,256] parameter(1)
ROOT r = f32[32,256] dot(p0, p1),
lhs_contracting_dims={1}, rhs_contracting_dims={0}
}
ENTRY e {
p0 = f32[32,96] parameter(0)
p1 = f32[96,256] parameter(1)
ROOT _ = f32[32,256] fusion(p0, p1), kind=kCustom, calls=fusion1,
backend_config={"fusion_backend_config": {kind: "__cudnn$fusion"}}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
ParseAndReturnVerifiedModule(hlo_string));
auto fusion_analysis = AnalyzeFusion(
*module->entry_computation()->root_instruction(), device_info_);
auto launch_dimensions =
GpuPerformanceModelBase::EstimateFusionLaunchDimensions(fusion_analysis);
EXPECT_EQ(launch_dimensions.num_blocks(), 64);
EXPECT_EQ(launch_dimensions.num_threads_per_block(), 128);
}
}
}
} |
366 | #ifndef TENSORFLOW_CORE_UTIL_BAD_INDICES_POLICY_H_
#define TENSORFLOW_CORE_UTIL_BAD_INDICES_POLICY_H_
#include "absl/status/statusor.h"
#include "absl/strings/string_view.h"
namespace tensorflow {
enum class BadIndicesPolicy {
kDefault,
kError,
kIgnore,
};
absl::StatusOr<BadIndicesPolicy> BadIndicesPolicyFromString(
absl::string_view str);
}
#endif
#include "tensorflow/core/util/bad_indices_policy.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/string_view.h"
namespace tensorflow {
constexpr char kDefault[] = "DEFAULT";
constexpr char kErrorStr[] = "ERROR";
constexpr char kIgnoreStr[] = "IGNORE";
absl::StatusOr<BadIndicesPolicy> BadIndicesPolicyFromString(
absl::string_view str) {
if (str.empty()) return BadIndicesPolicy::kDefault;
if (str == kDefault) return BadIndicesPolicy::kDefault;
if (str == kErrorStr) return BadIndicesPolicy::kError;
if (str == kIgnoreStr) return BadIndicesPolicy::kIgnore;
return absl::InvalidArgumentError(
absl::StrCat("Unknown bad indices handling attribute: ", str));
}
} | #include "tensorflow/core/util/bad_indices_policy.h"
#include <gmock/gmock.h>
#include "absl/status/statusor.h"
#include "absl/strings/string_view.h"
#include "tensorflow/core/platform/test.h"
namespace tensorflow {
namespace {
constexpr absl::string_view kDefault = "DEFAULT";
constexpr absl::string_view kErrorStr = "ERROR";
constexpr absl::string_view kIgnoreStr = "IGNORE";
class BadIndicesPolicyFromStringTest : public ::testing::Test {
protected:
void TestValidInput(absl::string_view input, BadIndicesPolicy expected) {
absl::StatusOr<BadIndicesPolicy> result = BadIndicesPolicyFromString(input);
ASSERT_TRUE(result.ok());
EXPECT_EQ(result.value(), expected);
}
};
TEST_F(BadIndicesPolicyFromStringTest, EmptyString) {
TestValidInput("", BadIndicesPolicy::kDefault);
}
TEST_F(BadIndicesPolicyFromStringTest, DefaultKeyword) {
TestValidInput(kDefault, BadIndicesPolicy::kDefault);
}
TEST_F(BadIndicesPolicyFromStringTest, ErrorKeyword) {
TestValidInput(kErrorStr, BadIndicesPolicy::kError);
}
TEST_F(BadIndicesPolicyFromStringTest, IgnoreKeyword) {
TestValidInput(kIgnoreStr, BadIndicesPolicy::kIgnore);
}
TEST_F(BadIndicesPolicyFromStringTest, InvalidInput) {
absl::StatusOr<BadIndicesPolicy> result =
BadIndicesPolicyFromString("unknown");
ASSERT_FALSE(result.ok());
EXPECT_THAT(result.status().message(),
::testing::HasSubstr("Unknown bad indices handling attribute"));
}
}
} |
367 | #ifndef QUICHE_HTTP2_HPACK_DECODER_HPACK_DECODER_STRING_BUFFER_H_
#define QUICHE_HTTP2_HPACK_DECODER_HPACK_DECODER_STRING_BUFFER_H_
#include <stddef.h>
#include <ostream>
#include <string>
#include "absl/strings/string_view.h"
#include "quiche/http2/hpack/huffman/hpack_huffman_decoder.h"
#include "quiche/common/platform/api/quiche_export.h"
namespace http2 {
class QUICHE_EXPORT HpackDecoderStringBuffer {
public:
enum class State : uint8_t { RESET, COLLECTING, COMPLETE };
enum class Backing : uint8_t { RESET, UNBUFFERED, BUFFERED };
HpackDecoderStringBuffer();
~HpackDecoderStringBuffer();
HpackDecoderStringBuffer(const HpackDecoderStringBuffer&) = delete;
HpackDecoderStringBuffer& operator=(const HpackDecoderStringBuffer&) = delete;
void Reset();
void OnStart(bool huffman_encoded, size_t len);
bool OnData(const char* data, size_t len);
bool OnEnd();
void BufferStringIfUnbuffered();
bool IsBuffered() const;
size_t BufferedLength() const;
absl::string_view str() const;
absl::string_view GetStringIfComplete() const;
std::string ReleaseString();
State state_for_testing() const { return state_; }
Backing backing_for_testing() const { return backing_; }
void OutputDebugStringTo(std::ostream& out) const;
private:
std::string buffer_;
absl::string_view value_;
HpackHuffmanDecoder decoder_;
size_t remaining_len_;
bool is_huffman_encoded_;
State state_;
Backing backing_;
};
QUICHE_EXPORT std::ostream& operator<<(std::ostream& out,
const HpackDecoderStringBuffer& v);
}
#endif
#include "quiche/http2/hpack/decoder/hpack_decoder_string_buffer.h"
#include <ostream>
#include <string>
#include <utility>
#include "quiche/common/platform/api/quiche_bug_tracker.h"
#include "quiche/common/platform/api/quiche_logging.h"
namespace http2 {
std::ostream& operator<<(std::ostream& out,
const HpackDecoderStringBuffer::State v) {
switch (v) {
case HpackDecoderStringBuffer::State::RESET:
return out << "RESET";
case HpackDecoderStringBuffer::State::COLLECTING:
return out << "COLLECTING";
case HpackDecoderStringBuffer::State::COMPLETE:
return out << "COMPLETE";
}
int unknown = static_cast<int>(v);
QUICHE_BUG(http2_bug_50_1)
<< "Invalid HpackDecoderStringBuffer::State: " << unknown;
return out << "HpackDecoderStringBuffer::State(" << unknown << ")";
}
std::ostream& operator<<(std::ostream& out,
const HpackDecoderStringBuffer::Backing v) {
switch (v) {
case HpackDecoderStringBuffer::Backing::RESET:
return out << "RESET";
case HpackDecoderStringBuffer::Backing::UNBUFFERED:
return out << "UNBUFFERED";
case HpackDecoderStringBuffer::Backing::BUFFERED:
return out << "BUFFERED";
}
auto v2 = static_cast<int>(v);
QUICHE_BUG(http2_bug_50_2)
<< "Invalid HpackDecoderStringBuffer::Backing: " << v2;
return out << "HpackDecoderStringBuffer::Backing(" << v2 << ")";
}
HpackDecoderStringBuffer::HpackDecoderStringBuffer()
: remaining_len_(0),
is_huffman_encoded_(false),
state_(State::RESET),
backing_(Backing::RESET) {}
HpackDecoderStringBuffer::~HpackDecoderStringBuffer() = default;
void HpackDecoderStringBuffer::Reset() {
QUICHE_DVLOG(3) << "HpackDecoderStringBuffer::Reset";
state_ = State::RESET;
}
void HpackDecoderStringBuffer::OnStart(bool huffman_encoded, size_t len) {
QUICHE_DVLOG(2) << "HpackDecoderStringBuffer::OnStart";
QUICHE_DCHECK_EQ(state_, State::RESET);
remaining_len_ = len;
is_huffman_encoded_ = huffman_encoded;
state_ = State::COLLECTING;
if (huffman_encoded) {
decoder_.Reset();
buffer_.clear();
backing_ = Backing::BUFFERED;
len = len * 8 / 5;
if (buffer_.capacity() < len) {
buffer_.reserve(len);
}
} else {
backing_ = Backing::RESET;
value_ = absl::string_view();
}
}
bool HpackDecoderStringBuffer::OnData(const char* data, size_t len) {
QUICHE_DVLOG(2) << "HpackDecoderStringBuffer::OnData state=" << state_
<< ", backing=" << backing_;
QUICHE_DCHECK_EQ(state_, State::COLLECTING);
QUICHE_DCHECK_LE(len, remaining_len_);
remaining_len_ -= len;
if (is_huffman_encoded_) {
QUICHE_DCHECK_EQ(backing_, Backing::BUFFERED);
return decoder_.Decode(absl::string_view(data, len), &buffer_);
}
if (backing_ == Backing::RESET) {
if (remaining_len_ == 0) {
value_ = absl::string_view(data, len);
backing_ = Backing::UNBUFFERED;
return true;
}
backing_ = Backing::BUFFERED;
buffer_.reserve(remaining_len_ + len);
buffer_.assign(data, len);
return true;
}
QUICHE_DCHECK_EQ(backing_, Backing::BUFFERED);
buffer_.append(data, len);
return true;
}
bool HpackDecoderStringBuffer::OnEnd() {
QUICHE_DVLOG(2) << "HpackDecoderStringBuffer::OnEnd";
QUICHE_DCHECK_EQ(state_, State::COLLECTING);
QUICHE_DCHECK_EQ(0u, remaining_len_);
if (is_huffman_encoded_) {
QUICHE_DCHECK_EQ(backing_, Backing::BUFFERED);
if (!decoder_.InputProperlyTerminated()) {
return false;
}
value_ = buffer_;
} else if (backing_ == Backing::BUFFERED) {
value_ = buffer_;
}
state_ = State::COMPLETE;
return true;
}
void HpackDecoderStringBuffer::BufferStringIfUnbuffered() {
QUICHE_DVLOG(3) << "HpackDecoderStringBuffer::BufferStringIfUnbuffered state="
<< state_ << ", backing=" << backing_;
if (state_ != State::RESET && backing_ == Backing::UNBUFFERED) {
QUICHE_DVLOG(2)
<< "HpackDecoderStringBuffer buffering std::string of length "
<< value_.size();
buffer_.assign(value_.data(), value_.size());
if (state_ == State::COMPLETE) {
value_ = buffer_;
}
backing_ = Backing::BUFFERED;
}
}
bool HpackDecoderStringBuffer::IsBuffered() const {
QUICHE_DVLOG(3) << "HpackDecoderStringBuffer::IsBuffered";
return state_ != State::RESET && backing_ == Backing::BUFFERED;
}
size_t HpackDecoderStringBuffer::BufferedLength() const {
QUICHE_DVLOG(3) << "HpackDecoderStringBuffer::BufferedLength";
return IsBuffered() ? buffer_.size() : 0;
}
absl::string_view HpackDecoderStringBuffer::str() const {
QUICHE_DVLOG(3) << "HpackDecoderStringBuffer::str";
QUICHE_DCHECK_EQ(state_, State::COMPLETE);
return value_;
}
absl::string_view HpackDecoderStringBuffer::GetStringIfComplete() const {
if (state_ != State::COMPLETE) {
return {};
}
return str();
}
std::string HpackDecoderStringBuffer::ReleaseString() {
QUICHE_DVLOG(3) << "HpackDecoderStringBuffer::ReleaseString";
QUICHE_DCHECK_EQ(state_, State::COMPLETE);
QUICHE_DCHECK_EQ(backing_, Backing::BUFFERED);
if (state_ == State::COMPLETE) {
state_ = State::RESET;
if (backing_ == Backing::BUFFERED) {
return std::move(buffer_);
} else {
return std::string(value_);
}
}
return "";
}
void HpackDecoderStringBuffer::OutputDebugStringTo(std::ostream& out) const {
out << "{state=" << state_;
if (state_ != State::RESET) {
out << ", backing=" << backing_;
out << ", remaining_len=" << remaining_len_;
out << ", is_huffman_encoded=" << is_huffman_encoded_;
if (backing_ == Backing::BUFFERED) {
out << ", buffer: " << buffer_;
} else {
out << ", value: " << value_;
}
}
out << "}";
}
std::ostream& operator<<(std::ostream& out, const HpackDecoderStringBuffer& v) {
v.OutputDebugStringTo(out);
return out;
}
} | #include "quiche/http2/hpack/decoder/hpack_decoder_string_buffer.h"
#include <initializer_list>
#include <sstream>
#include <string>
#include "absl/strings/escaping.h"
#include "absl/strings/match.h"
#include "quiche/http2/test_tools/verify_macros.h"
#include "quiche/common/platform/api/quiche_logging.h"
#include "quiche/common/platform/api/quiche_test.h"
using ::testing::AssertionResult;
using ::testing::AssertionSuccess;
using ::testing::HasSubstr;
namespace http2 {
namespace test {
namespace {
class HpackDecoderStringBufferTest : public quiche::test::QuicheTest {
protected:
typedef HpackDecoderStringBuffer::State State;
typedef HpackDecoderStringBuffer::Backing Backing;
State state() const { return buf_.state_for_testing(); }
Backing backing() const { return buf_.backing_for_testing(); }
AssertionResult VerifyLogHasSubstrs(std::initializer_list<std::string> strs) {
QUICHE_VLOG(1) << buf_;
std::ostringstream ss;
buf_.OutputDebugStringTo(ss);
std::string dbg_str(ss.str());
for (const auto& expected : strs) {
HTTP2_VERIFY_TRUE(absl::StrContains(dbg_str, expected));
}
return AssertionSuccess();
}
HpackDecoderStringBuffer buf_;
};
TEST_F(HpackDecoderStringBufferTest, PlainWhole) {
absl::string_view data("some text.");
QUICHE_LOG(INFO) << buf_;
EXPECT_EQ(state(), State::RESET);
buf_.OnStart( false, data.size());
EXPECT_EQ(state(), State::COLLECTING);
EXPECT_EQ(backing(), Backing::RESET);
QUICHE_LOG(INFO) << buf_;
EXPECT_TRUE(buf_.OnData(data.data(), data.size()));
EXPECT_EQ(state(), State::COLLECTING);
EXPECT_EQ(backing(), Backing::UNBUFFERED);
EXPECT_TRUE(buf_.OnEnd());
EXPECT_EQ(state(), State::COMPLETE);
EXPECT_EQ(backing(), Backing::UNBUFFERED);
EXPECT_EQ(0u, buf_.BufferedLength());
EXPECT_TRUE(VerifyLogHasSubstrs(
{"state=COMPLETE", "backing=UNBUFFERED", "value: some text."}));
EXPECT_EQ(data.data(), buf_.str().data());
buf_.BufferStringIfUnbuffered();
QUICHE_LOG(INFO) << buf_;
EXPECT_EQ(backing(), Backing::BUFFERED);
EXPECT_EQ(buf_.BufferedLength(), data.size());
EXPECT_EQ(data, buf_.str());
EXPECT_NE(data.data(), buf_.str().data());
EXPECT_TRUE(VerifyLogHasSubstrs(
{"state=COMPLETE", "backing=BUFFERED", "buffer: some text."}));
}
TEST_F(HpackDecoderStringBufferTest, PlainSplit) {
absl::string_view data("some text.");
absl::string_view part1 = data.substr(0, 1);
absl::string_view part2 = data.substr(1);
EXPECT_EQ(state(), State::RESET);
buf_.OnStart( false, data.size());
EXPECT_EQ(state(), State::COLLECTING);
EXPECT_EQ(backing(), Backing::RESET);
EXPECT_TRUE(buf_.OnData(part1.data(), part1.size()));
EXPECT_EQ(state(), State::COLLECTING);
EXPECT_EQ(backing(), Backing::BUFFERED);
EXPECT_EQ(buf_.BufferedLength(), part1.size());
QUICHE_LOG(INFO) << buf_;
EXPECT_TRUE(buf_.OnData(part2.data(), part2.size()));
EXPECT_EQ(state(), State::COLLECTING);
EXPECT_EQ(backing(), Backing::BUFFERED);
EXPECT_EQ(buf_.BufferedLength(), data.size());
EXPECT_TRUE(buf_.OnEnd());
EXPECT_EQ(state(), State::COMPLETE);
EXPECT_EQ(backing(), Backing::BUFFERED);
EXPECT_EQ(buf_.BufferedLength(), data.size());
QUICHE_LOG(INFO) << buf_;
absl::string_view buffered = buf_.str();
EXPECT_EQ(data, buffered);
EXPECT_NE(data.data(), buffered.data());
buf_.BufferStringIfUnbuffered();
EXPECT_EQ(backing(), Backing::BUFFERED);
EXPECT_EQ(buf_.BufferedLength(), data.size());
EXPECT_EQ(buffered, buf_.str());
EXPECT_EQ(buffered.data(), buf_.str().data());
}
TEST_F(HpackDecoderStringBufferTest, HuffmanWhole) {
std::string encoded;
ASSERT_TRUE(absl::HexStringToBytes("f1e3c2e5f23a6ba0ab90f4ff", &encoded));
absl::string_view decoded("www.example.com");
EXPECT_EQ(state(), State::RESET);
buf_.OnStart( true, encoded.size());
EXPECT_EQ(state(), State::COLLECTING);
EXPECT_TRUE(buf_.OnData(encoded.data(), encoded.size()));
EXPECT_EQ(state(), State::COLLECTING);
EXPECT_EQ(backing(), Backing::BUFFERED);
EXPECT_TRUE(buf_.OnEnd());
EXPECT_EQ(state(), State::COMPLETE);
EXPECT_EQ(backing(), Backing::BUFFERED);
EXPECT_EQ(buf_.BufferedLength(), decoded.size());
EXPECT_EQ(decoded, buf_.str());
EXPECT_TRUE(VerifyLogHasSubstrs(
{"{state=COMPLETE", "backing=BUFFERED", "buffer: www.example.com}"}));
std::string s = buf_.ReleaseString();
EXPECT_EQ(s, decoded);
EXPECT_EQ(state(), State::RESET);
}
TEST_F(HpackDecoderStringBufferTest, HuffmanSplit) {
std::string encoded;
ASSERT_TRUE(absl::HexStringToBytes("f1e3c2e5f23a6ba0ab90f4ff", &encoded));
std::string part1 = encoded.substr(0, 5);
std::string part2 = encoded.substr(5);
absl::string_view decoded("www.example.com");
EXPECT_EQ(state(), State::RESET);
buf_.OnStart( true, encoded.size());
EXPECT_EQ(state(), State::COLLECTING);
EXPECT_EQ(backing(), Backing::BUFFERED);
EXPECT_EQ(0u, buf_.BufferedLength());
QUICHE_LOG(INFO) << buf_;
EXPECT_TRUE(buf_.OnData(part1.data(), part1.size()));
EXPECT_EQ(state(), State::COLLECTING);
EXPECT_EQ(backing(), Backing::BUFFERED);
EXPECT_GT(buf_.BufferedLength(), 0u);
EXPECT_LT(buf_.BufferedLength(), decoded.size());
QUICHE_LOG(INFO) << buf_;
EXPECT_TRUE(buf_.OnData(part2.data(), part2.size()));
EXPECT_EQ(state(), State::COLLECTING);
EXPECT_EQ(backing(), Backing::BUFFERED);
EXPECT_EQ(buf_.BufferedLength(), decoded.size());
QUICHE_LOG(INFO) << buf_;
EXPECT_TRUE(buf_.OnEnd());
EXPECT_EQ(state(), State::COMPLETE);
EXPECT_EQ(backing(), Backing::BUFFERED);
EXPECT_EQ(buf_.BufferedLength(), decoded.size());
EXPECT_EQ(decoded, buf_.str());
QUICHE_LOG(INFO) << buf_;
buf_.Reset();
EXPECT_EQ(state(), State::RESET);
QUICHE_LOG(INFO) << buf_;
}
TEST_F(HpackDecoderStringBufferTest, InvalidHuffmanOnData) {
std::string encoded;
ASSERT_TRUE(absl::HexStringToBytes("ffffffff", &encoded));
buf_.OnStart( true, encoded.size());
EXPECT_EQ(state(), State::COLLECTING);
EXPECT_FALSE(buf_.OnData(encoded.data(), encoded.size()));
EXPECT_EQ(state(), State::COLLECTING);
EXPECT_EQ(backing(), Backing::BUFFERED);
QUICHE_LOG(INFO) << buf_;
}
TEST_F(HpackDecoderStringBufferTest, InvalidHuffmanOnEnd) {
std::string encoded;
ASSERT_TRUE(absl::HexStringToBytes("00", &encoded));
buf_.OnStart( true, encoded.size());
EXPECT_EQ(state(), State::COLLECTING);
EXPECT_TRUE(buf_.OnData(encoded.data(), encoded.size()));
EXPECT_EQ(state(), State::COLLECTING);
EXPECT_EQ(backing(), Backing::BUFFERED);
EXPECT_FALSE(buf_.OnEnd());
QUICHE_LOG(INFO) << buf_;
}
}
}
} |
368 | #ifndef TENSORFLOW_LITE_KERNELS_ACCELERATION_TEST_UTIL_INTERNAL_H_
#define TENSORFLOW_LITE_KERNELS_ACCELERATION_TEST_UTIL_INTERNAL_H_
#include <algorithm>
#include <atomic>
#include <functional>
#include <iterator>
#include <optional>
#include <string>
#include <vector>
#include "absl/types/optional.h"
#include "re2/re2.h"
namespace tflite {
void ReadAccelerationConfig(
const char* config,
const std::function<void(std::string, std::string, bool)>& consumer);
template <typename T>
class ConfigurationEntry {
public:
ConfigurationEntry(const std::string& test_id_rex, T test_config,
bool is_denylist)
: test_id_rex_(test_id_rex),
test_config_(test_config),
is_denylist_(is_denylist) {}
bool Matches(const std::string& test_id) {
return RE2::FullMatch(test_id, test_id_rex_);
}
bool IsDenylistEntry() const { return is_denylist_; }
const T& TestConfig() const { return test_config_; }
const std::string& TestIdRex() const { return test_id_rex_; }
private:
std::string test_id_rex_;
T test_config_;
bool is_denylist_;
};
template <typename T>
std::optional<T> GetAccelerationTestParam(std::string test_id) {
static std::atomic<std::vector<ConfigurationEntry<T>>*> test_config_ptr;
if (test_config_ptr.load() == nullptr) {
auto config = new std::vector<ConfigurationEntry<T>>();
auto consumer = [&config](std::string key, std::string value_str,
bool is_denylist) mutable {
T value = T::ParseConfigurationLine(value_str);
config->push_back(ConfigurationEntry<T>(key, value, is_denylist));
};
ReadAccelerationConfig(T::AccelerationTestConfig(), consumer);
auto* prev_val = test_config_ptr.exchange(config);
delete prev_val;
}
const std::vector<ConfigurationEntry<T>>* test_config =
test_config_ptr.load();
const auto test_config_iter = std::find_if(
test_config->begin(), test_config->end(),
[&test_id](ConfigurationEntry<T> elem) { return elem.Matches(test_id); });
if (test_config_iter != test_config->end() &&
!test_config_iter->IsDenylistEntry()) {
return std::optional<T>(test_config_iter->TestConfig());
} else {
return std::optional<T>();
}
}
}
#endif
#include "tensorflow/lite/kernels/acceleration_test_util_internal.h"
#include <ctype.h>
#include <algorithm>
#include <functional>
#include <iterator>
#include <sstream>
#include <string>
namespace tflite {
void ReadAccelerationConfig(
const char* config,
const std::function<void(std::string, std::string, bool)>& consumer) {
if (config) {
std::istringstream istream{config};
std::string curr_config_line;
while (std::getline(istream, curr_config_line)) {
curr_config_line.erase(
curr_config_line.begin(),
std::find_if_not(curr_config_line.begin(), curr_config_line.end(),
[](int ch) { return std::isspace(ch); }));
if (curr_config_line.empty() || curr_config_line.at(0) == '#') {
continue;
}
auto first_sep_pos =
std::find(curr_config_line.begin(), curr_config_line.end(), ',');
bool is_denylist = false;
std::string key = curr_config_line;
std::string value{};
if (first_sep_pos != curr_config_line.end()) {
key = std::string(curr_config_line.begin(), first_sep_pos);
value = std::string(first_sep_pos + 1, curr_config_line.end());
}
if (key[0] == '-') {
key = key.substr(1);
is_denylist = true;
}
consumer(key, value, is_denylist);
}
}
}
} | #include "tensorflow/lite/kernels/acceleration_test_util_internal.h"
#include <functional>
#include <optional>
#include <string>
#include <unordered_map>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
namespace tflite {
using ::testing::Eq;
using ::testing::Not;
using ::testing::Test;
struct SimpleConfig {
public:
static constexpr char kAccelerationTestConfig[] =
R"(
#test-id,some-other-data
test-1,data-1
test-2,
test-3,data-3
test-4.*,data-4
-test-5
test-6
test-7,data-7
)";
static const char* AccelerationTestConfig() {
return kAccelerationTestConfig;
}
static SimpleConfig ParseConfigurationLine(const std::string& conf_line) {
return {conf_line};
}
std::string value;
};
class ReadAccelerationConfigTest : public ::testing::Test {
public:
std::unordered_map<std::string, SimpleConfig> allowlist_;
std::unordered_map<std::string, SimpleConfig> denylist_;
std::function<void(std::string, std::string, bool)> consumer_ =
[this](std::string key, std::string value, bool is_denylist) {
if (is_denylist) {
denylist_[key] = {value};
} else {
allowlist_[key] = {value};
}
};
};
TEST_F(ReadAccelerationConfigTest, ReadsAKeyOnlyLine) {
ReadAccelerationConfig("key", consumer_);
EXPECT_THAT(allowlist_.find("key"), Not(Eq(allowlist_.end())));
EXPECT_TRUE(denylist_.empty());
}
TEST_F(ReadAccelerationConfigTest, ReadsADenylistKeyOnlyLine) {
ReadAccelerationConfig("-key", consumer_);
EXPECT_THAT(denylist_.find("key"), Not(Eq(allowlist_.end())));
EXPECT_TRUE(allowlist_.empty());
}
TEST_F(ReadAccelerationConfigTest, ReadsAKeyValueLine) {
ReadAccelerationConfig("key,value", consumer_);
EXPECT_THAT(allowlist_["key"].value, Eq("value"));
EXPECT_TRUE(denylist_.empty());
}
TEST_F(ReadAccelerationConfigTest, ReadsADenyListKeyValueLine) {
ReadAccelerationConfig("-key,value", consumer_);
EXPECT_THAT(denylist_["key"].value, Eq("value"));
EXPECT_TRUE(allowlist_.empty());
}
TEST_F(ReadAccelerationConfigTest, KeysAreLeftTrimmed) {
ReadAccelerationConfig(" key,value", consumer_);
EXPECT_THAT(allowlist_["key"].value, Eq("value"));
EXPECT_TRUE(denylist_.empty());
}
TEST_F(ReadAccelerationConfigTest, BlKeysAreLeftTrimmed) {
ReadAccelerationConfig(" -key,value", consumer_);
EXPECT_THAT(denylist_["key"].value, Eq("value"));
EXPECT_TRUE(allowlist_.empty());
}
TEST_F(ReadAccelerationConfigTest, IgnoresCommentedLines) {
ReadAccelerationConfig("#key,value", consumer_);
EXPECT_TRUE(allowlist_.empty());
EXPECT_TRUE(denylist_.empty());
}
TEST_F(ReadAccelerationConfigTest, CommentCanHaveTrailingBlanks) {
ReadAccelerationConfig(" #key,value", consumer_);
EXPECT_TRUE(allowlist_.empty());
EXPECT_TRUE(denylist_.empty());
}
TEST_F(ReadAccelerationConfigTest, CommentsAreOnlyForTheFullLine) {
ReadAccelerationConfig("key,value #comment", consumer_);
EXPECT_THAT(allowlist_["key"].value, Eq("value #comment"));
}
TEST_F(ReadAccelerationConfigTest, IgnoresEmptyLines) {
ReadAccelerationConfig("", consumer_);
EXPECT_TRUE(allowlist_.empty());
EXPECT_TRUE(denylist_.empty());
}
TEST_F(ReadAccelerationConfigTest, ParsesMultipleLines) {
ReadAccelerationConfig("key1,value1\nkey2,value2\n-key3,value3", consumer_);
EXPECT_THAT(allowlist_["key1"].value, Eq("value1"));
EXPECT_THAT(allowlist_["key2"].value, Eq("value2"));
EXPECT_THAT(denylist_["key3"].value, Eq("value3"));
}
TEST_F(ReadAccelerationConfigTest, ParsesMultipleLinesWithCommentsAndSpaces) {
ReadAccelerationConfig("key1,value1\n#comment\n\nkey2,value2", consumer_);
EXPECT_THAT(allowlist_["key1"].value, Eq("value1"));
EXPECT_THAT(allowlist_["key2"].value, Eq("value2"));
}
TEST_F(ReadAccelerationConfigTest, ParsesMultipleLinesWithMissingConfigValues) {
ReadAccelerationConfig("key1\nkey2,value2\nkey3\nkey4,value4", consumer_);
EXPECT_THAT(allowlist_["key1"].value, Eq(""));
EXPECT_THAT(allowlist_["key2"].value, Eq("value2"));
EXPECT_THAT(allowlist_["key3"].value, Eq(""));
EXPECT_THAT(allowlist_["key4"].value, Eq("value4"));
}
TEST(GetAccelerationTestParam, LoadsTestConfig) {
const auto config_value_maybe =
GetAccelerationTestParam<SimpleConfig>("test-3");
ASSERT_TRUE(config_value_maybe.has_value());
ASSERT_THAT(config_value_maybe.value().value, Eq("data-3"));
}
TEST(GetAccelerationTestParam, LoadsTestConfigWithEmptyValue) {
const auto config_value_maybe =
GetAccelerationTestParam<SimpleConfig>("test-2");
ASSERT_TRUE(config_value_maybe.has_value());
ASSERT_THAT(config_value_maybe.value().value, Eq(""));
}
TEST(GetAccelerationTestParam, SupportsWildcards) {
const auto config_value_maybe =
GetAccelerationTestParam<SimpleConfig>("test-41");
ASSERT_TRUE(config_value_maybe.has_value());
ASSERT_THAT(config_value_maybe.value().value, Eq("data-4"));
}
TEST(GetAccelerationTestParam, SupportDenylist) {
const auto config_value_maybe =
GetAccelerationTestParam<SimpleConfig>("test-5");
ASSERT_FALSE(config_value_maybe.has_value());
}
struct UnmatchedSimpleConfig {
public:
static constexpr const char* kAccelerationTestConfig = nullptr;
static const char* AccelerationTestConfig() {
return kAccelerationTestConfig;
}
static UnmatchedSimpleConfig ParseConfigurationLine(
const std::string& conf_line) {
return {conf_line};
}
std::string value;
};
TEST(GetAccelerationTestParam, ReturnEmptyOptionalForNullConfig) {
ASSERT_FALSE(
GetAccelerationTestParam<UnmatchedSimpleConfig>("test-3").has_value());
}
} |
369 | #ifndef ABSL_CONTAINER_INTERNAL_TEST_INSTANCE_TRACKER_H_
#define ABSL_CONTAINER_INTERNAL_TEST_INSTANCE_TRACKER_H_
#include <cstdlib>
#include <ostream>
#include "absl/types/compare.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace test_internal {
class BaseCountedInstance {
public:
explicit BaseCountedInstance(int x) : value_(x) {
++num_instances_;
++num_live_instances_;
}
BaseCountedInstance(const BaseCountedInstance& x)
: value_(x.value_), is_live_(x.is_live_) {
++num_instances_;
if (is_live_) ++num_live_instances_;
++num_copies_;
}
BaseCountedInstance(BaseCountedInstance&& x)
: value_(x.value_), is_live_(x.is_live_) {
x.is_live_ = false;
++num_instances_;
++num_moves_;
}
~BaseCountedInstance() {
--num_instances_;
if (is_live_) --num_live_instances_;
}
BaseCountedInstance& operator=(const BaseCountedInstance& x) {
value_ = x.value_;
if (is_live_) --num_live_instances_;
is_live_ = x.is_live_;
if (is_live_) ++num_live_instances_;
++num_copies_;
return *this;
}
BaseCountedInstance& operator=(BaseCountedInstance&& x) {
value_ = x.value_;
if (is_live_) --num_live_instances_;
is_live_ = x.is_live_;
x.is_live_ = false;
++num_moves_;
return *this;
}
bool operator==(const BaseCountedInstance& x) const {
++num_comparisons_;
return value_ == x.value_;
}
bool operator!=(const BaseCountedInstance& x) const {
++num_comparisons_;
return value_ != x.value_;
}
bool operator<(const BaseCountedInstance& x) const {
++num_comparisons_;
return value_ < x.value_;
}
bool operator>(const BaseCountedInstance& x) const {
++num_comparisons_;
return value_ > x.value_;
}
bool operator<=(const BaseCountedInstance& x) const {
++num_comparisons_;
return value_ <= x.value_;
}
bool operator>=(const BaseCountedInstance& x) const {
++num_comparisons_;
return value_ >= x.value_;
}
absl::weak_ordering compare(const BaseCountedInstance& x) const {
++num_comparisons_;
return value_ < x.value_
? absl::weak_ordering::less
: value_ == x.value_ ? absl::weak_ordering::equivalent
: absl::weak_ordering::greater;
}
int value() const {
if (!is_live_) std::abort();
return value_;
}
friend std::ostream& operator<<(std::ostream& o,
const BaseCountedInstance& v) {
return o << "[value:" << v.value() << "]";
}
static void SwapImpl(
BaseCountedInstance& lhs,
BaseCountedInstance& rhs) {
using std::swap;
swap(lhs.value_, rhs.value_);
swap(lhs.is_live_, rhs.is_live_);
++BaseCountedInstance::num_swaps_;
}
private:
friend class InstanceTracker;
int value_;
bool is_live_ = true;
static int num_instances_;
static int num_live_instances_;
static int num_moves_;
static int num_copies_;
static int num_swaps_;
static int num_comparisons_;
};
class InstanceTracker {
public:
InstanceTracker()
: start_instances_(BaseCountedInstance::num_instances_),
start_live_instances_(BaseCountedInstance::num_live_instances_) {
ResetCopiesMovesSwaps();
}
~InstanceTracker() {
if (instances() != 0) std::abort();
if (live_instances() != 0) std::abort();
}
int instances() const {
return BaseCountedInstance::num_instances_ - start_instances_;
}
int live_instances() const {
return BaseCountedInstance::num_live_instances_ - start_live_instances_;
}
int moves() const { return BaseCountedInstance::num_moves_ - start_moves_; }
int copies() const {
return BaseCountedInstance::num_copies_ - start_copies_;
}
int swaps() const { return BaseCountedInstance::num_swaps_ - start_swaps_; }
int comparisons() const {
return BaseCountedInstance::num_comparisons_ - start_comparisons_;
}
void ResetCopiesMovesSwaps() {
start_moves_ = BaseCountedInstance::num_moves_;
start_copies_ = BaseCountedInstance::num_copies_;
start_swaps_ = BaseCountedInstance::num_swaps_;
start_comparisons_ = BaseCountedInstance::num_comparisons_;
}
private:
int start_instances_;
int start_live_instances_;
int start_moves_;
int start_copies_;
int start_swaps_;
int start_comparisons_;
};
class CopyableOnlyInstance : public BaseCountedInstance {
public:
explicit CopyableOnlyInstance(int x) : BaseCountedInstance(x) {}
CopyableOnlyInstance(const CopyableOnlyInstance& rhs) = default;
CopyableOnlyInstance& operator=(const CopyableOnlyInstance& rhs) = default;
friend void swap(CopyableOnlyInstance& lhs, CopyableOnlyInstance& rhs) {
BaseCountedInstance::SwapImpl(lhs, rhs);
}
static bool supports_move() { return false; }
};
class CopyableMovableInstance : public BaseCountedInstance {
public:
explicit CopyableMovableInstance(int x) : BaseCountedInstance(x) {}
CopyableMovableInstance(const CopyableMovableInstance& rhs) = default;
CopyableMovableInstance(CopyableMovableInstance&& rhs) = default;
CopyableMovableInstance& operator=(const CopyableMovableInstance& rhs) =
default;
CopyableMovableInstance& operator=(CopyableMovableInstance&& rhs) = default;
friend void swap(CopyableMovableInstance& lhs, CopyableMovableInstance& rhs) {
BaseCountedInstance::SwapImpl(lhs, rhs);
}
static bool supports_move() { return true; }
};
class MovableOnlyInstance : public BaseCountedInstance {
public:
explicit MovableOnlyInstance(int x) : BaseCountedInstance(x) {}
MovableOnlyInstance(MovableOnlyInstance&& other) = default;
MovableOnlyInstance& operator=(MovableOnlyInstance&& other) = default;
friend void swap(MovableOnlyInstance& lhs, MovableOnlyInstance& rhs) {
BaseCountedInstance::SwapImpl(lhs, rhs);
}
static bool supports_move() { return true; }
};
}
ABSL_NAMESPACE_END
}
#endif
#include "absl/container/internal/test_instance_tracker.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace test_internal {
int BaseCountedInstance::num_instances_ = 0;
int BaseCountedInstance::num_live_instances_ = 0;
int BaseCountedInstance::num_moves_ = 0;
int BaseCountedInstance::num_copies_ = 0;
int BaseCountedInstance::num_swaps_ = 0;
int BaseCountedInstance::num_comparisons_ = 0;
}
ABSL_NAMESPACE_END
} | #include "absl/container/internal/test_instance_tracker.h"
#include "gtest/gtest.h"
namespace {
using absl::test_internal::CopyableMovableInstance;
using absl::test_internal::CopyableOnlyInstance;
using absl::test_internal::InstanceTracker;
using absl::test_internal::MovableOnlyInstance;
TEST(TestInstanceTracker, CopyableMovable) {
InstanceTracker tracker;
CopyableMovableInstance src(1);
EXPECT_EQ(1, src.value()) << src;
CopyableMovableInstance copy(src);
CopyableMovableInstance move(std::move(src));
EXPECT_EQ(1, tracker.copies());
EXPECT_EQ(1, tracker.moves());
EXPECT_EQ(0, tracker.swaps());
EXPECT_EQ(3, tracker.instances());
EXPECT_EQ(2, tracker.live_instances());
tracker.ResetCopiesMovesSwaps();
CopyableMovableInstance copy_assign(1);
copy_assign = copy;
CopyableMovableInstance move_assign(1);
move_assign = std::move(move);
EXPECT_EQ(1, tracker.copies());
EXPECT_EQ(1, tracker.moves());
EXPECT_EQ(0, tracker.swaps());
EXPECT_EQ(5, tracker.instances());
EXPECT_EQ(3, tracker.live_instances());
tracker.ResetCopiesMovesSwaps();
{
using std::swap;
swap(move_assign, copy);
swap(copy, move_assign);
EXPECT_EQ(2, tracker.swaps());
EXPECT_EQ(0, tracker.copies());
EXPECT_EQ(0, tracker.moves());
EXPECT_EQ(5, tracker.instances());
EXPECT_EQ(3, tracker.live_instances());
}
}
TEST(TestInstanceTracker, CopyableOnly) {
InstanceTracker tracker;
CopyableOnlyInstance src(1);
EXPECT_EQ(1, src.value()) << src;
CopyableOnlyInstance copy(src);
CopyableOnlyInstance copy2(std::move(src));
EXPECT_EQ(2, tracker.copies());
EXPECT_EQ(0, tracker.moves());
EXPECT_EQ(3, tracker.instances());
EXPECT_EQ(3, tracker.live_instances());
tracker.ResetCopiesMovesSwaps();
CopyableOnlyInstance copy_assign(1);
copy_assign = copy;
CopyableOnlyInstance copy_assign2(1);
copy_assign2 = std::move(copy2);
EXPECT_EQ(2, tracker.copies());
EXPECT_EQ(0, tracker.moves());
EXPECT_EQ(5, tracker.instances());
EXPECT_EQ(5, tracker.live_instances());
tracker.ResetCopiesMovesSwaps();
{
using std::swap;
swap(src, copy);
swap(copy, src);
EXPECT_EQ(2, tracker.swaps());
EXPECT_EQ(0, tracker.copies());
EXPECT_EQ(0, tracker.moves());
EXPECT_EQ(5, tracker.instances());
EXPECT_EQ(5, tracker.live_instances());
}
}
TEST(TestInstanceTracker, MovableOnly) {
InstanceTracker tracker;
MovableOnlyInstance src(1);
EXPECT_EQ(1, src.value()) << src;
MovableOnlyInstance move(std::move(src));
MovableOnlyInstance move_assign(2);
move_assign = std::move(move);
EXPECT_EQ(3, tracker.instances());
EXPECT_EQ(1, tracker.live_instances());
EXPECT_EQ(2, tracker.moves());
EXPECT_EQ(0, tracker.copies());
tracker.ResetCopiesMovesSwaps();
{
using std::swap;
MovableOnlyInstance other(2);
swap(move_assign, other);
swap(other, move_assign);
EXPECT_EQ(2, tracker.swaps());
EXPECT_EQ(0, tracker.copies());
EXPECT_EQ(0, tracker.moves());
EXPECT_EQ(4, tracker.instances());
EXPECT_EQ(2, tracker.live_instances());
}
}
TEST(TestInstanceTracker, ExistingInstances) {
CopyableMovableInstance uncounted_instance(1);
CopyableMovableInstance uncounted_live_instance(
std::move(uncounted_instance));
InstanceTracker tracker;
EXPECT_EQ(0, tracker.instances());
EXPECT_EQ(0, tracker.live_instances());
EXPECT_EQ(0, tracker.copies());
{
CopyableMovableInstance instance1(1);
EXPECT_EQ(1, tracker.instances());
EXPECT_EQ(1, tracker.live_instances());
EXPECT_EQ(0, tracker.copies());
EXPECT_EQ(0, tracker.moves());
{
InstanceTracker tracker2;
CopyableMovableInstance instance2(instance1);
CopyableMovableInstance instance3(std::move(instance2));
EXPECT_EQ(3, tracker.instances());
EXPECT_EQ(2, tracker.live_instances());
EXPECT_EQ(1, tracker.copies());
EXPECT_EQ(1, tracker.moves());
EXPECT_EQ(2, tracker2.instances());
EXPECT_EQ(1, tracker2.live_instances());
EXPECT_EQ(1, tracker2.copies());
EXPECT_EQ(1, tracker2.moves());
}
EXPECT_EQ(1, tracker.instances());
EXPECT_EQ(1, tracker.live_instances());
EXPECT_EQ(1, tracker.copies());
EXPECT_EQ(1, tracker.moves());
}
EXPECT_EQ(0, tracker.instances());
EXPECT_EQ(0, tracker.live_instances());
EXPECT_EQ(1, tracker.copies());
EXPECT_EQ(1, tracker.moves());
}
TEST(TestInstanceTracker, Comparisons) {
InstanceTracker tracker;
MovableOnlyInstance one(1), two(2);
EXPECT_EQ(0, tracker.comparisons());
EXPECT_FALSE(one == two);
EXPECT_EQ(1, tracker.comparisons());
EXPECT_TRUE(one != two);
EXPECT_EQ(2, tracker.comparisons());
EXPECT_TRUE(one < two);
EXPECT_EQ(3, tracker.comparisons());
EXPECT_FALSE(one > two);
EXPECT_EQ(4, tracker.comparisons());
EXPECT_TRUE(one <= two);
EXPECT_EQ(5, tracker.comparisons());
EXPECT_FALSE(one >= two);
EXPECT_EQ(6, tracker.comparisons());
EXPECT_TRUE(one.compare(two) < 0);
EXPECT_EQ(7, tracker.comparisons());
tracker.ResetCopiesMovesSwaps();
EXPECT_EQ(0, tracker.comparisons());
}
} |
370 | #ifndef XLA_SERVICE_CPU_CONV_CANONICALIZATION_H_
#define XLA_SERVICE_CPU_CONV_CANONICALIZATION_H_
#include "xla/hlo/ir/hlo_module.h"
#include "xla/service/cpu/target_machine_features.h"
#include "xla/service/hlo_pass_interface.h"
namespace xla {
namespace cpu {
class ConvCanonicalization : public HloModulePass {
public:
explicit ConvCanonicalization(
const TargetMachineFeatures* target_machine_features)
: target_machine_features_(*target_machine_features) {}
~ConvCanonicalization() override {}
absl::string_view name() const override {
return "convolution-canonicalization";
}
using HloPassInterface::Run;
absl::StatusOr<bool> Run(
HloModule* module,
const absl::flat_hash_set<absl::string_view>& execution_threads) override;
private:
const TargetMachineFeatures& target_machine_features_;
};
}
}
#endif
#include "xla/service/cpu/conv_canonicalization.h"
#include "xla/hlo/ir/hlo_computation.h"
#include "xla/hlo/ir/hlo_instruction.h"
#include "xla/hlo/ir/hlo_opcode.h"
#include "xla/permutation_util.h"
#include "xla/service/cpu/cpu_runtime.h"
#include "xla/service/cpu/ir_emission_utils.h"
#include "xla/shape_util.h"
#include "xla/util.h"
#include "xla/xla_data.pb.h"
#include "tsl/platform/errors.h"
namespace xla {
namespace cpu {
absl::StatusOr<bool> ConvCanonicalization::Run(
HloModule* module,
const absl::flat_hash_set<absl::string_view>& execution_threads) {
bool changed = false;
for (HloInstruction* hlo :
module->entry_computation()->MakeInstructionPostOrder()) {
if (hlo->opcode() == HloOpcode::kConvolution &&
!PotentiallyImplementedAsEigenConvolution(*hlo,
target_machine_features_)) {
const ConvolutionDimensionNumbers& dnums =
hlo->convolution_dimension_numbers();
auto input_batch_dim = dnums.input_batch_dimension();
auto input_feature_dim = dnums.input_feature_dimension();
auto kernel_input_feature_dim = dnums.kernel_input_feature_dimension();
auto kernel_output_feature_dim = dnums.kernel_output_feature_dimension();
const int64_t num_spatial_dims = dnums.output_spatial_dimensions_size();
const int64_t num_dims = num_spatial_dims + 2;
HloInstruction* input = hlo->mutable_operand(0);
std::vector<int64_t> new_input_dim_order(num_dims);
std::vector<int64_t> new_input_dims(num_dims);
new_input_dim_order[0] = input_batch_dim;
new_input_dims[0] = input->shape().dimensions(input_batch_dim);
for (int64_t i = 0; i < num_spatial_dims; ++i) {
new_input_dim_order[i + 1] = dnums.input_spatial_dimensions(i);
new_input_dims[i + 1] =
input->shape().dimensions(dnums.input_spatial_dimensions(i));
}
new_input_dim_order[num_dims - 1] = input_feature_dim;
new_input_dims[num_dims - 1] =
input->shape().dimensions(input_feature_dim);
Shape new_input_shape =
ShapeUtil::MakeShape(input->shape().element_type(), new_input_dims);
HloInstruction* new_input = module->entry_computation()->AddInstruction(
HloInstruction::CreateTranspose(new_input_shape, input,
new_input_dim_order));
HloInstruction* kernel = hlo->mutable_operand(1);
std::vector<int64_t> new_kernel_dim_order(num_dims);
std::vector<int64_t> new_kernel_dims(num_dims);
for (int64_t i = 0; i < num_spatial_dims; ++i) {
new_kernel_dim_order[i] = dnums.kernel_spatial_dimensions(i);
new_kernel_dims[i] =
kernel->shape().dimensions(dnums.kernel_spatial_dimensions(i));
}
new_kernel_dim_order[num_dims - 2] = kernel_input_feature_dim;
new_kernel_dims[num_dims - 2] =
kernel->shape().dimensions(kernel_input_feature_dim);
new_kernel_dim_order[num_dims - 1] = kernel_output_feature_dim;
new_kernel_dims[num_dims - 1] =
kernel->shape().dimensions(kernel_output_feature_dim);
Shape new_kernel_shape =
ShapeUtil::MakeShape(kernel->shape().element_type(), new_kernel_dims);
HloInstruction* new_kernel = module->entry_computation()->AddInstruction(
HloInstruction::CreateTranspose(new_kernel_shape, kernel,
new_kernel_dim_order));
std::vector<int64_t> new_output_dim_order(num_dims);
std::vector<int64_t> new_conv_dims(num_dims);
auto output_batch_dim = dnums.output_batch_dimension();
auto output_feature_dim = dnums.output_feature_dimension();
new_output_dim_order[0] = output_batch_dim;
new_conv_dims[0] = hlo->shape().dimensions(output_batch_dim);
for (int64_t i = 0; i < num_spatial_dims; ++i) {
new_output_dim_order[i + 1] = dnums.output_spatial_dimensions(i);
new_conv_dims[i + 1] =
hlo->shape().dimensions(dnums.output_spatial_dimensions(i));
}
new_output_dim_order[num_dims - 1] = output_feature_dim;
new_conv_dims[num_dims - 1] = hlo->shape().dimensions(output_feature_dim);
Shape new_conv_shape =
ShapeUtil::MakeShape(hlo->shape().element_type(), new_conv_dims);
ConvolutionDimensionNumbers new_dnums;
new_dnums.set_input_batch_dimension(0);
new_dnums.set_output_batch_dimension(0);
for (int64_t i = 0; i < num_spatial_dims; ++i) {
new_dnums.add_input_spatial_dimensions(i + 1);
new_dnums.add_kernel_spatial_dimensions(i);
new_dnums.add_output_spatial_dimensions(i + 1);
}
new_dnums.set_input_feature_dimension(num_dims - 1);
new_dnums.set_output_feature_dimension(num_dims - 1);
new_dnums.set_kernel_input_feature_dimension(num_dims - 2);
new_dnums.set_kernel_output_feature_dimension(num_dims - 1);
HloInstruction* new_conv = module->entry_computation()->AddInstruction(
HloInstruction::CreateConvolve(
new_conv_shape, new_input, new_kernel, hlo->feature_group_count(),
hlo->batch_group_count(), hlo->window(), new_dnums,
hlo->precision_config()));
TF_RETURN_IF_ERROR(module->entry_computation()->ReplaceWithNewInstruction(
hlo, HloInstruction::CreateTranspose(
hlo->shape(), new_conv,
InversePermutation(new_output_dim_order))));
changed = true;
}
}
return changed;
}
}
} | #include "xla/service/cpu/conv_canonicalization.h"
#include <vector>
#include "xla/hlo/ir/hlo_computation.h"
#include "xla/hlo/ir/hlo_instruction.h"
#include "xla/hlo/ir/hlo_module.h"
#include "xla/service/cpu/target_machine_features_fake.h"
#include "xla/test.h"
#include "xla/test_helpers.h"
#include "xla/tests/hlo_test_base.h"
#include "xla/util.h"
namespace xla {
namespace cpu {
using ::testing::ElementsAre;
class ConvCanonicalizationTest : public HloTestBase {
public:
ConvCanonicalizationTest() {
for (int i = 0; i < 2; ++i) {
auto dim = conv_window_.add_dimensions();
dim->set_size(kWindowSize);
dim->set_stride(1);
dim->set_padding_low(0);
dim->set_padding_high(0);
dim->set_window_dilation(1);
dim->set_base_dilation(1);
}
}
protected:
Window conv_window_;
static constexpr int kBatchSize = 50;
static constexpr int kInputSize = 28;
static constexpr int kWindowSize = 5;
static constexpr int kInputFeatureCount = 32;
static constexpr int kOutputFeatureCount = 64;
};
TEST_F(ConvCanonicalizationTest, NonCanonicalToCanonical) {
auto builder = HloComputation::Builder(TestName());
auto input = builder.AddInstruction(HloInstruction::CreateConstant(
LiteralUtil::CreateR4FromArray4D(Array4D<float>(
kInputFeatureCount, kBatchSize, kInputSize, kInputSize))));
auto kernel = builder.AddInstruction(HloInstruction::CreateConstant(
LiteralUtil::CreateR4FromArray4D(Array4D<float>(
kOutputFeatureCount, kInputFeatureCount, kWindowSize, kWindowSize))));
ConvolutionDimensionNumbers dnums;
dnums.set_input_batch_dimension(1);
dnums.set_output_batch_dimension(1);
dnums.add_input_spatial_dimensions(2);
dnums.add_output_spatial_dimensions(2);
dnums.add_input_spatial_dimensions(3);
dnums.add_output_spatial_dimensions(3);
dnums.set_input_feature_dimension(0);
dnums.set_output_feature_dimension(0);
dnums.add_kernel_spatial_dimensions(2);
dnums.add_kernel_spatial_dimensions(3);
dnums.set_kernel_input_feature_dimension(1);
dnums.set_kernel_output_feature_dimension(0);
auto output_size = kInputSize - kWindowSize + 1;
builder.AddInstruction(HloInstruction::CreateConvolve(
ShapeUtil::MakeShape(
F32, {kOutputFeatureCount, kBatchSize, output_size, output_size}),
input, kernel, 1, 1,
conv_window_, dnums, DefaultPrecisionConfig(2)));
auto module = CreateNewVerifiedModule();
HloComputation* entry_computation =
module->AddEntryComputation(builder.Build());
cpu::TargetMachineFeaturesWithFakeAlignmentLogic target_machine_features(
[](int64_t shape_size) {
return cpu::TargetMachineFeatures::kEigenExpectedTensorAlignment;
});
ConvCanonicalization conv_canonicalization(&target_machine_features);
EXPECT_TRUE(conv_canonicalization.Run(module.get()).value());
const HloInstruction* output_reshape = entry_computation->root_instruction();
EXPECT_EQ(HloOpcode::kTranspose, output_reshape->opcode());
const HloInstruction* canonical_conv = output_reshape->operand(0);
EXPECT_EQ(HloOpcode::kConvolution, canonical_conv->opcode());
const HloInstruction* input_reshape = canonical_conv->operand(0);
EXPECT_EQ(HloOpcode::kTranspose, input_reshape->opcode());
const HloInstruction* kernel_reshape = canonical_conv->operand(1);
EXPECT_EQ(HloOpcode::kTranspose, kernel_reshape->opcode());
EXPECT_THAT(input_reshape->dimensions(), ElementsAre(1, 2, 3, 0));
EXPECT_THAT(kernel_reshape->dimensions(), ElementsAre(2, 3, 1, 0));
EXPECT_THAT(output_reshape->dimensions(), ElementsAre(3, 0, 1, 2));
}
TEST_F(ConvCanonicalizationTest, CanonicalStaysTheSame) {
auto builder = HloComputation::Builder(TestName());
auto input = builder.AddInstruction(HloInstruction::CreateConstant(
LiteralUtil::CreateR4FromArray4D(Array4D<float>(
kBatchSize, kInputSize, kInputSize, kInputFeatureCount))));
auto kernel = builder.AddInstruction(HloInstruction::CreateConstant(
LiteralUtil::CreateR4FromArray4D(Array4D<float>(
kWindowSize, kWindowSize, kInputFeatureCount, kOutputFeatureCount))));
ConvolutionDimensionNumbers dnums;
dnums.set_input_batch_dimension(0);
dnums.set_output_batch_dimension(0);
dnums.add_input_spatial_dimensions(1);
dnums.add_output_spatial_dimensions(1);
dnums.add_input_spatial_dimensions(2);
dnums.add_output_spatial_dimensions(2);
dnums.set_input_feature_dimension(3);
dnums.set_output_feature_dimension(3);
dnums.add_kernel_spatial_dimensions(0);
dnums.add_kernel_spatial_dimensions(1);
dnums.set_kernel_input_feature_dimension(2);
dnums.set_kernel_output_feature_dimension(3);
auto output_size = kInputSize - kWindowSize + 1;
builder.AddInstruction(HloInstruction::CreateConvolve(
ShapeUtil::MakeShape(
F32, {kBatchSize, output_size, output_size, kOutputFeatureCount}),
input, kernel, 1, 1,
conv_window_, dnums, DefaultPrecisionConfig(2)));
auto module = CreateNewVerifiedModule();
module->AddEntryComputation(builder.Build());
cpu::TargetMachineFeaturesWithFakeAlignmentLogic target_machine_features(
[](int64_t shape_size) {
return cpu::TargetMachineFeatures::kEigenExpectedTensorAlignment;
});
ConvCanonicalization conv_canonicalization(&target_machine_features);
EXPECT_FALSE(conv_canonicalization.Run(module.get()).value());
}
}
} |
371 | #ifndef XLA_PYTHON_IFRT_PROXY_CLIENT_GRPC_CLIENT_SESSION_H_
#define XLA_PYTHON_IFRT_PROXY_CLIENT_GRPC_CLIENT_SESSION_H_
#include <functional>
#include <memory>
#include "absl/base/call_once.h"
#include "absl/base/thread_annotations.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/string_view.h"
#include "absl/synchronization/mutex.h"
#include "absl/synchronization/notification.h"
#include "grpcpp/client_context.h"
#include "grpcpp/support/client_callback.h"
#include "grpcpp/support/sync_stream.h"
#include "xla/python/ifrt/future.h"
#include "xla/python/ifrt_proxy/client/client_session.h"
#include "xla/python/ifrt_proxy/common/grpc_ifrt_service.grpc.pb.h"
#include "xla/python/ifrt_proxy/common/ifrt_service.pb.h"
#include "tsl/platform/threadpool.h"
#include "tsl/platform/unbounded_work_queue.h"
namespace xla {
namespace ifrt {
namespace proxy {
class GrpcClientSession : public ClientSession {
public:
using StreamTerminatedCallback = std::function<void(absl::Status)>;
static std::shared_ptr<GrpcClientSession> Create(
std::shared_ptr<grpc::GrpcIfrtService::StubInterface> stub,
GrpcIfrtSessionMetadata metadata,
StreamTerminatedCallback stream_terminated_cb);
Future<std::shared_ptr<IfrtResponse>> Enqueue(
std::unique_ptr<IfrtRequest> request) override;
using ResponseCallback =
std::function<void(absl::StatusOr<std::shared_ptr<IfrtResponse>>)>;
absl::Status Enqueue(std::unique_ptr<IfrtRequest> req,
ResponseCallback callback);
void Finish(const absl::Status& client_status) override;
GrpcClientSession(const GrpcClientSession&) = delete;
GrpcClientSession& operator=(const GrpcClientSession&) = delete;
~GrpcClientSession() override;
private:
class ResponseCallbackTable;
GrpcClientSession(std::shared_ptr<grpc::GrpcIfrtService::StubInterface> stub,
std::unique_ptr<::grpc::ClientContext> context,
StreamTerminatedCallback stream_terminated_cb);
void ReadLoop();
const std::unique_ptr<ResponseCallbackTable> response_callbacks_;
std::unique_ptr<tsl::thread::ThreadPool> reader_thread_;
absl::Notification reader_thread_stopped_;
bool writes_stopped_ ABSL_GUARDED_BY(writer_mu_) = false;
absl::Mutex writer_mu_;
absl::once_flag finish_once_;
const std::shared_ptr<grpc::GrpcIfrtService::StubInterface> stub_;
const std::unique_ptr<::grpc::ClientContext> context_;
const std::unique_ptr<
::grpc::ClientReaderWriterInterface<IfrtRequest, IfrtResponse>>
stream_;
const StreamTerminatedCallback stream_terminated_cb_;
std::unique_ptr<tsl::UnboundedWorkQueue> user_futures_work_queue_;
};
std::shared_ptr<grpc::GrpcIfrtService::StubInterface> CreateGrpcStub(
absl::string_view server_address);
}
}
}
#endif
#include "xla/python/ifrt_proxy/client/grpc_client_session.h"
#include <cstdint>
#include <functional>
#include <memory>
#include <optional>
#include <string>
#include <utility>
#include "absl/base/call_once.h"
#include "absl/base/thread_annotations.h"
#include "absl/container/flat_hash_map.h"
#include "absl/functional/bind_front.h"
#include "absl/log/check.h"
#include "absl/log/log.h"
#include "absl/status/status.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/string_view.h"
#include "absl/synchronization/mutex.h"
#include "absl/synchronization/notification.h"
#include "grpc/grpc.h"
#include "grpcpp/channel.h"
#include "grpcpp/client_context.h"
#include "grpcpp/create_channel.h"
#include "grpcpp/security/credentials.h"
#include "grpcpp/support/channel_arguments.h"
#include "xla/pjrt/distributed/util.h"
#include "xla/python/ifrt/future.h"
#include "xla/python/ifrt_proxy/client/client_session.h"
#include "xla/python/ifrt_proxy/common/grpc_credentials.h"
#include "xla/python/ifrt_proxy/common/grpc_ifrt_service.grpc.pb.h"
#include "xla/python/ifrt_proxy/common/ifrt_service.pb.h"
#include "tsl/platform/env.h"
#include "tsl/platform/errors.h"
#include "tsl/platform/logging.h"
#include "tsl/platform/threadpool.h"
#include "tsl/platform/unbounded_work_queue.h"
namespace xla {
namespace ifrt {
namespace proxy {
using OpId = int64_t;
class GrpcClientSession::ResponseCallbackTable {
public:
absl::Status Add(OpId op_id, ResponseCallback callback) {
absl::MutexLock l(&mu_);
const bool inserted = table_.insert({op_id, std::move(callback)}).second;
if (!inserted) {
return absl::AlreadyExistsError(
absl::StrCat("Op id ", op_id, " already exists"));
}
return absl::OkStatus();
}
std::optional<ResponseCallback> Pop(OpId op_id) {
absl::MutexLock l(&mu_);
auto it = table_.find(op_id);
if (it == table_.end()) {
return std::nullopt;
}
auto cb = std::move(it->second);
table_.erase(it);
return std::move(cb);
}
absl::flat_hash_map<OpId, ResponseCallback> PopAll() {
absl::flat_hash_map<OpId, ResponseCallback> result;
absl::MutexLock l(&mu_);
result = std::move(table_);
table_ = absl::flat_hash_map<OpId, ResponseCallback>();
return result;
}
private:
absl::Mutex mu_;
absl::flat_hash_map<OpId, ResponseCallback> table_ ABSL_GUARDED_BY(mu_);
};
std::shared_ptr<GrpcClientSession> GrpcClientSession::Create(
std::shared_ptr<grpc::GrpcIfrtService::StubInterface> stub,
GrpcIfrtSessionMetadata metadata,
StreamTerminatedCallback stream_terminated_cb) {
auto context = std::make_unique<::grpc::ClientContext>();
context->AddMetadata("ifrt-proxy-grpc-ifrt-session-metadata-bin",
metadata.SerializeAsString());
std::shared_ptr<GrpcClientSession> result(new GrpcClientSession(
std::move(stub), std::move(context), std::move(stream_terminated_cb)));
return result;
}
GrpcClientSession::GrpcClientSession(
std::shared_ptr<grpc::GrpcIfrtService::StubInterface> stub,
std::unique_ptr<::grpc::ClientContext> context,
StreamTerminatedCallback stream_terminated_cb)
: response_callbacks_(std::make_unique<ResponseCallbackTable>()),
reader_thread_(std::make_unique<tsl::thread::ThreadPool>(
tsl::Env::Default(), "ifrt_proxy_client_grpc_reader",
1)),
stub_(std::move(stub)),
context_(std::move(context)),
stream_(stub_->IfrtSession(context_.get())),
stream_terminated_cb_(std::move(stream_terminated_cb)),
user_futures_work_queue_(std::make_unique<tsl::UnboundedWorkQueue>(
tsl::Env::Default(), "GrpcClientSessionUserFuturesWorkQueue")) {
reader_thread_->Schedule(
absl::bind_front(&GrpcClientSession::ReadLoop, this));
}
Future<std::shared_ptr<IfrtResponse>> GrpcClientSession::Enqueue(
std::unique_ptr<IfrtRequest> request) {
auto promise = Future<std::shared_ptr<IfrtResponse>>::CreatePromise();
absl::Status status = Enqueue(
std::move(request),
[promise, queue = user_futures_work_queue_.get()](
absl::StatusOr<std::shared_ptr<IfrtResponse>> response) mutable {
queue->Schedule([promise = std::move(promise),
response = std::move(response)]() mutable -> void {
promise.Set(std::move(response));
});
});
if (!status.ok()) {
user_futures_work_queue_->Schedule([promise, status]() mutable -> void {
promise.Set(std::move(status));
});
}
return Future<std::shared_ptr<IfrtResponse>>(std::move(promise));
}
absl::Status GrpcClientSession::Enqueue(std::unique_ptr<IfrtRequest> req,
ResponseCallback callback) {
const OpId op_id = req->request_metadata().op_id();
absl::MutexLock l(&writer_mu_);
if (writes_stopped_) {
return absl::FailedPreconditionError(
"GrpcClientSession: writes no longer allowed.");
}
TF_RETURN_IF_ERROR(response_callbacks_->Add(op_id, std::move(callback)));
if (!stream_->Write(*req)) {
CHECK(response_callbacks_->Pop(op_id).has_value());
return absl::UnknownError("GrpcClientSession: writing to stream failed.");
}
return absl::OkStatus();
}
void GrpcClientSession::ReadLoop() {
while (true) {
auto read_buffer = std::make_unique<IfrtResponse>();
if (!stream_->Read(read_buffer.get())) {
LOG(INFO) << "GrpcClientSession: reader loop is exiting.";
break;
}
const OpId op_id = read_buffer->response_metadata().op_id();
std::optional<ResponseCallback> callback = response_callbacks_->Pop(op_id);
if (callback.has_value()) {
VLOG(1) << "GrpcClientSession: Issuing callback for " << op_id;
(*callback)(std::move(read_buffer));
VLOG(1) << "GrpcClientSession: Done with callback for " << op_id;
} else {
LOG(ERROR) << "Received response with no remaining registered callback: "
<< read_buffer->DebugString();
}
}
reader_thread_stopped_.Notify();
Finish(absl::OkStatus());
}
void GrpcClientSession::Finish(const absl::Status& client_status) {
LOG(INFO) << "GrpcClientSession: Finish() called with client status "
<< client_status;
absl::call_once(finish_once_, [&] {
context_->TryCancel();
LOG(INFO) << "GrpcClientSession: Waiting for reader thread to stop.";
reader_thread_stopped_.WaitForNotification();
auto finish_stream_and_get_server_status = [&]() -> absl::Status {
LOG(INFO) << "GrpClientSession: Attempting to call stream->Finish()";
absl::MutexLock l(&writer_mu_);
LOG(INFO) << "GrpClientSession: Attempting to call stream->Finish(), "
"mutex acquired";
absl::Status server_status = xla::FromGrpcStatus(stream_->Finish());
LOG(INFO) << "GrpClientSession: stream->Finish() returned server status "
<< server_status;
CHECK(!writes_stopped_);
writes_stopped_ = true;
return server_status;
};
absl::Status combined_status = finish_stream_and_get_server_status();
combined_status.Update(client_status);
auto all_callbacks = response_callbacks_->PopAll();
for (auto& [_, cb] : all_callbacks) {
if (combined_status.ok()) {
cb(absl::AbortedError("Finish(OK) called."));
} else {
cb(combined_status);
}
}
LOG(INFO) << "GrpClientSession::Finish(): calling terminated cb with "
<< combined_status;
stream_terminated_cb_(combined_status);
});
}
GrpcClientSession::~GrpcClientSession() {
GrpcClientSession::Finish(absl::CancelledError("~GrpcClientSession called."));
reader_thread_.reset();
LOG(INFO) << "Deleting GrpcClientSession.user_futures_work_queue_ ...";
user_futures_work_queue_.reset();
LOG(INFO) << "Deleted GrpcClientSession.user_futures_work_queue_.";
}
std::shared_ptr<grpc::GrpcIfrtService::StubInterface> CreateGrpcStub(
absl::string_view server_address) {
::grpc::ChannelArguments args;
args.SetInt(GRPC_ARG_MAX_SEND_MESSAGE_LENGTH, -1);
args.SetInt(GRPC_ARG_MAX_RECEIVE_MESSAGE_LENGTH, -1);
std::shared_ptr<::grpc::Channel> channel = ::grpc::CreateCustomChannel(
std::string(server_address), GetClientCredentials(), args);
VLOG(0) << " Established channel.";
CHECK(channel != nullptr);
std::shared_ptr<grpc::GrpcIfrtService::StubInterface> stub =
grpc::GrpcIfrtService::NewStub(channel);
VLOG(0) << " Created stub.";
CHECK(stub != nullptr);
return stub;
}
}
}
} | #include "xla/python/ifrt_proxy/client/grpc_client_session.h"
#include <atomic>
#include <deque>
#include <functional>
#include <memory>
#include <optional>
#include <string>
#include <utility>
#include <variant>
#include <vector>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "absl/base/thread_annotations.h"
#include "absl/container/flat_hash_set.h"
#include "absl/log/check.h"
#include "absl/log/log.h"
#include "absl/log/log_sink_registry.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/str_cat.h"
#include "absl/synchronization/mutex.h"
#include "absl/synchronization/notification.h"
#include "absl/time/time.h"
#include "grpc/support/time.h"
#include "grpcpp/channel.h"
#include "grpcpp/create_channel.h"
#include "grpcpp/server_builder.h"
#include "grpcpp/server_context.h"
#include "grpcpp/support/status.h"
#include "grpcpp/support/sync_stream.h"
#include "xla/python/ifrt_proxy/client/version.h"
#include "xla/python/ifrt_proxy/common/grpc_credentials.h"
#include "xla/python/ifrt_proxy/common/grpc_ifrt_service.grpc.pb.h"
#include "xla/python/ifrt_proxy/common/grpc_ifrt_service.pb.h"
#include "xla/python/ifrt_proxy/common/ifrt_service.pb.h"
#include "tsl/platform/errors.h"
#include "tsl/platform/logging.h"
#include "tsl/platform/status_matchers.h"
#include "tsl/platform/statusor.h"
#include "tsl/platform/test.h"
namespace xla {
namespace ifrt {
namespace proxy {
namespace {
using ::testing::Not;
using ::tsl::testing::IsOk;
constexpr int kOp1 = 1;
constexpr int kOp2 = 2;
constexpr absl::Duration kSufficientTime = absl::Seconds(5);
GrpcIfrtSessionMetadata Metadata() {
GrpcIfrtSessionMetadata metadata;
metadata.mutable_version()->set_protocol_version(kClientMaxVersion);
return metadata;
}
absl::Status TestError() { return absl::UnknownError("test error"); }
class Queue {
public:
void Push(absl::Status t) {
absl::MutexLock l(&mu_);
queue_.push_back(std::move(t));
}
std::optional<absl::Status> PopOrTimeout(
absl::Duration timeout = kSufficientTime) {
absl::MutexLock l(&mu_);
auto cond = [this]() ABSL_SHARED_LOCKS_REQUIRED(mu_) -> bool {
return !queue_.empty();
};
mu_.AwaitWithTimeout(absl::Condition(&cond), timeout);
if (queue_.empty()) {
return std::nullopt;
}
absl::Status result = std::move(queue_.front());
queue_.pop_front();
return result;
}
absl::Status Pop(absl::Duration timeout = kSufficientTime) {
auto result = PopOrTimeout(timeout);
CHECK(result.has_value()) << "Timeout!";
return *result;
}
void PopAllDuringDestruction() {
absl::MutexLock l(&mu_);
allow_non_empty_destruction_ = true;
}
~Queue() {
absl::MutexLock l(&mu_);
if (!allow_non_empty_destruction_) CHECK(queue_.empty()) << " " << this;
}
private:
absl::Mutex mu_;
std::deque<absl::Status> queue_ ABSL_GUARDED_BY(mu_);
bool allow_non_empty_destruction_ ABSL_GUARDED_BY(mu_) = false;
};
void ExpectHeadAndTail(
std::vector<std::variant<absl::StatusOr<Queue*>, absl::Status>> var_list) {
std::vector<absl::Status> status_list;
for (const auto& v : var_list) {
if (std::holds_alternative<absl::StatusOr<Queue*>>(v)) {
status_list.push_back(std::get<absl::StatusOr<Queue*>>(v).status());
} else {
status_list.push_back(std::get<absl::Status>(v));
}
}
bool seen_not_ok = false;
std::string str;
for (const auto& s : status_list) {
absl::StrAppend(&str, "\n", s.ToString(), "\n-----\n");
}
for (const auto& s : status_list) {
if (!s.ok()) seen_not_ok = true;
if (seen_not_ok) {
EXPECT_THAT(s, Not(IsOk())) << str;
}
}
}
using ServerStream = ::grpc::ServerReaderWriter<IfrtResponse, IfrtRequest>;
using SessionAction = bool;
constexpr SessionAction kContinueSession = true;
constexpr SessionAction kStopSession = false;
using OnSessionStart = std::function<SessionAction()>;
using OnReqReceived =
std::function<SessionAction(const IfrtRequest&, ServerStream*)>;
class SimpleIfrtService : public grpc::GrpcIfrtService::Service {
public:
SimpleIfrtService(OnReqReceived on_req_received,
OnSessionStart on_session_start)
: on_req_received_(std::move(on_req_received)),
on_session_start_(std::move(on_session_start)) {}
::grpc::Status IfrtSession(::grpc::ServerContext* context,
ServerStream* stream) override {
if (on_session_start_ && on_session_start_() == kStopSession) {
return ::grpc::Status::OK;
}
{
absl::MutexLock l(&mu_);
CHECK(contexts_.insert(context).second);
}
while (true) {
IfrtRequest request;
LOG(INFO) << "Server: waiting on Read().";
if (!stream->Read(&request)) {
LOG(INFO) << "Server: Read() returned false.";
break;
}
LOG(INFO) << "Server: Read() returned true.";
if (!on_req_received_) {
IfrtResponse response;
response.mutable_response_metadata()->set_op_id(
request.request_metadata().op_id());
stream->Write(response);
} else if (on_req_received_(request, stream) == kStopSession) {
break;
}
}
{
absl::MutexLock l(&mu_);
CHECK_EQ(contexts_.erase(context), 1);
}
LOG(INFO) << "Finishing IFRT session";
return ::grpc::Status::OK;
}
void CancelAllServerSessions() {
absl::MutexLock l(&mu_);
for (const auto& context : contexts_) {
context->TryCancel();
}
}
private:
const OnReqReceived on_req_received_;
const OnSessionStart on_session_start_;
absl::Mutex mu_;
absl::flat_hash_set<::grpc::ServerContext*> contexts_ ABSL_GUARDED_BY(mu_);
};
class ClientAndServer {
public:
explicit ClientAndServer(OnReqReceived on_req_received = nullptr,
OnSessionStart on_session_start = nullptr) {
std::string address =
absl::StrCat("localhost:", tsl::testing::PickUnusedPortOrDie());
::grpc::ServerBuilder builder;
builder.AddListeningPort(address, GetServerCredentials());
ifrt_service_ =
std::make_unique<SimpleIfrtService>(on_req_received, on_session_start);
builder.RegisterService(ifrt_service_.get());
server_ = builder.BuildAndStart();
LOG(INFO) << "Server started and listening on " << address;
absl::FlushLogSinks();
std::shared_ptr<::grpc::Channel> channel =
::grpc::CreateChannel(address, GetClientCredentials());
channel->WaitForConnected(gpr_time_add(
gpr_now(GPR_CLOCK_REALTIME), gpr_time_from_seconds(10, GPR_TIMESPAN)));
LOG(INFO) << "conn_state = " << channel->GetState(false);
auto stub = grpc::GrpcIfrtService::NewStub(channel);
CHECK(stub != nullptr);
client_session_ = GrpcClientSession::Create(
std::move(stub), Metadata(), [this](absl::Status s) {
client_finished_q_.Push(s);
client_finished_notification_.Notify();
});
client_finished_q_.PopAllDuringDestruction();
}
void StopServer() {
ifrt_service_->CancelAllServerSessions();
server_->Shutdown();
server_->Wait();
}
~ClientAndServer() {
StopServer();
client_session_->Finish(absl::CancelledError("~ClientAndServer"));
client_finished_notification_.WaitForNotificationWithTimeout(
kSufficientTime);
CHECK(client_finished_notification_.HasBeenNotified());
}
GrpcClientSession* client_session() { return client_session_.get(); }
Queue* client_finished_q() { return &client_finished_q_; }
absl::StatusOr<Queue*> SendSimpleRequest(int op_id) {
owned_queues_.push_back(std::make_unique<Queue>());
Queue* q = owned_queues_.back().get();
auto req = std::make_unique<IfrtRequest>();
req->mutable_request_metadata()->set_op_id(op_id);
TF_RETURN_IF_ERROR(client_session_->Enqueue(
std::move(req), [q](absl::StatusOr<GrpcClientSession::Response> resp) {
q->Push(resp.status());
}));
return q;
}
private:
std::vector<std::unique_ptr<Queue>> owned_queues_;
Queue client_finished_q_;
absl::Notification client_finished_notification_;
std::shared_ptr<GrpcClientSession> client_session_;
std::unique_ptr<::grpc::Server> server_;
std::unique_ptr<SimpleIfrtService> ifrt_service_;
};
TEST(GrpcClientSessionTest, HappyCaseOneRequestWithServerTermination) {
ClientAndServer cs;
TF_ASSERT_OK_AND_ASSIGN(Queue * response_q, cs.SendSimpleRequest(kOp1));
EXPECT_THAT(response_q->Pop(), IsOk());
EXPECT_EQ(cs.client_finished_q()->PopOrTimeout(), std::nullopt);
cs.StopServer();
EXPECT_THAT(cs.client_finished_q()->Pop(), Not(IsOk()));
}
TEST(GrpcClientSessionTest, HappyCaseTwoRequestsWithClientFinish) {
ClientAndServer cs;
TF_ASSERT_OK_AND_ASSIGN(Queue * response_q_1, cs.SendSimpleRequest(kOp1));
TF_ASSERT_OK_AND_ASSIGN(Queue * response_q_2, cs.SendSimpleRequest(kOp2));
EXPECT_THAT(response_q_1->Pop(), IsOk());
EXPECT_THAT(response_q_2->Pop(), IsOk());
EXPECT_EQ(cs.client_finished_q()->PopOrTimeout(), std::nullopt);
cs.client_session()->Finish(TestError());
EXPECT_THAT(cs.client_finished_q()->Pop(), Not(IsOk()));
}
TEST(GrpcClientSessionTest, ServerFinishesDuringFirstRead) {
ClientAndServer cs(
[](auto, auto) { return kStopSession; });
TF_ASSERT_OK_AND_ASSIGN(Queue * response_q_1, cs.SendSimpleRequest(kOp1));
EXPECT_THAT(response_q_1->Pop(), Not(IsOk()));
absl::StatusOr<Queue*> response_q_2 = cs.SendSimpleRequest(kOp2);
EXPECT_THAT(response_q_2.status(), Not(IsOk()));
EXPECT_THAT(cs.client_finished_q()->Pop(), Not(IsOk()));
}
TEST(GrpcClientSessionTest, ServerFinishesDuringConstruction) {
ClientAndServer cs(nullptr,
[]() { return kStopSession; });
absl::StatusOr<Queue*> response_q_1 = cs.SendSimpleRequest(kOp1);
absl::StatusOr<Queue*> response_q_2 = cs.SendSimpleRequest(kOp2);
ExpectHeadAndTail({response_q_1, response_q_2});
if (response_q_1.ok()) EXPECT_THAT(response_q_1.value()->Pop(), Not(IsOk()));
if (response_q_2.ok()) EXPECT_THAT(response_q_2.value()->Pop(), Not(IsOk()));
EXPECT_THAT(cs.client_finished_q()->Pop(), Not(IsOk()));
}
TEST(GrpcClientSessionTest, ClientFinishesAfterServerConsumesFirstRequest) {
std::atomic<GrpcClientSession*> session_ptr;
ClientAndServer cs(
[session_ptr = &session_ptr](auto, auto) {
session_ptr->load()->Finish(TestError());
return kContinueSession;
});
session_ptr.store(cs.client_session());
TF_ASSERT_OK_AND_ASSIGN(Queue * response_q_1, cs.SendSimpleRequest(kOp1));
EXPECT_THAT(response_q_1->Pop(), Not(IsOk()));
absl::StatusOr<Queue*> response_q_2 = cs.SendSimpleRequest(kOp2);
EXPECT_THAT(response_q_2.status(), Not(IsOk()));
EXPECT_THAT(cs.client_finished_q()->Pop(), Not(IsOk()));
}
TEST(GrpcClientSessionTest, ClientFinishesAfterServerWritesFirstResponse) {
std::atomic<GrpcClientSession*> session_ptr;
ClientAndServer cs(
[session_ptr = &session_ptr](const IfrtRequest& r,
ServerStream* s) {
IfrtResponse response;
response.mutable_response_metadata()->set_op_id(
r.request_metadata().op_id());
s->Write(response);
session_ptr->load()->Finish(TestError());
return kContinueSession;
});
session_ptr.store(cs.client_session());
TF_ASSERT_OK_AND_ASSIGN(Queue * response_q_1, cs.SendSimpleRequest(kOp1));
absl::StatusOr<Queue*> response_q_2 = cs.SendSimpleRequest(kOp2);
response_q_1->Pop().IgnoreError();
if (response_q_2.ok()) {
EXPECT_THAT(response_q_2.value()->Pop(), Not(IsOk()));
}
EXPECT_THAT(cs.client_finished_q()->Pop(), Not(IsOk()));
}
TEST(GrpcClientSessionTest, ClientFinishesDuringServerConstruction) {
std::atomic<GrpcClientSession*> session_ptr;
absl::Notification init_done;
ClientAndServer cs(nullptr,
[session_ptr = &session_ptr,
init_done = &init_done]() {
init_done->WaitForNotification();
session_ptr->load()->Finish(TestError());
return kContinueSession;
});
session_ptr.store(cs.client_session());
init_done.Notify();
absl::StatusOr<Queue*> response_q_1 = cs.SendSimpleRequest(kOp1);
absl::StatusOr<Queue*> response_q_2 = cs.SendSimpleRequest(kOp2);
if (response_q_1.ok()) {
EXPECT_THAT(response_q_1.value()->Pop(), Not(IsOk()));
}
if (response_q_2.ok()) {
EXPECT_THAT(response_q_2.value()->Pop(), Not(IsOk()));
}
ExpectHeadAndTail({response_q_1, response_q_2});
EXPECT_THAT(cs.client_finished_q()->Pop(), Not(IsOk()));
}
TEST(GrpcClientSessionTest, MethodsAfterFinishReturnError) {
ClientAndServer cs;
TF_ASSERT_OK_AND_ASSIGN(Queue * response_q_1, cs.SendSimpleRequest(kOp1));
cs.client_session()->Finish(TestError());
EXPECT_THAT(cs.SendSimpleRequest(kOp2), Not(IsOk()));
response_q_1->PopAllDuringDestruction();
}
TEST(GrpcClientSessionTest, ReceivingBadIfrtResponseDoesNotCrash) {
ClientAndServer cs(
[](const IfrtRequest& r, ServerStream* s) mutable {
IfrtResponse resp;
resp.mutable_response_metadata()->set_op_id(kOp2);
s->Write(resp);
resp.mutable_response_metadata()->set_op_id(
r.request_metadata().op_id());
s->Write(resp);
return kContinueSession;
});
TF_ASSERT_OK_AND_ASSIGN(Queue * response_q, cs.SendSimpleRequest(kOp1));
EXPECT_THAT(response_q->Pop(), IsOk());
}
TEST(GrpcClientSessionTest, BadInitialChannelFailsPromptly) {
std::string address =
absl::StrCat("localhost:", tsl::testing::PickUnusedPortOrDie());
std::shared_ptr<::grpc::Channel> channel =
::grpc::CreateChannel(address, GetClientCredentials());
std::unique_ptr<grpc::GrpcIfrtService::StubInterface> stub =
grpc::GrpcIfrtService::NewStub(channel);
EXPECT_TRUE(stub != nullptr);
auto session_finished = std::make_shared<Queue>();
auto session = GrpcClientSession::Create(
std::move(stub), Metadata(),
[session_finished](absl::Status s) { session_finished->Push(s); });
EXPECT_THAT(session_finished->Pop(), Not(IsOk()));
}
}
}
}
} |
372 | #ifndef TENSORFLOW_LITE_KERNELS_INTERNAL_REFERENCE_EXP_H_
#define TENSORFLOW_LITE_KERNELS_INTERNAL_REFERENCE_EXP_H_
#include <cmath>
#include "ruy/profiler/instrumentation.h"
#include "tensorflow/lite/kernels/internal/types.h"
namespace tflite {
namespace reference_ops {
template <typename T>
inline void Exp(const T* input_data, const size_t num_elements,
T* output_data) {
ruy::profiler::ScopeLabel label("Exp");
for (size_t idx = 0; idx < num_elements; ++idx) {
output_data[idx] = std::exp(input_data[idx]);
}
}
}
}
#endif
#include <cmath>
#include "tensorflow/lite/core/c/common.h"
#include "tensorflow/lite/kernels/internal/common.h"
#include "tensorflow/lite/kernels/internal/reference/integer_ops/lut.h"
#include "tensorflow/lite/kernels/internal/reference/reference_ops.h"
#include "tensorflow/lite/kernels/internal/tensor.h"
#include "tensorflow/lite/kernels/internal/tensor_ctypes.h"
#include "tensorflow/lite/kernels/kernel_util.h"
namespace tflite {
namespace ops {
namespace builtin {
namespace exp {
enum KernelType {
kReference,
};
struct ExpContext {
ExpContext(TfLiteContext* context, TfLiteNode* node) {
input = GetInput(context, node, 0);
output = GetOutput(context, node, 0);
}
const TfLiteTensor* input;
TfLiteTensor* output;
};
struct OpData {
union {
int8_t lut_int8[LUTSize<int8_t>()];
int16_t lut_int16[LUTSize<int16_t>()];
};
};
void* Init(TfLiteContext* context, const char* buffer, size_t length) {
return new OpData;
}
void Free(TfLiteContext* context, void* buffer) {
delete reinterpret_cast<OpData*>(buffer);
}
TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {
OpData* data = static_cast<OpData*>(node->user_data);
TF_LITE_ENSURE_EQ(context, NumInputs(node), 1);
TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);
ExpContext op_context(context, node);
const TfLiteTensor* input = op_context.input;
TfLiteTensor* output = op_context.output;
TfLiteIntArray* output_dims = TfLiteIntArrayCopy(input->dims);
output->type = input->type;
if (input->type == kTfLiteInt8) {
LUTPopulate<int8_t>(
input->params.scale, input->params.zero_point, output->params.scale,
output->params.zero_point, [](float value) { return std::exp(value); },
data->lut_int8);
} else if (input->type == kTfLiteInt16) {
TF_LITE_ENSURE_EQ(context, input->params.zero_point, 0);
TF_LITE_ENSURE_EQ(context, output->params.zero_point, 0);
LUTPopulate<int16_t>(
input->params.scale, input->params.zero_point, output->params.scale,
output->params.zero_point, [](float value) { return std::exp(value); },
data->lut_int16);
}
return context->ResizeTensor(context, op_context.output, output_dims);
}
template <KernelType kernel_type>
TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {
OpData* data = reinterpret_cast<OpData*>(node->user_data);
ExpContext op_context(context, node);
if (kernel_type == kReference) {
switch (op_context.input->type) {
case kTfLiteFloat32:
reference_ops::Exp(GetTensorData<float>(op_context.input),
NumElements(op_context.input),
GetTensorData<float>(op_context.output));
break;
case kTfLiteInt8:
reference_integer_ops::LookupTable(
GetTensorData<int8_t>(op_context.input),
NumElements(op_context.input), data->lut_int8,
GetTensorData<int8_t>(op_context.output));
break;
case kTfLiteInt16:
reference_integer_ops::LookupTable(
GetTensorData<int16_t>(op_context.input),
NumElements(op_context.input), data->lut_int16,
GetTensorData<int16_t>(op_context.output));
break;
default:
TF_LITE_KERNEL_LOG(context,
"Type %d is currently not supported by Exp.",
op_context.input->type);
return kTfLiteError;
}
}
return kTfLiteOk;
}
}
TfLiteRegistration* Register_EXP_REF() {
static TfLiteRegistration r = {exp::Init, exp::Free, exp::Prepare,
exp::Eval<exp::kReference>};
return &r;
}
TfLiteRegistration* Register_EXP() { return Register_EXP_REF(); }
}
}
} | #include <math.h>
#include <initializer_list>
#include <limits>
#include <type_traits>
#include <vector>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "flatbuffers/flatbuffers.h"
#include "tensorflow/lite/kernels/test_util.h"
#include "tensorflow/lite/schema/schema_generated.h"
namespace tflite {
namespace {
using ::testing::ElementsAreArray;
class BaseExpOpModel : public SingleOpModel {
public:
BaseExpOpModel(const TensorData& input, const TensorData& output) {
input_ = AddInput(input);
output_ = AddOutput(output);
SetBuiltinOp(BuiltinOperator_EXP, BuiltinOptions_ExpOptions,
CreateExpOptions(builder_).Union());
BuildInterpreter({GetShape(input_)});
}
std::vector<int> GetOutputShape() { return GetTensorShape(output_); }
protected:
int input_;
int output_;
};
class FloatExpOpModel : public BaseExpOpModel {
public:
using BaseExpOpModel::BaseExpOpModel;
void SetInput(std::initializer_list<float> data) {
PopulateTensor(input_, data);
}
std::vector<float> GetOutput() { return ExtractVector<float>(output_); }
};
class QuantizedExpOpModel : public BaseExpOpModel {
public:
using BaseExpOpModel::BaseExpOpModel;
template <class T>
void SetInput(std::initializer_list<float> data) {
QuantizeAndPopulate<T>(input_, data);
}
template <typename integer_dtype>
std::vector<float> GetDequantizedOutput() {
return Dequantize<integer_dtype>(ExtractVector<integer_dtype>(output_),
GetScale(output_), GetZeroPoint(output_));
}
};
template <typename T>
inline float GetTolerance(float min, float max) {
float kQuantizedTolerance = (max - min) / (std::numeric_limits<T>::max() -
std::numeric_limits<T>::min());
if (std::is_same<T, int8_t>::value) {
kQuantizedTolerance += (max - min) / 256.0f;
} else if (std::is_same<T, int16_t>::value) {
kQuantizedTolerance += (max - min) / 512.0f;
}
return kQuantizedTolerance;
}
TEST(ExpOpTest, ExpFloat) {
std::initializer_list<float> data = {0.0f, 1.0f, -1.0f, 100.0f,
-100.0f, 0.01f, -0.01f};
FloatExpOpModel m({TensorType_FLOAT32, {1, 1, 7}}, {TensorType_FLOAT32, {}});
m.SetInput(data);
ASSERT_EQ(m.Invoke(), kTfLiteOk);
EXPECT_THAT(m.GetOutputShape(), ElementsAreArray({1, 1, 7}));
EXPECT_THAT(
m.GetOutput(),
ElementsAreArray(ArrayFloatNear(
{std::exp(0.0f), std::exp(1.0f), std::exp(-1.0f), std::exp(100.0f),
std::exp(-100.0f), std::exp(0.01f), std::exp(-0.01f)})));
}
template <TensorType tensor_type, typename integer_dtype>
void QuantizedExpSymmetricTest() {
const float kMin = -1;
const float kMax =
std::numeric_limits<integer_dtype>::max() /
static_cast<float>(std::numeric_limits<integer_dtype>::max() + 1);
const float kQuantizedTolerance = GetTolerance<integer_dtype>(-3.1, 3.1);
QuantizedExpOpModel m({tensor_type, {1, 2, 2, 2}, 1.3f * kMin, 1.3f * kMax},
{tensor_type, {}, 3.01f * kMin, 3.01f * kMax});
m.SetInput<integer_dtype>({-1.3, -1.0, -0.3, 0, 0.1, 0.5, 1.0, 1.1});
ASSERT_EQ(m.Invoke(), kTfLiteOk);
EXPECT_THAT(m.GetOutputShape(), ElementsAreArray({1, 2, 2, 2}));
EXPECT_THAT(m.GetDequantizedOutput<integer_dtype>(),
ElementsAreArray(ArrayFloatNear(
{0.2725, 0.3679, 0.7408, 1.0, 1.1052, 1.6487, 2.7183, 3.0042},
kQuantizedTolerance)));
}
TEST(ExpOpTest, ExpSymmetricInt8) {
QuantizedExpSymmetricTest<TensorType_INT8, int8_t>();
}
TEST(ExpOpTest, ExpSymmetricInt16) {
QuantizedExpSymmetricTest<TensorType_INT16, int16_t>();
}
template <TensorType tensor_type, typename integer_dtype>
void QuantizedExpAsymmetricTest() {
const float kQuantizedTolerance = GetTolerance<integer_dtype>(-1.3, 3.01);
QuantizedExpOpModel m({tensor_type, {1, 2, 2, 2}, -1.3, 1.1},
{tensor_type, {}, 0.0, 3.01});
m.SetInput<integer_dtype>({-1.3, -1.0, -0.3, 0, 0.1, 0.5, 1.0, 1.1});
ASSERT_EQ(m.Invoke(), kTfLiteOk);
EXPECT_THAT(m.GetOutputShape(), ElementsAreArray({1, 2, 2, 2}));
EXPECT_THAT(m.GetDequantizedOutput<integer_dtype>(),
ElementsAreArray(ArrayFloatNear(
{0.2725, 0.3679, 0.7408, 1.0, 1.1052, 1.6487, 2.7183, 3.0042},
kQuantizedTolerance)));
}
TEST(ExpOpTest, ExpAsymmetricInt8) {
QuantizedExpAsymmetricTest<TensorType_INT8, int8_t>();
}
}
} |
373 | #ifndef TENSORSTORE_DRIVER_DOWNSAMPLE_GRID_OCCUPANCY_MAP_H_
#define TENSORSTORE_DRIVER_DOWNSAMPLE_GRID_OCCUPANCY_MAP_H_
#include <vector>
#include "tensorstore/array.h"
#include "tensorstore/box.h"
#include "tensorstore/index.h"
#include "tensorstore/util/span.h"
namespace tensorstore {
namespace internal_downsample {
class GridOccupancyTracker {
public:
std::vector<Index> occupied_chunks;
void MarkOccupied(BoxView<> box) {
occupied_chunks.insert(occupied_chunks.end(), box.origin().begin(),
box.origin().end());
occupied_chunks.insert(occupied_chunks.end(), box.shape().begin(),
box.shape().end());
}
};
class GridOccupancyMap {
public:
explicit GridOccupancyMap(GridOccupancyTracker&& tracker, BoxView<> domain);
DimensionIndex rank() const { return occupied_chunk_mask.rank(); }
bool GetGridCellDomain(span<const Index> grid_cell,
MutableBoxView<> grid_cell_domain) const;
void InitializeCellIterator(span<Index> grid_cell) const;
bool AdvanceCellIterator(span<Index> grid_cell) const;
std::vector<std::vector<Index>> partition_points;
SharedArray<bool> occupied_chunk_mask;
};
}
}
#endif
#include "tensorstore/driver/downsample/grid_occupancy_map.h"
#include <vector>
#include "absl/container/flat_hash_map.h"
#include "tensorstore/array.h"
#include "tensorstore/box.h"
#include "tensorstore/index.h"
#include "tensorstore/util/iterate.h"
#include "tensorstore/util/span.h"
namespace tensorstore {
namespace internal_downsample {
GridOccupancyMap::GridOccupancyMap(GridOccupancyTracker&& tracker,
BoxView<> domain)
: partition_points(domain.rank()) {
const DimensionIndex rank = domain.rank();
span<Index> occupied_chunks = tracker.occupied_chunks;
{
absl::flat_hash_map<Index, Index> partition_map;
for (DimensionIndex dim = 0; dim < rank; ++dim) {
partition_map.clear();
IndexInterval bounds = domain[dim];
partition_map.emplace(bounds.inclusive_min(), 0);
partition_map.emplace(bounds.exclusive_max(), 0);
for (ptrdiff_t i = dim; i < occupied_chunks.size(); i += 2 * rank) {
Index begin = occupied_chunks[i];
Index end = begin + occupied_chunks[i + rank];
partition_map.emplace(begin, 0);
partition_map.emplace(end, 0);
}
auto& dim_partition_points = partition_points[dim];
dim_partition_points.reserve(partition_map.size());
for (const auto& p : partition_map) {
dim_partition_points.push_back(p.first);
}
std::sort(dim_partition_points.begin(), dim_partition_points.end());
for (size_t i = 0, size = dim_partition_points.size(); i < size; ++i) {
partition_map.at(dim_partition_points[i]) = i;
}
for (ptrdiff_t i = dim; i < occupied_chunks.size(); i += 2 * rank) {
Index& begin = occupied_chunks[i];
Index& end = occupied_chunks[i + rank];
end = partition_map.at(begin + end);
begin = partition_map.at(begin);
}
}
}
Index grid_cell[kMaxRank];
span<Index> grid_cell_span(&grid_cell[0], rank);
{
for (DimensionIndex dim = 0; dim < rank; ++dim) {
grid_cell[dim] = partition_points[dim].size() - 1;
}
occupied_chunk_mask =
AllocateArray<bool>(grid_cell_span, c_order, value_init);
}
for (ptrdiff_t i = 0; i < occupied_chunks.size(); i += 2 * rank) {
std::copy_n(&occupied_chunks[i], rank, &grid_cell[0]);
do {
occupied_chunk_mask(grid_cell_span) = true;
} while (internal::AdvanceIndices(rank, &grid_cell[0], &occupied_chunks[i],
&occupied_chunks[i + rank]));
}
}
bool GridOccupancyMap::GetGridCellDomain(
span<const Index> grid_cell, MutableBoxView<> grid_cell_domain) const {
assert(grid_cell.size() == grid_cell_domain.rank());
assert(grid_cell.size() == rank());
if (occupied_chunk_mask(grid_cell)) return false;
for (DimensionIndex dim = 0; dim < grid_cell.size(); ++dim) {
const Index partition_index = grid_cell[dim];
grid_cell_domain[dim] = IndexInterval::UncheckedHalfOpen(
partition_points[dim][partition_index],
partition_points[dim][partition_index + 1]);
}
return true;
}
void GridOccupancyMap::InitializeCellIterator(span<Index> grid_cell) const {
std::fill(grid_cell.begin(), grid_cell.end(), 0);
}
bool GridOccupancyMap::AdvanceCellIterator(span<Index> grid_cell) const {
assert(grid_cell.size() == occupied_chunk_mask.rank());
return internal::AdvanceIndices(grid_cell.size(), grid_cell.data(),
occupied_chunk_mask.shape().data());
}
}
} | #include "tensorstore/driver/downsample/grid_occupancy_map.h"
#include <vector>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "tensorstore/box.h"
#include "tensorstore/index.h"
namespace {
using ::tensorstore::Box;
using ::tensorstore::BoxView;
using ::tensorstore::Index;
using ::tensorstore::MakeArray;
using ::tensorstore::internal_downsample::GridOccupancyMap;
using ::tensorstore::internal_downsample::GridOccupancyTracker;
std::vector<Box<>> GetUnoccupiedBoxes(const GridOccupancyMap& map) {
std::vector<Box<>> boxes;
std::vector<Index> grid_cell(map.rank());
map.InitializeCellIterator(grid_cell);
Box<> box(map.rank());
do {
if (map.GetGridCellDomain(grid_cell, box)) {
boxes.push_back(box);
}
} while (map.AdvanceCellIterator(grid_cell));
return boxes;
}
TEST(GridOccupancyMapTest, Rank1) {
GridOccupancyTracker tracker;
tracker.MarkOccupied(BoxView<1>({1}, {3}));
tracker.MarkOccupied(BoxView<1>({5}, {4}));
GridOccupancyMap map(std::move(tracker), BoxView<1>({-1}, {11}));
EXPECT_THAT(
map.partition_points,
::testing::ElementsAre(::testing::ElementsAre(-1, 1, 4, 5, 9, 10)));
EXPECT_EQ(map.occupied_chunk_mask, MakeArray<bool>({0, 1, 0, 1, 0}));
EXPECT_THAT(GetUnoccupiedBoxes(map),
::testing::ElementsAre(Box<>({-1}, {2}), Box<>({4}, {1}),
Box<>({9}, {1})));
}
TEST(GridOccupancyMapTest, Rank2) {
GridOccupancyTracker tracker;
tracker.MarkOccupied(BoxView<2>({0, 0}, {3, 2}));
tracker.MarkOccupied(BoxView<2>({3, 3}, {1, 3}));
tracker.MarkOccupied(BoxView<2>({0, 5}, {2, 3}));
GridOccupancyMap map(std::move(tracker), BoxView<2>({4, 10}));
EXPECT_THAT(
map.partition_points,
::testing::ElementsAre(::testing::ElementsAre(0, 2, 3, 4),
::testing::ElementsAre(0, 2, 3, 5, 6, 8, 10)));
EXPECT_EQ(map.occupied_chunk_mask, MakeArray<bool>({
{1, 0, 0, 1, 1, 0},
{1, 0, 0, 0, 0, 0},
{0, 0, 1, 1, 0, 0},
}));
EXPECT_THAT(
GetUnoccupiedBoxes(map),
::testing::ElementsAre(
Box<>({0, 2}, {2, 1}), Box<>({0, 3}, {2, 2}), Box<>({0, 8}, {2, 2}),
Box<>({2, 2}, {1, 1}), Box<>({2, 3}, {1, 2}), Box<>({2, 5}, {1, 1}),
Box<>({2, 6}, {1, 2}), Box<>({2, 8}, {1, 2}), Box<>({3, 0}, {1, 2}),
Box<>({3, 2}, {1, 1}), Box<>({3, 6}, {1, 2}), Box<>({3, 8}, {1, 2})));
}
} |
374 | #ifndef XLA_TOOLS_HLO_BISECT_HLO_BISECT_STATE_H_
#define XLA_TOOLS_HLO_BISECT_HLO_BISECT_STATE_H_
#include <memory>
#include <string>
#include <utility>
#include "absl/container/flat_hash_map.h"
#include "absl/container/flat_hash_set.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "xla/hlo/ir/hlo_module.h"
#include "xla/literal.h"
namespace xla {
namespace bisect {
class BugCheckerInterface {
public:
virtual ~BugCheckerInterface() {}
virtual absl::StatusOr<bool> Run(const HloModule& module) = 0;
virtual absl::flat_hash_map<std::string, Literal> GetResults() = 0;
};
class HloBisectState {
public:
explicit HloBisectState(std::unique_ptr<HloModule> module,
BugCheckerInterface* bug_checker)
: module_(std::move(module)), bug_checker_(bug_checker) {}
absl::StatusOr<bool> ShouldProcess();
absl::StatusOr<bool> TrimEntryComputation();
std::unique_ptr<xla::HloModule>&& GetResult();
private:
absl::StatusOr<bool> RunModule(const HloModule& module);
absl::StatusOr<bool> TrimByOutputs();
absl::StatusOr<bool> TrimByInstructions();
absl::StatusOr<bool> TrimByUsingConstants();
absl::Status ExpectModuleIsBuggy();
std::unique_ptr<xla::HloModule> module_;
BugCheckerInterface* bug_checker_;
absl::flat_hash_set<std::string> foldable_instructions_;
absl::flat_hash_map<std::string, Literal> foldable_instructions_values_;
};
}
}
#endif
#include "xla/tools/hlo_bisect/hlo_bisect_state.h"
#include <iterator>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "absl/algorithm/container.h"
#include "absl/container/flat_hash_map.h"
#include "absl/types/span.h"
#include "xla/hlo/ir/hlo_computation.h"
#include "xla/hlo/ir/hlo_instruction.h"
#include "xla/hlo/ir/hlo_module.h"
#include "xla/hlo/ir/hlo_opcode.h"
#include "xla/service/hlo_dce.h"
#include "xla/tests/test_utils.h"
#include "xla/util.h"
namespace xla {
namespace bisect {
namespace {
std::vector<HloInstruction*> GetModifiedInstructionPostOrder(
HloComputation* computation) {
std::vector<HloInstruction*> instructions(
computation->parameter_instructions().begin(),
computation->parameter_instructions().end());
absl::c_copy_if(computation->MakeInstructionPostOrder(),
std::back_inserter(instructions),
[&](const HloInstruction* instr) {
return instr->opcode() != HloOpcode::kParameter;
});
return instructions;
}
absl::Status MorphModuleWithOutputs(HloModule* module,
absl::Span<HloInstruction* const> outputs) {
HloComputation* entry_computation = module->entry_computation();
HloInstruction* new_root = outputs.size() == 1
? outputs[0]
: entry_computation->AddInstruction(
HloInstruction::CreateTuple(outputs));
entry_computation->set_root_instruction(new_root, true);
*module->mutable_entry_computation_layout() =
module->compute_computation_layout();
HloDCE dce;
absl::StatusOr<bool> dce_result = dce.Run(module);
return dce_result.status();
}
absl::Status MorphModuleWithInstructions(
HloModule* module, absl::Span<HloInstruction* const> instructions) {
ConstHloInstructionSet in_range_instructions(instructions.begin(),
instructions.end());
auto keep_result = [&](const HloInstruction* instruction) {
return instruction->opcode() != HloOpcode::kParameter &&
!absl::c_any_of(instruction->users(),
[&](const HloInstruction* user) {
return in_range_instructions.count(user) != 0;
});
};
std::vector<HloInstruction*> outputs;
absl::c_copy_if(instructions, std::back_inserter(outputs), keep_result);
return MorphModuleWithOutputs(module, outputs);
}
absl::Status MorphModuleWithInstructions(HloModule* module,
size_t num_instructions) {
std::vector<HloInstruction*> ordered_instructions =
GetModifiedInstructionPostOrder(module->entry_computation());
HloInstruction* const* instructions_begin = &ordered_instructions.front();
return MorphModuleWithInstructions(
module, absl::MakeSpan(instructions_begin, num_instructions));
}
absl::Status MorphModuleWithLiterals(
HloModule* module, absl::flat_hash_map<std::string, Literal> literal_map) {
HloComputation* entry_computation = module->entry_computation();
absl::flat_hash_map<HloInstruction*, Literal> replace_map;
for (HloInstruction* instruction : entry_computation->instructions()) {
auto it = literal_map.find(instruction->name());
if (it != literal_map.end()) {
replace_map.emplace(instruction, std::move(it->second));
}
}
for (auto& [instruction, literal] : replace_map) {
if (!instruction->IsDead()) {
HloInstruction* new_instruction = entry_computation->AddInstruction(
HloInstruction::CreateConstant(std::move(literal)));
absl::Status replace_status =
entry_computation->ReplaceInstruction(instruction, new_instruction);
TF_RETURN_IF_ERROR(replace_status);
}
}
xla::HloDCE dce;
absl::StatusOr<bool> dce_status = dce.Run(module);
return dce_status.status();
}
bool InstructionNotReplaceableWithConstant(HloInstruction* instruction) {
return instruction->shape().is_dynamic() ||
instruction->opcode() == HloOpcode::kConstant ||
instruction->opcode() == HloOpcode::kTuple ||
instruction->opcode() == HloOpcode::kParameter;
}
}
absl::StatusOr<bool> HloBisectState::ShouldProcess() {
return RunModule(*module_);
}
absl::StatusOr<bool> HloBisectState::TrimEntryComputation() {
bool changed_in_loop = false;
bool changed = false;
for (int iter = 0; changed || iter < 2; iter++) {
if (iter % 2 == 0) {
VLOG(2) << "Trimming by outputs, iteration " << iter;
TF_ASSIGN_OR_RETURN(changed, TrimByOutputs());
} else {
VLOG(2) << "Trimming by instructions, iteration " << iter;
TF_ASSIGN_OR_RETURN(changed, TrimByInstructions());
}
changed_in_loop |= changed;
}
VLOG(2) << "Trimming by replacing instructions with literals";
TF_ASSIGN_OR_RETURN(changed, TrimByUsingConstants());
VLOG(2) << "Final module: " << module_->ToString();
return changed || changed_in_loop;
}
std::unique_ptr<xla::HloModule>&& HloBisectState::GetResult() {
return std::move(module_);
}
absl::StatusOr<bool> HloBisectState::RunModule(const HloModule& module) {
VLOG(3) << "Modified module: " << module.ToString();
absl::StatusOr<bool> bug_result = bug_checker_->Run(module);
TF_RETURN_IF_ERROR(bug_result.status());
VLOG(3) << "Bug checker result: " << bug_result.value();
if (!bug_result.value()) {
for (HloInstruction* instr : module.entry_computation()->instructions()) {
foldable_instructions_.emplace(instr->name());
}
for (auto& [key, value] : bug_checker_->GetResults()) {
foldable_instructions_values_[key] = std::move(value);
}
}
return bug_result;
}
absl::StatusOr<bool> HloBisectState::TrimByOutputs() {
HloInstruction* root_instruction =
module_->entry_computation()->root_instruction();
if (root_instruction->opcode() != HloOpcode::kTuple ||
root_instruction->operand_count() < 2) {
return false;
}
auto run_modified = [&](int64_t start, int64_t end) -> absl::StatusOr<bool> {
std::unique_ptr<HloModule> new_module = module_->Clone("");
HloInstruction* const* new_operands =
new_module->entry_computation()->root_instruction()->operands().begin();
TF_RETURN_IF_ERROR(MorphModuleWithOutputs(
new_module.get(),
absl::MakeSpan(new_operands + start, end - start + 1)));
return RunModule(*new_module);
};
int64_t bisect_low = 0;
int64_t bisect_high = root_instruction->operand_count() - 1;
while (bisect_low < bisect_high) {
int64_t cur = bisect_low + (bisect_high - bisect_low) / 2;
VLOG(2) << "Number of outputs: " << (cur - bisect_low + 1) << " ["
<< bisect_low << ".." << cur << "]";
TF_ASSIGN_OR_RETURN(bool has_bug, run_modified(bisect_low, cur));
if (has_bug) {
bisect_high = cur;
} else {
TF_ASSIGN_OR_RETURN(has_bug, run_modified(cur + 1, bisect_high));
if (has_bug) {
bisect_low = cur + 1;
} else {
break;
}
}
}
bool changed =
(bisect_high - bisect_low) < (root_instruction->operand_count() - 1);
if (changed) {
TF_RETURN_IF_ERROR(MorphModuleWithOutputs(
module_.get(),
absl::MakeSpan(root_instruction->operands().begin() + bisect_low,
bisect_high - bisect_low + 1)));
TF_RETURN_IF_ERROR(ExpectModuleIsBuggy());
}
return changed;
}
absl::StatusOr<bool> HloBisectState::TrimByInstructions() {
HloComputation* computation = module_->entry_computation();
int64_t upper_bound = computation->instruction_count() -
computation->root_instruction()->shape().IsTuple();
int64_t bisect_low = computation->num_parameters() - 1;
int64_t bisect_high = upper_bound;
while (bisect_low + 1 < bisect_high) {
int64_t cur = bisect_low + (bisect_high - bisect_low) / 2;
VLOG(2) << "Number of instructions: " << cur << " (of "
<< computation->instruction_count() << ")";
std::unique_ptr<HloModule> new_module = module_->Clone("");
TF_RETURN_IF_ERROR(MorphModuleWithInstructions(new_module.get(), cur));
TF_ASSIGN_OR_RETURN(bool has_bug, RunModule(*new_module));
if (has_bug) {
bisect_high = cur;
} else {
bisect_low = cur;
}
}
if (bisect_high == computation->num_parameters()) {
return Internal(
"The checker fails on an empty computation! Something is not right. "
"Can't bisect.");
}
bool changed = bisect_high < upper_bound;
if (changed) {
TF_RETURN_IF_ERROR(MorphModuleWithInstructions(module_.get(), bisect_high));
TF_RETURN_IF_ERROR(ExpectModuleIsBuggy());
}
return changed;
}
absl::StatusOr<bool> HloBisectState::TrimByUsingConstants() {
absl::flat_hash_map<std::string, Literal> literal_map;
int64_t random_literals_count = 0;
for (HloInstruction* instr : module_->entry_computation()->instructions()) {
if (InstructionNotReplaceableWithConstant(instr)) {
continue;
}
if (foldable_instructions_values_.contains(instr->name())) {
auto it = foldable_instructions_values_.extract(instr->name());
literal_map.insert(std::move(it));
} else if (foldable_instructions_.contains(instr->name())) {
absl::StatusOr<Literal> literal_status = MakeFakeLiteral(instr->shape());
TF_RETURN_IF_ERROR(literal_status.status());
literal_map[instr->name()] = std::move(literal_status).value();
++random_literals_count;
}
}
VLOG(2) << "Number of literals: " << literal_map.size()
<< " (random: " << random_literals_count << ")";
std::unique_ptr<HloModule> new_module = module_->Clone("");
TF_RETURN_IF_ERROR(
MorphModuleWithLiterals(new_module.get(), std::move(literal_map)));
TF_ASSIGN_OR_RETURN(bool has_bug, RunModule(*new_module));
if (has_bug) {
std::swap(module_, new_module);
}
return has_bug;
}
absl::Status HloBisectState::ExpectModuleIsBuggy() {
TF_ASSIGN_OR_RETURN(bool has_bug, RunModule(*module_));
if (has_bug) {
return absl::OkStatus();
}
const int retry_count = 5;
int bug_count = 0;
for (int i = 0; i < retry_count; i++) {
TF_ASSIGN_OR_RETURN(has_bug, bug_checker_->Run(*module_));
if (has_bug) {
bug_count++;
}
}
if (bug_count != 0) {
return InternalStrCat("The checker is non deterministic! (only ", bug_count,
" failures seen in ", (retry_count + 1), " runs)");
}
return Internal("We \"lost\" the bug while bisecting!");
}
}
} | #include "xla/tools/hlo_bisect/hlo_bisect_state.h"
#include <initializer_list>
#include <string>
#include <utility>
#include <vector>
#include "absl/algorithm/container.h"
#include "absl/status/statusor.h"
#include "xla/hlo/ir/hlo_module.h"
#include "xla/hlo/ir/hlo_opcode.h"
#include "xla/literal.h"
#include "xla/service/pattern_matcher.h"
#include "xla/service/pattern_matcher_gmock.h"
#include "xla/tests/hlo_test_base.h"
namespace xla {
namespace bisect {
namespace {
namespace m = match;
using HloBisectStateTest = HloTestBase;
class TestBugSearch : public BugCheckerInterface {
public:
TestBugSearch(std::initializer_list<HloOpcode> opcodes) : opcodes_(opcodes) {}
absl::StatusOr<bool> Run(const HloModule& module) override {
auto has_opcode = [&](HloOpcode opcode) {
return absl::c_any_of(module.entry_computation()->instructions(),
[opcode](const HloInstruction* instr) {
return instr->opcode() == opcode;
});
};
return absl::c_all_of(opcodes_, has_opcode);
}
absl::flat_hash_map<std::string, Literal> GetResults() override { return {}; }
private:
std::vector<HloOpcode> opcodes_;
};
Literal CreateLiteral(float value) {
Literal result = Literal::CreateFromShape(ShapeUtil::MakeShape(F32, {}));
result.PopulateWithValue(value);
return result;
}
TEST_F(HloBisectStateTest, TrimByOutputs) {
const char* kModuleStr = R"(
HloModule test_module
ENTRY test_computation {
p1 = s32[8] parameter(0)
p2 = s32[8] parameter(1)
a = s32[8] add(p1, p2)
b = s32[8] multiply(p1, p2)
c = s32[8] subtract(p1, p2)
ROOT sum = tuple(a, b, c)
}
)";
TF_ASSERT_OK_AND_ASSIGN(auto module,
ParseAndReturnVerifiedModule(kModuleStr));
TestBugSearch bug_checker({HloOpcode::kMultiply});
HloBisectState bisect(std::move(module), &bug_checker);
TF_ASSERT_OK_AND_ASSIGN(bool changed, bisect.TrimEntryComputation());
EXPECT_TRUE(changed);
auto reduced_module = std::move(bisect).GetResult();
EXPECT_THAT(reduced_module->entry_computation()->root_instruction(),
GmockMatch(m::Multiply(m::Parameter(0), m::Parameter(1))));
}
TEST_F(HloBisectStateTest, TrimByInstructions) {
const char* kModuleStr = R"(
HloModule axpy_module
ENTRY axpy_computation {
alpha = f32[] parameter(0)
broadcast = f32[10] broadcast(alpha), dimensions={}
x = f32[10] parameter(1)
ax = f32[10] multiply(broadcast, x)
y = f32[10] parameter(2)
ROOT add = f32[10] add(ax, y)
}
)";
TF_ASSERT_OK_AND_ASSIGN(auto module,
ParseAndReturnVerifiedModule(kModuleStr));
TestBugSearch bug_checker({HloOpcode::kMultiply, HloOpcode::kBroadcast});
HloBisectState bisect(std::move(module), &bug_checker);
TF_ASSERT_OK_AND_ASSIGN(bool changed, bisect.TrimEntryComputation());
EXPECT_TRUE(changed);
auto reduced_module = std::move(bisect).GetResult();
EXPECT_THAT(
reduced_module->entry_computation()->root_instruction(),
GmockMatch(m::Multiply(m::Broadcast(m::Parameter(0)), m::Parameter(1))));
}
TEST_F(HloBisectStateTest, TrimByUsingRandomConstants) {
const char* kModuleStr = R"(
HloModule test_module
ENTRY test_computation {
p1 = f32[4] parameter(0)
p2 = f32[4] parameter(1)
a = f32[4] multiply(p1, p2)
b = f32[4] add(p1, p2)
ROOT result = f32[4] power(a, b)
}
)";
TF_ASSERT_OK_AND_ASSIGN(auto module,
ParseAndReturnVerifiedModule(kModuleStr));
TestBugSearch bug_checker({HloOpcode::kPower});
HloBisectState bisect(std::move(module), &bug_checker);
TF_ASSERT_OK_AND_ASSIGN(bool changed, bisect.TrimEntryComputation());
EXPECT_TRUE(changed);
auto reduced_module = std::move(bisect).GetResult();
EXPECT_THAT(reduced_module->entry_computation()->root_instruction(),
GmockMatch(m::Power(m::Constant(), m::Constant())));
}
TEST_F(HloBisectStateTest, TrimByUsingReferenceConstants) {
class TestBugSearchWithReferenceConstants : public TestBugSearch {
public:
TestBugSearchWithReferenceConstants()
: TestBugSearch({HloOpcode::kPower}) {}
absl::flat_hash_map<std::string, Literal> GetResults() override {
absl::flat_hash_map<std::string, Literal> results;
results["a"] = CreateLiteral(2.0f);
results["b"] = CreateLiteral(3.0f);
return results;
}
};
const char* kModuleStr = R"(
HloModule test_module
ENTRY test_computation {
p1 = f32[] parameter(0)
p2 = f32[] parameter(1)
a = f32[] multiply(p1, p2)
b = f32[] add(p1, p2)
ROOT result = f32[] power(a, b)
}
)";
TF_ASSERT_OK_AND_ASSIGN(auto module,
ParseAndReturnVerifiedModule(kModuleStr));
TestBugSearchWithReferenceConstants bug_checker;
HloBisectState bisect(std::move(module), &bug_checker);
TF_ASSERT_OK_AND_ASSIGN(bool changed, bisect.TrimEntryComputation());
EXPECT_TRUE(changed);
auto reduced_module = std::move(bisect).GetResult();
EXPECT_THAT(reduced_module->entry_computation()->root_instruction(),
GmockMatch(m::Power(m::Constant(), m::Constant())));
}
TEST_F(HloBisectStateTest, TrimByOutputsLostBug) {
class CustomBugSearch : public TestBugSearch {
public:
CustomBugSearch() : TestBugSearch({HloOpcode::kConstant}) {}
absl::StatusOr<bool> Run(const HloModule& module) override {
TF_ASSIGN_OR_RETURN(bool has_constants, TestBugSearch::Run(module));
int program_size = module.entry_computation()->instruction_count();
return program_size == 5 && !has_constants;
}
};
const char* kModuleStr = R"(
HloModule test_module
ENTRY test_computation {
p1 = s32[8] parameter(0)
p2 = s32[8] parameter(1)
a = s32[8] add(p1, p2)
b = s32[8] multiply(p1, p2)
ROOT sum = tuple(a, b)
}
)";
TF_ASSERT_OK_AND_ASSIGN(auto module,
ParseAndReturnVerifiedModule(kModuleStr));
CustomBugSearch bug_checker;
HloBisectState bisect(std::move(module), &bug_checker);
TF_ASSERT_OK_AND_ASSIGN(bool changed, bisect.TrimEntryComputation());
EXPECT_FALSE(changed);
}
}
}
} |
375 | #ifndef TENSORFLOW_TSL_PLATFORM_ROCM_ROCDL_PATH_H_
#define TENSORFLOW_TSL_PLATFORM_ROCM_ROCDL_PATH_H_
#include "tsl/platform/types.h"
namespace tsl {
string RocmRoot();
string RocdlRoot();
}
#endif
#include "tsl/platform/rocm_rocdl_path.h"
#include <stdlib.h>
#include "tsl/platform/path.h"
#if !defined(PLATFORM_GOOGLE) && TENSORFLOW_USE_ROCM
#include "rocm/rocm_config.h"
#endif
#include "tsl/platform/logging.h"
namespace tsl {
string RocmRoot() {
#if TENSORFLOW_USE_ROCM
if (const char* rocm_path_env = std::getenv("ROCM_PATH")) {
VLOG(3) << "ROCM root = " << rocm_path_env;
return rocm_path_env;
} else {
VLOG(3) << "ROCM root = " << TF_ROCM_TOOLKIT_PATH;
return TF_ROCM_TOOLKIT_PATH;
}
#else
return "";
#endif
}
string RocdlRoot() { return io::JoinPath(RocmRoot(), "amdgcn/bitcode"); }
} | #include "tensorflow/core/platform/rocm_rocdl_path.h"
#include "tensorflow/core/lib/core/status_test_util.h"
#include "tensorflow/core/platform/env.h"
#include "tensorflow/core/platform/path.h"
#include "tensorflow/core/platform/test.h"
#if !defined(PLATFORM_GOOGLE) && TENSORFLOW_USE_ROCM
#include "rocm/rocm_config.h"
#endif
namespace tensorflow {
#if TENSORFLOW_USE_ROCM
TEST(RocmRocdlPathTest, ROCDLPath) {
VLOG(2) << "ROCm-Device-Libs root = " << RocdlRoot();
std::vector<string> rocdl_files;
TF_EXPECT_OK(Env::Default()->GetMatchingPaths(
io::JoinPath(RocdlRoot(), "*.bc"), &rocdl_files));
EXPECT_LT(0, rocdl_files.size());
}
#endif
} |
376 | #ifndef TENSORFLOW_CORE_KERNELS_DATA_RANGE_DATASET_OP_H_
#define TENSORFLOW_CORE_KERNELS_DATA_RANGE_DATASET_OP_H_
#include "tensorflow/core/framework/dataset.h"
namespace tensorflow {
namespace data {
class RangeDatasetOp : public DatasetOpKernel {
public:
static constexpr const char* const kDatasetType = "Range";
static constexpr const char* const kStart = "start";
static constexpr const char* const kStop = "stop";
static constexpr const char* const kStep = "step";
static constexpr const char* const kOutputTypes = "output_types";
static constexpr const char* const kOutputShapes = "output_shapes";
static constexpr const char* const kReplicateOnSplit = "replicate_on_split";
explicit RangeDatasetOp(OpKernelConstruction* ctx);
protected:
void MakeDataset(OpKernelContext* ctx, DatasetBase** output) override;
private:
class Dataset;
class RangeSplitProvider;
DataTypeVector output_types_;
bool replicate_on_split_ = false;
};
}
}
#endif
#include "tensorflow/core/kernels/data/range_dataset_op.h"
#include <cstdlib>
#include <functional>
#include <optional>
#include <string>
#include <utility>
#include "absl/memory/memory.h"
#include "absl/status/status.h"
#include "tensorflow/core/data/global_shuffle_utils.h"
#include "tensorflow/core/data/name_utils.h"
#include "tensorflow/core/data/split_utils.h"
#include "tensorflow/core/framework/dataset.h"
#include "tensorflow/core/framework/partial_tensor_shape.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/platform/errors.h"
#include "tsl/platform/mutex.h"
#include "tsl/platform/types.h"
namespace tensorflow {
namespace data {
constexpr const char* const RangeDatasetOp::kDatasetType;
constexpr const char* const RangeDatasetOp::kStart;
constexpr const char* const RangeDatasetOp::kStop;
constexpr const char* const RangeDatasetOp::kStep;
constexpr const char* const RangeDatasetOp::kOutputTypes;
constexpr const char* const RangeDatasetOp::kOutputShapes;
constexpr const char* const RangeDatasetOp::kReplicateOnSplit;
namespace {
constexpr char kNext[] = "next";
constexpr char kHasSplitProvider[] = "has_split_provider";
constexpr char kSlash[] = "/";
constexpr char kSplitProvider[] = "split_provider";
Status ConvertOutputTypes(const tensorflow::DataTypeVector& output_dtypes,
std::vector<Tensor>* out_tensors, int64 value) {
switch (output_dtypes[0]) {
#define HANDLE_TYPE(type) \
case DataTypeToEnum<type>::value: { \
out_tensors->emplace_back(static_cast<type>(value)); \
break; \
}
TF_CALL_NUMBER_TYPES(HANDLE_TYPE);
#undef HANDLE_TYPE
default:
return errors::InvalidArgument("Unsupported data type: ",
DataTypeString(output_dtypes[0]));
}
return absl::OkStatus();
}
int64_t sgn(int64_t val) { return (0 < val) - (val < 0); }
int64_t RangeCardinality(int64_t start, int64_t stop, int64_t step) {
if (stop >= tsl::kint64max) {
return kInfiniteCardinality;
}
if (sgn(stop - start) * sgn(step) <= 0) {
return 0;
} else if (step > 0) {
return (stop - start - 1) / step + 1;
} else {
return (start - stop - 1) / -step + 1;
}
}
class RangeCounter {
public:
RangeCounter(int64_t start, int64_t stop, int64_t step)
: start_(start), stop_(stop), step_(step), next_(start) {}
int64_t GetNext(bool* end_of_counter) {
mutex_lock l(mu_);
if ((step_ > 0 && next_ >= stop_) || (step_ < 0 && next_ <= stop_)) {
*end_of_counter = true;
return -1;
}
*end_of_counter = false;
int64_t result = next_;
next_ += step_;
return result;
}
int64_t Peek() const {
mutex_lock l(mu_);
return next_;
}
void Reset() {
mutex_lock l(mu_);
next_ = start_;
}
void SetNext(int64_t value) {
mutex_lock l(mu_);
next_ = value;
}
int64_t Cardinality() const { return RangeCardinality(start_, stop_, step_); }
private:
const int64_t start_;
const int64_t stop_;
const int64_t step_;
mutable mutex mu_;
int64_t next_ TF_GUARDED_BY(mu_);
};
}
class RangeDatasetOp::RangeSplitProvider : public SplitProvider {
public:
RangeSplitProvider(int64_t start, int64_t stop, int64_t step)
: counter_(start, stop, step) {}
Status GetNext(Tensor* split, bool* end_of_splits) override {
int64_t next = counter_.GetNext(end_of_splits);
if (*end_of_splits) {
return absl::OkStatus();
}
*split = Tensor(DT_INT64, TensorShape{});
split->scalar<int64_t>()() = next;
return absl::OkStatus();
}
Status Reset() override {
counter_.Reset();
return absl::OkStatus();
}
Status Save(std::function<std::string(std::string)> key_name_fn,
IteratorStateWriter* writer) override {
TF_RETURN_IF_ERROR(
writer->WriteScalar(key_name_fn(kNext), counter_.Peek()));
return absl::OkStatus();
}
Status Restore(std::function<std::string(std::string)> key_name_fn,
IteratorStateReader* reader) override {
int64_t next;
TF_RETURN_IF_ERROR(reader->ReadScalar(key_name_fn(kNext), &next));
counter_.SetNext(next);
return absl::OkStatus();
}
int64_t Cardinality() const override { return counter_.Cardinality(); }
private:
RangeCounter counter_;
};
class RangeDatasetOp::Dataset : public DatasetBase {
public:
Dataset(OpKernelContext* ctx, int64_t start, int64_t stop, int64_t step,
DataTypeVector output_dtypes, bool replicate_on_split)
: DatasetBase(DatasetContext(ctx)),
start_(start),
stop_(stop),
step_(step),
output_dtypes_(output_dtypes),
replicate_on_split_(replicate_on_split) {}
absl::Status RandomIndexingCompatible() const override {
return absl::OkStatus();
}
std::unique_ptr<IteratorBase> MakeIteratorInternal(
const string& prefix) const override {
return std::make_unique<Iterator>(Iterator::Params{
this, name_utils::IteratorPrefix(kDatasetType, prefix)});
}
const DataTypeVector& output_dtypes() const override {
return output_dtypes_;
}
const std::vector<PartialTensorShape>& output_shapes() const override {
static std::vector<PartialTensorShape>* shapes =
new std::vector<PartialTensorShape>({PartialTensorShape({})});
return *shapes;
}
string DebugString() const override {
name_utils::DatasetDebugStringParams params;
params.set_args(start_, stop_, step_);
return name_utils::DatasetDebugString(kDatasetType, params);
}
int64_t CardinalityInternal(CardinalityOptions options) const override {
return RangeCardinality(start_, stop_, step_);
}
Status MakeSplitProviders(std::vector<std::unique_ptr<SplitProvider>>*
split_providers) const override {
split_providers->push_back(
std::make_unique<RangeSplitProvider>(start_, stop_, step_));
return absl::OkStatus();
}
Status InputDatasets(std::vector<const DatasetBase*>* inputs) const override {
inputs->clear();
return absl::OkStatus();
}
Status CheckExternalState() const override { return absl::OkStatus(); }
Status Get(OpKernelContext* ctx, int64 index,
std::vector<Tensor>* out_tensors) const override {
return Get(AnyContext(ctx), index, out_tensors);
}
Status Get(AnyContext ctx, int64 index,
std::vector<Tensor>* out_tensors) const override {
TF_RETURN_IF_ERROR(CheckRandomAccessCompatible(index));
return ConvertOutputTypes(output_dtypes(), out_tensors,
start_ + (index * step_));
}
protected:
Status AsGraphDefInternal(SerializationContext* ctx,
DatasetGraphDefBuilder* b,
Node** output) const override {
Node* start = nullptr;
Node* stop = nullptr;
Node* step = nullptr;
TF_RETURN_IF_ERROR(b->AddScalar(start_, &start));
TF_RETURN_IF_ERROR(b->AddScalar(stop_, &stop));
TF_RETURN_IF_ERROR(b->AddScalar(step_, &step));
AttrValue replicate_on_split;
b->BuildAttrValue(replicate_on_split_, &replicate_on_split);
TF_RETURN_IF_ERROR(b->AddDataset(
this, {start, stop, step},
{std::make_pair(kReplicateOnSplit, replicate_on_split)},
output));
return absl::OkStatus();
}
private:
class Iterator : public DatasetIterator<Dataset> {
public:
explicit Iterator(const Params& params)
: DatasetIterator<Dataset>(params),
global_shuffle_iterator_(dataset()) {}
bool SymbolicCheckpointCompatible() const override { return true; }
Status Initialize(IteratorContext* ctx) override {
if (ctx->split_providers().empty() || dataset()->replicate_on_split_) {
counter_ = std::make_unique<RangeCounter>(
dataset()->start_, dataset()->stop_, dataset()->step_);
} else {
TF_ASSIGN_OR_RETURN(split_provider_,
GetSingleSplitProvider(ctx, dataset()));
}
return absl::OkStatus();
}
Status GetNextInternal(IteratorContext* ctx,
std::vector<Tensor>* out_tensors,
bool* end_of_sequence) override {
if (ctx->index_mapper() != nullptr) {
return global_shuffle_iterator_.GetNext(ctx, out_tensors,
end_of_sequence);
}
int64_t value;
if (split_provider_ != nullptr) {
Tensor split;
TF_RETURN_IF_ERROR(split_provider_->GetNext(&split, end_of_sequence));
if (*end_of_sequence) {
return absl::OkStatus();
}
value = split.scalar<int64_t>()();
} else {
value = counter_->GetNext(end_of_sequence);
if (*end_of_sequence) {
return absl::OkStatus();
}
}
out_tensors->reserve(1);
return ConvertOutputTypes(output_dtypes(), out_tensors, value);
}
protected:
std::shared_ptr<model::Node> CreateNode(
IteratorContext* ctx, model::Node::Args args) const override {
return model::MakeSourceNode(std::move(args));
}
Status SaveInternal(SerializationContext* ctx,
IteratorStateWriter* writer) override {
if (split_provider_) {
TF_RETURN_IF_ERROR(
writer->WriteScalar(prefix(), kHasSplitProvider, true));
TF_RETURN_IF_ERROR(split_provider_->Save(
[this](const std::string& key) {
return SplitProviderKeyNameFn(key);
},
writer));
} else {
TF_RETURN_IF_ERROR(
writer->WriteScalar(prefix(), kNext, counter_->Peek()));
}
return absl::OkStatus();
}
Status RestoreInternal(IteratorContext* ctx,
IteratorStateReader* reader) override {
if (ctx->restored_element_count().has_value()) {
return global_shuffle_iterator_.Restore(ctx);
}
if (reader->Contains(prefix(), kHasSplitProvider)) {
TF_RETURN_IF_ERROR(split_provider_->Restore(
[this](const std::string& key) {
return SplitProviderKeyNameFn(key);
},
reader));
} else {
int64_t next;
TF_RETURN_IF_ERROR(reader->ReadScalar(prefix(), kNext, &next));
counter_->SetNext(next);
}
return absl::OkStatus();
}
std::string SplitProviderKeyNameFn(const std::string& key) {
return full_name(absl::StrCat(kSplitProvider, kSlash, key));
}
private:
std::unique_ptr<RangeCounter> counter_;
std::shared_ptr<SplitProvider> split_provider_;
GlobalShuffleIterator global_shuffle_iterator_;
};
const int64_t start_;
const int64_t stop_;
const int64_t step_;
const DataTypeVector output_dtypes_;
const bool replicate_on_split_;
};
RangeDatasetOp::RangeDatasetOp(OpKernelConstruction* ctx)
: DatasetOpKernel(ctx) {
OP_REQUIRES_OK(ctx, ctx->GetAttr(kOutputTypes, &output_types_));
if (ctx->HasAttr(kReplicateOnSplit)) {
OP_REQUIRES_OK(ctx, ctx->GetAttr(kReplicateOnSplit, &replicate_on_split_));
}
}
void RangeDatasetOp::MakeDataset(OpKernelContext* ctx, DatasetBase** output) {
int64_t start;
OP_REQUIRES_OK(ctx, ParseScalarArgument<int64_t>(ctx, kStart, &start));
int64_t stop;
OP_REQUIRES_OK(ctx, ParseScalarArgument<int64_t>(ctx, kStop, &stop));
int64_t step;
OP_REQUIRES_OK(ctx, ParseScalarArgument<int64_t>(ctx, kStep, &step));
OP_REQUIRES(ctx, step != 0,
errors::InvalidArgument("step must be a non-zero integer."));
*output =
new Dataset(ctx, start, stop, step, output_types_, replicate_on_split_);
}
namespace {
REGISTER_KERNEL_BUILDER(Name("RangeDataset").Device(DEVICE_CPU),
RangeDatasetOp);
}
}
} | #include "tensorflow/core/kernels/data/range_dataset_op.h"
#include "tensorflow/core/data/dataset_test_base.h"
namespace tensorflow {
namespace data {
namespace {
class RangeDatasetOpTest : public DatasetOpsTestBase {};
RangeDatasetParams PositiveStepRangeDatasetParams() {
return RangeDatasetParams(0, 10, 3);
}
RangeDatasetParams NegativeStepRangeDatasetParams() {
return RangeDatasetParams(10, 0, -3);
}
RangeDatasetParams Int32OverflowRangeDatasetParames() {
return RangeDatasetParams(2'147'483'647LL, 2'147'483'649LL,
1);
}
RangeDatasetParams UnsignedInt32OverflowRangeDatasetParames() {
return RangeDatasetParams(4'294'967'295LL, 4'294'967'297LL,
1);
}
RangeDatasetParams ZeroStepRangeDatasetParams() {
return RangeDatasetParams(10, 0, 0);
}
RangeDatasetParams RangeDatasetParams1() {
return RangeDatasetParams(0, 10, 3,
{DT_INT32});
}
RangeDatasetParams RangeDatasetParams2() {
return RangeDatasetParams(0, 10, 3,
{DT_INT64});
}
std::vector<GetNextTestCase<RangeDatasetParams>> GetNextTestCases() {
return {{PositiveStepRangeDatasetParams(),
CreateTensors<int64_t>(TensorShape({}), {{0}, {3}, {6}, {9}})},
{NegativeStepRangeDatasetParams(),
CreateTensors<int64_t>(TensorShape({}), {{10}, {7}, {4}, {1}})},
{Int32OverflowRangeDatasetParames(),
CreateTensors<int64_t>(TensorShape({}),
{{2'147'483'647LL}, {2'147'483'648LL}})},
{UnsignedInt32OverflowRangeDatasetParames(),
CreateTensors<int64_t>(TensorShape({}),
{{4'294'967'295LL}, {4'294'967'296LL}})}};
}
ITERATOR_GET_NEXT_TEST_P(RangeDatasetOpTest, RangeDatasetParams,
GetNextTestCases())
TEST_F(RangeDatasetOpTest, DatasetNodeName) {
auto range_dataset_params = PositiveStepRangeDatasetParams();
TF_ASSERT_OK(Initialize(range_dataset_params));
TF_ASSERT_OK(CheckDatasetNodeName(range_dataset_params.node_name()));
}
TEST_F(RangeDatasetOpTest, DatasetTypeString) {
auto range_dataset_params = PositiveStepRangeDatasetParams();
TF_ASSERT_OK(Initialize(range_dataset_params));
TF_ASSERT_OK(
CheckDatasetTypeString(name_utils::OpName(RangeDatasetOp::kDatasetType)));
}
std::vector<DatasetOutputDtypesTestCase<RangeDatasetParams>>
DatasetOutputDtypesTestCases() {
return {{RangeDatasetParams1(),
{DT_INT32}},
{RangeDatasetParams2(),
{DT_INT64}}};
}
DATASET_OUTPUT_DTYPES_TEST_P(RangeDatasetOpTest, RangeDatasetParams,
DatasetOutputDtypesTestCases())
TEST_F(RangeDatasetOpTest, DatasetOutputShapes) {
auto range_dataset_params = PositiveStepRangeDatasetParams();
TF_ASSERT_OK(Initialize(range_dataset_params));
TF_ASSERT_OK(CheckDatasetOutputShapes({PartialTensorShape({})}));
}
std::vector<CardinalityTestCase<RangeDatasetParams>> CardinalityTestCases() {
return {{PositiveStepRangeDatasetParams(),
4},
{NegativeStepRangeDatasetParams(),
4}};
}
DATASET_CARDINALITY_TEST_P(RangeDatasetOpTest, RangeDatasetParams,
CardinalityTestCases())
std::vector<IteratorOutputDtypesTestCase<RangeDatasetParams>>
IteratorOutputDtypesTestCases() {
return {{RangeDatasetParams1(),
{DT_INT32}},
{RangeDatasetParams2(),
{DT_INT64}}};
}
ITERATOR_OUTPUT_DTYPES_TEST_P(RangeDatasetOpTest, RangeDatasetParams,
IteratorOutputDtypesTestCases())
TEST_F(RangeDatasetOpTest, IteratorOutputShapes) {
auto range_dataset_params = PositiveStepRangeDatasetParams();
TF_ASSERT_OK(Initialize(range_dataset_params));
TF_ASSERT_OK(CheckIteratorOutputShapes({PartialTensorShape({})}));
}
TEST_F(RangeDatasetOpTest, IteratorPrefix) {
auto range_dataset_params = PositiveStepRangeDatasetParams();
TF_ASSERT_OK(Initialize(range_dataset_params));
TF_ASSERT_OK(CheckIteratorPrefix(name_utils::IteratorPrefix(
RangeDatasetOp::kDatasetType, range_dataset_params.iterator_prefix())));
}
std::vector<IteratorSaveAndRestoreTestCase<RangeDatasetParams>>
IteratorSaveAndRestoreTestCases() {
return {{PositiveStepRangeDatasetParams(),
{0, 1, 4},
CreateTensors<int64_t>(TensorShape({}), {{0}, {3}, {6}, {9}})},
{NegativeStepRangeDatasetParams(),
{0, 1, 4},
CreateTensors<int64_t>(TensorShape({}), {{10}, {7}, {4}, {1}})}};
}
ITERATOR_SAVE_AND_RESTORE_TEST_P(RangeDatasetOpTest, RangeDatasetParams,
IteratorSaveAndRestoreTestCases())
TEST_F(RangeDatasetOpTest, ZeroStep) {
auto range_dataset_params = ZeroStepRangeDatasetParams();
EXPECT_EQ(Initialize(range_dataset_params).code(),
absl::StatusCode::kInvalidArgument);
}
TEST_F(RangeDatasetOpTest, SplitProviderPositiveStep) {
auto params = RangeDatasetParams(0, 10, 3,
{DT_INT64});
TF_ASSERT_OK(InitializeRuntime(params));
TF_EXPECT_OK(CheckSplitProviderFullIteration(
params, CreateTensors<int64_t>(TensorShape({}), {{0}, {3}, {6}, {9}})));
TF_EXPECT_OK(CheckSplitProviderShardedIteration(
params, 2, 1,
CreateTensors<int64_t>(TensorShape({}), {{3}, {9}})));
}
TEST_F(RangeDatasetOpTest, SplitProviderNegativeStep) {
auto params = RangeDatasetParams(10, 0, -3,
{DT_INT64});
TF_ASSERT_OK(InitializeRuntime(params));
TF_EXPECT_OK(CheckSplitProviderFullIteration(
params, CreateTensors<int64_t>(TensorShape({}), {{10}, {7}, {4}, {1}})));
TF_EXPECT_OK(CheckSplitProviderShardedIteration(
params, 2, 0,
CreateTensors<int64_t>(TensorShape({}), {{10}, {4}})));
}
TEST_F(RangeDatasetOpTest, SplitProviderEmpty) {
auto params = RangeDatasetParams(0, 0, 1,
{DT_INT64});
TF_ASSERT_OK(InitializeRuntime(params));
TF_EXPECT_OK(CheckSplitProviderFullIteration(
params, CreateTensors<int64_t>(TensorShape({}), {})));
TF_EXPECT_OK(CheckSplitProviderShardedIteration(
params, 3, 2,
CreateTensors<int64_t>(TensorShape({}), {})));
}
}
}
} |
377 | #ifndef TENSORSTORE_UTIL_UTF8_STRING_H_
#define TENSORSTORE_UTIL_UTF8_STRING_H_
#include <ostream>
#include <string>
#include "tensorstore/serialization/fwd.h"
namespace tensorstore {
struct Utf8String {
std::string utf8;
friend bool operator<(const Utf8String& a, const Utf8String& b) {
return a.utf8 < b.utf8;
}
friend bool operator<=(const Utf8String& a, const Utf8String& b) {
return a.utf8 <= b.utf8;
}
friend bool operator>(const Utf8String& a, const Utf8String& b) {
return a.utf8 > b.utf8;
}
friend bool operator>=(const Utf8String& a, const Utf8String& b) {
return a.utf8 >= b.utf8;
}
friend bool operator==(const Utf8String& a, const Utf8String& b) {
return a.utf8 == b.utf8;
}
friend bool operator!=(const Utf8String& a, const Utf8String& b) {
return a.utf8 != b.utf8;
}
friend std::ostream& operator<<(std::ostream& os, const Utf8String& s) {
return os << s.utf8;
}
static constexpr auto ApplyMembers = [](auto&& x, auto f) {
return f(x.utf8);
};
};
static_assert(sizeof(Utf8String) == sizeof(std::string), "");
}
TENSORSTORE_DECLARE_SERIALIZER_SPECIALIZATION(tensorstore::Utf8String)
#endif
#include "tensorstore/util/utf8_string.h"
#include "tensorstore/internal/riegeli/delimited.h"
#include "tensorstore/internal/utf8.h"
#include "tensorstore/serialization/serialization.h"
#include "tensorstore/util/quote_string.h"
#include "tensorstore/util/status.h"
#include "tensorstore/util/str_cat.h"
namespace tensorstore {
namespace serialization {
bool Serializer<Utf8String>::Encode(EncodeSink& sink, const Utf8String& value) {
return serialization::WriteDelimited(sink.writer(), value.utf8);
}
bool Serializer<Utf8String>::Decode(DecodeSource& source, Utf8String& value) {
return serialization::ReadDelimitedUtf8(source.reader(), value.utf8);
}
}
} | #include "tensorstore/util/utf8_string.h"
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "tensorstore/serialization/serialization.h"
#include "tensorstore/serialization/test_util.h"
#include "tensorstore/util/status_testutil.h"
namespace {
using ::tensorstore::MatchesStatus;
using ::tensorstore::Utf8String;
using ::tensorstore::serialization::SerializationRoundTrip;
using ::tensorstore::serialization::TestSerializationRoundTrip;
TEST(SerializationTest, Valid) {
TestSerializationRoundTrip(Utf8String{""});
TestSerializationRoundTrip(Utf8String{"abc"});
TestSerializationRoundTrip(Utf8String{"\xc2\x80hello\xc2\xbf"});
}
TEST(SerializationTest, Invalid) {
EXPECT_THAT(SerializationRoundTrip(Utf8String{"\xC1"}),
MatchesStatus(absl::StatusCode::kDataLoss,
"String is not valid utf-8: .*"));
}
} |
378 | #ifndef TENSORFLOW_CORE_COMMON_RUNTIME_COMPOSITE_DEVICE_H_
#define TENSORFLOW_CORE_COMMON_RUNTIME_COMPOSITE_DEVICE_H_
#include "absl/strings/string_view.h"
#include "tensorflow/core/common_runtime/device.h"
#include "tensorflow/core/framework/allocator.h"
#include "tensorflow/core/framework/device_attributes.pb.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/core/status.h"
namespace tensorflow {
extern const char* const kCompositeDeviceType;
class CompositeDevice : public Device {
public:
Status Sync() override {
return errors::Internal(
"Sync() should never been invoked on CompositeDevice.");
}
Allocator* GetAllocator(AllocatorAttributes) override { return nullptr; }
const std::vector<string>* underlying_devices() const {
return &underlying_devices_;
}
static std::unique_ptr<CompositeDevice> MakeDevice(
const std::vector<string>& underlying_devices, const int unique_device_id,
const DeviceNameUtils::ParsedName& host_name, Status* status);
static std::unique_ptr<CompositeDevice> MakeDevice(
const std::vector<string>& underlying_devices, const string& device_name,
Status* status);
bool IsRemoteCallAllowed() const override { return false; }
private:
CompositeDevice(const DeviceAttributes& device_attributes,
const std::vector<string>& underlying_devices)
: Device(nullptr, device_attributes),
underlying_devices_(underlying_devices) {}
const std::vector<string> underlying_devices_;
CompositeDevice(const CompositeDevice&) = delete;
void operator=(const CompositeDevice&) = delete;
};
}
#endif
#include "tensorflow/core/common_runtime/composite_device.h"
#include "absl/strings/str_join.h"
#include "tensorflow/core/util/device_name_utils.h"
namespace tensorflow {
const char* const kCompositeDeviceType = "COMPOSITE";
std::unique_ptr<CompositeDevice> CompositeDevice::MakeDevice(
const std::vector<string>& underlying_devices, const int unique_device_id,
const DeviceNameUtils::ParsedName& host_name, Status* status) {
DeviceNameUtils::ParsedName parsed_name = host_name;
parsed_name.type = kCompositeDeviceType;
parsed_name.id = unique_device_id;
const string device_name = DeviceNameUtils::ParsedNameToString(parsed_name);
return CompositeDevice::MakeDevice(underlying_devices, device_name, status);
}
std::unique_ptr<CompositeDevice> CompositeDevice::MakeDevice(
const std::vector<string>& underlying_devices, const string& device_name,
Status* status) {
if (underlying_devices.empty()) {
status->Update(
errors::InvalidArgument("underlying_devices should not be empty."));
return nullptr;
}
DeviceNameUtils::ParsedName parsed_name;
if (!DeviceNameUtils::ParseFullName(underlying_devices.at(0), &parsed_name)) {
status->Update(tensorflow::errors::InvalidArgument(
"Cannot parse device name ", underlying_devices.at(0),
" when creating CompositeDevice."));
return nullptr;
}
const string& underlying_type = parsed_name.type;
for (int i = 1; i < underlying_devices.size(); ++i) {
DeviceNameUtils::ParsedName name;
if (!DeviceNameUtils::ParseFullName(underlying_devices.at(i), &name)) {
status->Update(tensorflow::errors::InvalidArgument(
"Cannot parse device name ", underlying_devices.at(i),
" when creating CompositeDevice."));
return nullptr;
}
if (name.type != underlying_type) {
status->Update(tensorflow::errors::InvalidArgument(
"Expect device type ", parsed_name.type, "; but got type ", name.type,
" from device: ", underlying_devices.at(i),
" when creating CompositeDevice."));
return nullptr;
}
}
DeviceAttributes device_attributes;
device_attributes.set_name(device_name);
device_attributes.set_device_type(kCompositeDeviceType);
return absl::WrapUnique(
new CompositeDevice(device_attributes, underlying_devices));
}
} | #include "tensorflow/core/common_runtime/composite_device.h"
#include "tensorflow/core/lib/core/status_test_util.h"
namespace tensorflow {
TEST(CompositeDeviceTest, Basic) {
const string host_name = "/job:localhost/replica:0/task:0/device:CPU:0";
DeviceNameUtils::ParsedName parsed_host_name;
EXPECT_TRUE(DeviceNameUtils::ParseFullName(host_name, &parsed_host_name));
std::vector<string> underlying_devices;
{
Status status;
std::unique_ptr<CompositeDevice> composite_device =
CompositeDevice::MakeDevice(underlying_devices, 0,
parsed_host_name, &status);
EXPECT_EQ(composite_device, nullptr);
EXPECT_EQ(error::INVALID_ARGUMENT, status.code());
EXPECT_TRUE(absl::StrContains(status.message(),
"underlying_devices should not be empty"))
<< status.ToString();
}
{
Status status;
underlying_devices.push_back(
"/job:localhost/replica:0/task:0/device:CPU:0");
underlying_devices.push_back(
"/job:localhost/replica:0/task:0/device:CPU:1");
std::unique_ptr<CompositeDevice> composite_device =
CompositeDevice::MakeDevice(underlying_devices, 0,
parsed_host_name, &status);
TF_ASSERT_OK(status);
EXPECT_EQ(composite_device->device_type(), kCompositeDeviceType);
EXPECT_EQ(underlying_devices, *composite_device->underlying_devices());
}
{
Status status;
underlying_devices.push_back(
"/job:localhost/replica:0/task:0/device:GPU:0");
std::unique_ptr<CompositeDevice> composite_device =
CompositeDevice::MakeDevice(underlying_devices, 1,
parsed_host_name, &status);
EXPECT_EQ(composite_device, nullptr);
EXPECT_EQ(error::INVALID_ARGUMENT, status.code());
EXPECT_TRUE(absl::StrContains(status.message(),
"Expect device type CPU; but got type GPU"))
<< status.ToString();
}
}
TEST(CompositeDeviceTest, DeviceName) {
const string composite_device_name =
"/job:localhost/replica:0/task:0/device:CPU:10";
std::vector<string> underlying_devices;
underlying_devices.push_back("/job:worker/replica:0/task:0/device:CPU:0");
underlying_devices.push_back("/job:worker/replica:0/task:0/device:CPU:1");
Status status;
std::unique_ptr<CompositeDevice> composite_device =
CompositeDevice::MakeDevice(underlying_devices, composite_device_name,
&status);
TF_ASSERT_OK(status);
EXPECT_EQ(composite_device->name(), composite_device_name);
EXPECT_EQ(composite_device->device_type(), kCompositeDeviceType);
EXPECT_EQ(underlying_devices, *composite_device->underlying_devices());
}
} |
379 | #ifndef I18N_ADDRESSINPUT_POST_BOX_MATCHERS_H_
#define I18N_ADDRESSINPUT_POST_BOX_MATCHERS_H_
#include <vector>
namespace i18n {
namespace addressinput {
class Rule;
struct RE2PlainPtr;
class PostBoxMatchers {
public:
static std::vector<const RE2PlainPtr*> GetMatchers(const Rule& country_rule);
PostBoxMatchers(const PostBoxMatchers&) = delete;
PostBoxMatchers& operator=(const PostBoxMatchers&) = delete;
};
}
}
#endif
#include "post_box_matchers.h"
#include <algorithm>
#include <cassert>
#include <cstddef>
#include <cstring>
#include <string>
#include <vector>
#include <re2/re2.h>
#include "language.h"
#include "rule.h"
#include "util/re2ptr.h"
#include "util/size.h"
namespace i18n {
namespace addressinput {
namespace {
struct LanguageInfo {
const char* language;
const char* regexp;
static bool less(const LanguageInfo& a, const LanguageInfo& b) {
return strcmp(a.language, b.language) < 0;
}
};
constexpr const LanguageInfo kLanguageInfoMap[] = {
{"ar", R"(صندوق بريد|ص[-. ]ب)"},
{"cs", R"((?i)p\.? ?p\.? \d)"},
{"da", R"((?i)Postboks)"},
{"de", R"((?i)Postfach)"},
{"el", R"((?i)T\.? ?Θ\.? \d{2})"},
{"en", R"(Private Bag|Post(?:al)? Box)"},
{"es", R"((?i)(?:Apartado|Casillas) de correos?)"},
{"fi", R"((?i)Postilokero|P\.?L\.? \d)"},
{"fr", R"((?i)Bo(?:[iî]|î)te Postale|BP \d|CEDEX \d)"},
{"hr", R"((?i)p\.? ?p\.? \d)"},
{"hu", R"((?i)Postafi(?:[oó]|ó)k|Pf\.? \d)"},
{"ja", R"(私書箱\d{1,5}号)"},
{"nl", R"((?i)Postbus)"},
{"no", R"((?i)Postboks)"},
{"pl", R"((?i)Skr(?:\.?|ytka) poczt(?:\.?|owa))"},
{"pt", R"((?i)Apartado)"},
{"ru", R"((?i)абонентский ящик|[аa]"я (?:(?:№|#|N) ?)?\d)"},
{"sv", R"((?i)Box \d)"},
{"und", R"(P\.? ?O\.? Box)"},
{"zh", R"(郵政信箱.{1,5}號|郵局第.{1,10}號信箱)"},
};
constexpr size_t kLanguageInfoMapSize = size(kLanguageInfoMap);
constexpr bool StrLessOrEqualConstexpr(const char* a, const char* b) {
return (*a == '\0') ? true : (
(*a == *b) ? StrLessOrEqualConstexpr(a + 1, b + 1) : (*a < *b));
}
static_assert(StrLessOrEqualConstexpr("", ""), "");
static_assert(StrLessOrEqualConstexpr("", "foo"), "");
static_assert(!StrLessOrEqualConstexpr("foo", ""), "");
static_assert(StrLessOrEqualConstexpr("foo", "foo"), "");
static_assert(!StrLessOrEqualConstexpr("foo", "bar"), "");
static_assert(StrLessOrEqualConstexpr("bar", "foo"), "");
static_assert(StrLessOrEqualConstexpr("foo", "foobar"), "");
static_assert(!StrLessOrEqualConstexpr("foobar", "foo"), "");
constexpr bool CheckLanguageInfoMapOrderConstexpr(size_t n = 0) {
return !StrLessOrEqualConstexpr(kLanguageInfoMap[n].language,
kLanguageInfoMap[n + 1].language) ? false : (
(n + 2 < kLanguageInfoMapSize) ?
CheckLanguageInfoMapOrderConstexpr(n + 1) : true);
}
static_assert(CheckLanguageInfoMapOrderConstexpr(),
"kLanguageInfoMap is not correctly sorted!");
const LanguageInfo* FindLanguageInfoFor(const std::string& language) {
const LanguageInfo* begin = kLanguageInfoMap;
const LanguageInfo* end = begin + kLanguageInfoMapSize;
LanguageInfo key = { language.c_str(), };
const LanguageInfo* probe =
std::lower_bound(begin, end, key, LanguageInfo::less);
if (probe != end && language == probe->language) {
return probe;
}
return nullptr;
}
class StaticRE2Array {
public:
StaticRE2Array() {
for (size_t n = 0; n < kLanguageInfoMapSize; ++n) {
re2s_[n].ptr = new RE2(kLanguageInfoMap[n].regexp);
}
}
~StaticRE2Array() {
for (auto& entry : re2s_) {
delete entry.ptr;
}
}
const RE2PlainPtr* FindMatcherFor(const std::string& language) const {
const LanguageInfo* info = FindLanguageInfoFor(language);
if (!info) {
return nullptr;
}
size_t idx = info - kLanguageInfoMap;
assert(idx < kLanguageInfoMapSize);
return &re2s_[idx];
}
private:
RE2PlainPtr re2s_[kLanguageInfoMapSize];
};
}
std::vector<const RE2PlainPtr*> PostBoxMatchers::GetMatchers(
const Rule& country_rule) {
static const StaticRE2Array kMatchers;
std::vector<std::string> languages{"und"};
for (const auto& language_tag : country_rule.GetLanguages()) {
Language language(language_tag);
languages.push_back(language.base);
}
std::vector<const RE2PlainPtr*> result;
for (const auto& language_tag : languages) {
const RE2PlainPtr* matcher = kMatchers.FindMatcherFor(language_tag);
if (matcher != nullptr) {
result.push_back(matcher);
}
}
return result;
}
}
} | #include "post_box_matchers.h"
#include <gtest/gtest.h>
#include "rule.h"
namespace {
using i18n::addressinput::PostBoxMatchers;
using i18n::addressinput::Rule;
TEST(PostBoxMatchersTest, AlwaysGetMatcherForLanguageUnd) {
Rule rule;
const auto& matchers = PostBoxMatchers::GetMatchers(rule);
EXPECT_EQ(1, matchers.size());
EXPECT_TRUE(matchers[0] != nullptr);
}
TEST(PostBoxMatchersTest, NoMatcherForInvalidLanguage) {
Rule rule;
ASSERT_TRUE(rule.ParseSerializedRule("{\"languages\":\"xx\"}"));
const auto& matchers = PostBoxMatchers::GetMatchers(rule);
EXPECT_EQ(1, matchers.size());
EXPECT_TRUE(matchers[0] != nullptr);
}
TEST(PostBoxMatchersTest, HasMatcherForValidLanguage) {
Rule rule;
ASSERT_TRUE(rule.ParseSerializedRule("{\"languages\":\"sv\"}"));
const auto& matchers = PostBoxMatchers::GetMatchers(rule);
EXPECT_EQ(2, matchers.size());
EXPECT_TRUE(matchers[0] != nullptr);
EXPECT_TRUE(matchers[1] != nullptr);
}
TEST(PostBoxMatchersTest, MixValidAndInvalidLanguage) {
Rule rule;
ASSERT_TRUE(rule.ParseSerializedRule("{\"languages\":\"xx~sv\"}"));
const auto& matchers = PostBoxMatchers::GetMatchers(rule);
EXPECT_EQ(2, matchers.size());
EXPECT_TRUE(matchers[0] != nullptr);
EXPECT_TRUE(matchers[1] != nullptr);
}
TEST(PostBoxMatchersTest, UseBaseLanguageForMatching) {
Rule rule;
ASSERT_TRUE(rule.ParseSerializedRule("{\"languages\":\"sv-SE\"}"));
const auto& matchers = PostBoxMatchers::GetMatchers(rule);
EXPECT_EQ(2, matchers.size());
EXPECT_TRUE(matchers[0] != nullptr);
EXPECT_TRUE(matchers[1] != nullptr);
}
TEST(PostBoxMatchersTest, LenientLanguageTagParsing) {
Rule rule;
ASSERT_TRUE(rule.ParseSerializedRule("{\"languages\":\"SV_SE\"}"));
const auto& matchers = PostBoxMatchers::GetMatchers(rule);
EXPECT_EQ(2, matchers.size());
EXPECT_TRUE(matchers[0] != nullptr);
EXPECT_TRUE(matchers[1] != nullptr);
}
} |
380 | #ifndef QUICHE_HTTP2_DECODER_DECODE_HTTP2_STRUCTURES_H_
#define QUICHE_HTTP2_DECODER_DECODE_HTTP2_STRUCTURES_H_
#include "quiche/http2/decoder/decode_buffer.h"
#include "quiche/http2/http2_structures.h"
#include "quiche/common/platform/api/quiche_export.h"
namespace http2 {
QUICHE_EXPORT void DoDecode(Http2FrameHeader* out, DecodeBuffer* b);
QUICHE_EXPORT void DoDecode(Http2PriorityFields* out, DecodeBuffer* b);
QUICHE_EXPORT void DoDecode(Http2RstStreamFields* out, DecodeBuffer* b);
QUICHE_EXPORT void DoDecode(Http2SettingFields* out, DecodeBuffer* b);
QUICHE_EXPORT void DoDecode(Http2PushPromiseFields* out, DecodeBuffer* b);
QUICHE_EXPORT void DoDecode(Http2PingFields* out, DecodeBuffer* b);
QUICHE_EXPORT void DoDecode(Http2GoAwayFields* out, DecodeBuffer* b);
QUICHE_EXPORT void DoDecode(Http2WindowUpdateFields* out, DecodeBuffer* b);
QUICHE_EXPORT void DoDecode(Http2AltSvcFields* out, DecodeBuffer* b);
QUICHE_EXPORT void DoDecode(Http2PriorityUpdateFields* out, DecodeBuffer* b);
}
#endif
#include "quiche/http2/decoder/decode_http2_structures.h"
#include <cstdint>
#include <cstring>
#include "quiche/http2/decoder/decode_buffer.h"
#include "quiche/http2/http2_constants.h"
#include "quiche/common/platform/api/quiche_logging.h"
namespace http2 {
void DoDecode(Http2FrameHeader* out, DecodeBuffer* b) {
QUICHE_DCHECK_NE(nullptr, out);
QUICHE_DCHECK_NE(nullptr, b);
QUICHE_DCHECK_LE(Http2FrameHeader::EncodedSize(), b->Remaining());
out->payload_length = b->DecodeUInt24();
out->type = static_cast<Http2FrameType>(b->DecodeUInt8());
out->flags = static_cast<Http2FrameFlag>(b->DecodeUInt8());
out->stream_id = b->DecodeUInt31();
}
void DoDecode(Http2PriorityFields* out, DecodeBuffer* b) {
QUICHE_DCHECK_NE(nullptr, out);
QUICHE_DCHECK_NE(nullptr, b);
QUICHE_DCHECK_LE(Http2PriorityFields::EncodedSize(), b->Remaining());
uint32_t stream_id_and_flag = b->DecodeUInt32();
out->stream_dependency = stream_id_and_flag & StreamIdMask();
if (out->stream_dependency == stream_id_and_flag) {
out->is_exclusive = false;
} else {
out->is_exclusive = true;
}
out->weight = b->DecodeUInt8() + 1;
}
void DoDecode(Http2RstStreamFields* out, DecodeBuffer* b) {
QUICHE_DCHECK_NE(nullptr, out);
QUICHE_DCHECK_NE(nullptr, b);
QUICHE_DCHECK_LE(Http2RstStreamFields::EncodedSize(), b->Remaining());
out->error_code = static_cast<Http2ErrorCode>(b->DecodeUInt32());
}
void DoDecode(Http2SettingFields* out, DecodeBuffer* b) {
QUICHE_DCHECK_NE(nullptr, out);
QUICHE_DCHECK_NE(nullptr, b);
QUICHE_DCHECK_LE(Http2SettingFields::EncodedSize(), b->Remaining());
out->parameter = static_cast<Http2SettingsParameter>(b->DecodeUInt16());
out->value = b->DecodeUInt32();
}
void DoDecode(Http2PushPromiseFields* out, DecodeBuffer* b) {
QUICHE_DCHECK_NE(nullptr, out);
QUICHE_DCHECK_NE(nullptr, b);
QUICHE_DCHECK_LE(Http2PushPromiseFields::EncodedSize(), b->Remaining());
out->promised_stream_id = b->DecodeUInt31();
}
void DoDecode(Http2PingFields* out, DecodeBuffer* b) {
QUICHE_DCHECK_NE(nullptr, out);
QUICHE_DCHECK_NE(nullptr, b);
QUICHE_DCHECK_LE(Http2PingFields::EncodedSize(), b->Remaining());
memcpy(out->opaque_bytes, b->cursor(), Http2PingFields::EncodedSize());
b->AdvanceCursor(Http2PingFields::EncodedSize());
}
void DoDecode(Http2GoAwayFields* out, DecodeBuffer* b) {
QUICHE_DCHECK_NE(nullptr, out);
QUICHE_DCHECK_NE(nullptr, b);
QUICHE_DCHECK_LE(Http2GoAwayFields::EncodedSize(), b->Remaining());
out->last_stream_id = b->DecodeUInt31();
out->error_code = static_cast<Http2ErrorCode>(b->DecodeUInt32());
}
void DoDecode(Http2WindowUpdateFields* out, DecodeBuffer* b) {
QUICHE_DCHECK_NE(nullptr, out);
QUICHE_DCHECK_NE(nullptr, b);
QUICHE_DCHECK_LE(Http2WindowUpdateFields::EncodedSize(), b->Remaining());
out->window_size_increment = b->DecodeUInt31();
}
void DoDecode(Http2PriorityUpdateFields* out, DecodeBuffer* b) {
QUICHE_DCHECK_NE(nullptr, out);
QUICHE_DCHECK_NE(nullptr, b);
QUICHE_DCHECK_LE(Http2PriorityUpdateFields::EncodedSize(), b->Remaining());
out->prioritized_stream_id = b->DecodeUInt31();
}
void DoDecode(Http2AltSvcFields* out, DecodeBuffer* b) {
QUICHE_DCHECK_NE(nullptr, out);
QUICHE_DCHECK_NE(nullptr, b);
QUICHE_DCHECK_LE(Http2AltSvcFields::EncodedSize(), b->Remaining());
out->origin_length = b->DecodeUInt16();
}
} | #include "quiche/http2/decoder/decode_http2_structures.h"
#include <stddef.h>
#include <string>
#include "absl/strings/string_view.h"
#include "quiche/http2/decoder/decode_buffer.h"
#include "quiche/http2/decoder/decode_status.h"
#include "quiche/http2/http2_constants.h"
#include "quiche/http2/test_tools/http2_frame_builder.h"
#include "quiche/http2/test_tools/http2_random.h"
#include "quiche/http2/test_tools/http2_structures_test_util.h"
#include "quiche/common/platform/api/quiche_logging.h"
#include "quiche/common/platform/api/quiche_test.h"
namespace http2 {
namespace test {
namespace {
template <typename T, size_t N>
absl::string_view ToStringPiece(T (&data)[N]) {
return absl::string_view(reinterpret_cast<const char*>(data), N * sizeof(T));
}
template <class S>
std::string SerializeStructure(const S& s) {
Http2FrameBuilder fb;
fb.Append(s);
EXPECT_EQ(S::EncodedSize(), fb.size());
return fb.buffer();
}
template <class S>
class StructureDecoderTest : public quiche::test::QuicheTest {
protected:
typedef S Structure;
StructureDecoderTest() : random_(), random_decode_count_(100) {}
void Randomize(S* p) { ::http2::test::Randomize(p, &random_); }
void DecodeLeadingStructure(const S* expected, absl::string_view data) {
ASSERT_LE(S::EncodedSize(), data.size());
DecodeBuffer db(data);
Randomize(&structure_);
DoDecode(&structure_, &db);
EXPECT_EQ(db.Offset(), S::EncodedSize());
if (expected != nullptr) {
EXPECT_EQ(structure_, *expected);
}
}
template <size_t N>
void DecodeLeadingStructure(const char (&data)[N]) {
DecodeLeadingStructure(nullptr, absl::string_view(data, N));
}
void EncodeThenDecode(const S& in_s) {
std::string bytes = SerializeStructure(in_s);
EXPECT_EQ(S::EncodedSize(), bytes.size());
DecodeLeadingStructure(&in_s, bytes);
}
void TestDecodingRandomizedStructures(size_t count) {
for (size_t i = 0; i < count && !HasFailure(); ++i) {
Structure input;
Randomize(&input);
EncodeThenDecode(input);
}
}
void TestDecodingRandomizedStructures() {
TestDecodingRandomizedStructures(random_decode_count_);
}
Http2Random random_;
const size_t random_decode_count_;
uint32_t decode_offset_ = 0;
S structure_;
size_t fast_decode_count_ = 0;
size_t slow_decode_count_ = 0;
};
class FrameHeaderDecoderTest : public StructureDecoderTest<Http2FrameHeader> {};
TEST_F(FrameHeaderDecoderTest, DecodesLiteral) {
{
const char kData[] = {
'\x00', '\x00', '\x05',
'\x01',
'\x08',
'\x00', '\x00', '\x00', '\x01',
'\x04',
'\x00', '\x00', '\x00', '\x00',
};
DecodeLeadingStructure(kData);
if (!HasFailure()) {
EXPECT_EQ(5u, structure_.payload_length);
EXPECT_EQ(Http2FrameType::HEADERS, structure_.type);
EXPECT_EQ(Http2FrameFlag::PADDED, structure_.flags);
EXPECT_EQ(1u, structure_.stream_id);
}
}
{
const char kData[] = {
'\xff', '\xff', '\xff',
'\xff',
'\xff',
'\xff', '\xff', '\xff', '\xff',
};
DecodeLeadingStructure(kData);
if (!HasFailure()) {
EXPECT_EQ((1u << 24) - 1, structure_.payload_length);
EXPECT_EQ(static_cast<Http2FrameType>(255), structure_.type);
EXPECT_EQ(255, structure_.flags);
EXPECT_EQ(0x7FFFFFFFu, structure_.stream_id);
}
}
}
TEST_F(FrameHeaderDecoderTest, DecodesRandomized) {
TestDecodingRandomizedStructures();
}
class PriorityFieldsDecoderTest
: public StructureDecoderTest<Http2PriorityFields> {};
TEST_F(PriorityFieldsDecoderTest, DecodesLiteral) {
{
const char kData[] = {
'\x80', '\x00', '\x00', '\x05',
'\xff',
};
DecodeLeadingStructure(kData);
if (!HasFailure()) {
EXPECT_EQ(5u, structure_.stream_dependency);
EXPECT_EQ(256u, structure_.weight);
EXPECT_EQ(true, structure_.is_exclusive);
}
}
{
const char kData[] = {
'\x7f', '\xff',
'\xff', '\xff',
'\x00',
};
DecodeLeadingStructure(kData);
if (!HasFailure()) {
EXPECT_EQ(StreamIdMask(), structure_.stream_dependency);
EXPECT_EQ(1u, structure_.weight);
EXPECT_FALSE(structure_.is_exclusive);
}
}
}
TEST_F(PriorityFieldsDecoderTest, DecodesRandomized) {
TestDecodingRandomizedStructures();
}
class RstStreamFieldsDecoderTest
: public StructureDecoderTest<Http2RstStreamFields> {};
TEST_F(RstStreamFieldsDecoderTest, DecodesLiteral) {
{
const char kData[] = {
'\x00', '\x00', '\x00', '\x01',
};
DecodeLeadingStructure(kData);
if (!HasFailure()) {
EXPECT_TRUE(structure_.IsSupportedErrorCode());
EXPECT_EQ(Http2ErrorCode::PROTOCOL_ERROR, structure_.error_code);
}
}
{
const char kData[] = {
'\xff', '\xff', '\xff',
'\xff',
};
DecodeLeadingStructure(kData);
if (!HasFailure()) {
EXPECT_FALSE(structure_.IsSupportedErrorCode());
EXPECT_EQ(static_cast<Http2ErrorCode>(0xffffffff), structure_.error_code);
}
}
}
TEST_F(RstStreamFieldsDecoderTest, DecodesRandomized) {
TestDecodingRandomizedStructures();
}
class SettingFieldsDecoderTest
: public StructureDecoderTest<Http2SettingFields> {};
TEST_F(SettingFieldsDecoderTest, DecodesLiteral) {
{
const char kData[] = {
'\x00', '\x01',
'\x00', '\x00', '\x40', '\x00',
};
DecodeLeadingStructure(kData);
if (!HasFailure()) {
EXPECT_TRUE(structure_.IsSupportedParameter());
EXPECT_EQ(Http2SettingsParameter::HEADER_TABLE_SIZE,
structure_.parameter);
EXPECT_EQ(1u << 14, structure_.value);
}
}
{
const char kData[] = {
'\x00', '\x00',
'\xff', '\xff', '\xff', '\xff',
};
DecodeLeadingStructure(kData);
if (!HasFailure()) {
EXPECT_FALSE(structure_.IsSupportedParameter());
EXPECT_EQ(static_cast<Http2SettingsParameter>(0), structure_.parameter);
}
}
}
TEST_F(SettingFieldsDecoderTest, DecodesRandomized) {
TestDecodingRandomizedStructures();
}
class PushPromiseFieldsDecoderTest
: public StructureDecoderTest<Http2PushPromiseFields> {};
TEST_F(PushPromiseFieldsDecoderTest, DecodesLiteral) {
{
const char kData[] = {
'\x00', '\x01', '\x8a', '\x92',
};
DecodeLeadingStructure(kData);
if (!HasFailure()) {
EXPECT_EQ(101010u, structure_.promised_stream_id);
}
}
{
const char kData[] = {
'\xff', '\xff', '\xff',
'\xff',
};
DecodeLeadingStructure(kData);
if (!HasFailure()) {
EXPECT_EQ(StreamIdMask(), structure_.promised_stream_id);
}
}
}
TEST_F(PushPromiseFieldsDecoderTest, DecodesRandomized) {
TestDecodingRandomizedStructures();
}
class PingFieldsDecoderTest : public StructureDecoderTest<Http2PingFields> {};
TEST_F(PingFieldsDecoderTest, DecodesLiteral) {
{
const char kData[] = {
'\x00', '\x01', '\x02', '\x03', '\x04', '\x05', '\x06', '\x07',
};
DecodeLeadingStructure(kData);
if (!HasFailure()) {
EXPECT_EQ(absl::string_view(kData, 8),
ToStringPiece(structure_.opaque_bytes));
}
}
{
const char kData[] = {
'\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00',
};
DecodeLeadingStructure(kData);
if (!HasFailure()) {
EXPECT_EQ(absl::string_view(kData, 8),
ToStringPiece(structure_.opaque_bytes));
}
}
{
const char kData[] = {
'\xff', '\xff', '\xff', '\xff', '\xff', '\xff', '\xff', '\xff',
};
DecodeLeadingStructure(kData);
if (!HasFailure()) {
EXPECT_EQ(absl::string_view(kData, 8),
ToStringPiece(structure_.opaque_bytes));
}
}
}
TEST_F(PingFieldsDecoderTest, DecodesRandomized) {
TestDecodingRandomizedStructures();
}
class GoAwayFieldsDecoderTest : public StructureDecoderTest<Http2GoAwayFields> {
};
TEST_F(GoAwayFieldsDecoderTest, DecodesLiteral) {
{
const char kData[] = {
'\x00', '\x00', '\x00', '\x00',
'\x00', '\x00', '\x00', '\x00',
};
DecodeLeadingStructure(kData);
if (!HasFailure()) {
EXPECT_EQ(0u, structure_.last_stream_id);
EXPECT_TRUE(structure_.IsSupportedErrorCode());
EXPECT_EQ(Http2ErrorCode::HTTP2_NO_ERROR, structure_.error_code);
}
}
{
const char kData[] = {
'\x00', '\x00', '\x00', '\x01',
'\x00', '\x00', '\x00', '\x0d',
};
DecodeLeadingStructure(kData);
if (!HasFailure()) {
EXPECT_EQ(1u, structure_.last_stream_id);
EXPECT_TRUE(structure_.IsSupportedErrorCode());
EXPECT_EQ(Http2ErrorCode::HTTP_1_1_REQUIRED, structure_.error_code);
}
}
{
const char kData[] = {
'\xff', '\xff',
'\xff', '\xff',
'\xff', '\xff',
'\xff', '\xff',
};
DecodeLeadingStructure(kData);
if (!HasFailure()) {
EXPECT_EQ(StreamIdMask(), structure_.last_stream_id);
EXPECT_FALSE(structure_.IsSupportedErrorCode());
EXPECT_EQ(static_cast<Http2ErrorCode>(0xffffffff), structure_.error_code);
}
}
}
TEST_F(GoAwayFieldsDecoderTest, DecodesRandomized) {
TestDecodingRandomizedStructures();
}
class WindowUpdateFieldsDecoderTest
: public StructureDecoderTest<Http2WindowUpdateFields> {};
TEST_F(WindowUpdateFieldsDecoderTest, DecodesLiteral) {
{
const char kData[] = {
'\x00', '\x01', '\x00', '\x00',
};
DecodeLeadingStructure(kData);
if (!HasFailure()) {
EXPECT_EQ(1u << 16, structure_.window_size_increment);
}
}
{
const char kData[] = {
'\x00', '\x00', '\x00', '\x00',
};
DecodeLeadingStructure(kData);
if (!HasFailure()) {
EXPECT_EQ(0u, structure_.window_size_increment);
}
}
{
const char kData[] = {
'\xff', '\xff', '\xff', '\xff',
};
DecodeLeadingStructure(kData);
if (!HasFailure()) {
EXPECT_EQ(StreamIdMask(), structure_.window_size_increment);
}
}
}
TEST_F(WindowUpdateFieldsDecoderTest, DecodesRandomized) {
TestDecodingRandomizedStructures();
}
class AltSvcFieldsDecoderTest : public StructureDecoderTest<Http2AltSvcFields> {
};
TEST_F(AltSvcFieldsDecoderTest, DecodesLiteral) {
{
const char kData[] = {
'\x00', '\x00',
};
DecodeLeadingStructure(kData);
if (!HasFailure()) {
EXPECT_EQ(0, structure_.origin_length);
}
}
{
const char kData[] = {
'\x00', '\x14',
};
DecodeLeadingStructure(kData);
if (!HasFailure()) {
EXPECT_EQ(20, structure_.origin_length);
}
}
{
const char kData[] = {
'\xff', '\xff',
};
DecodeLeadingStructure(kData);
if (!HasFailure()) {
EXPECT_EQ(65535, structure_.origin_length);
}
}
}
TEST_F(AltSvcFieldsDecoderTest, DecodesRandomized) {
TestDecodingRandomizedStructures();
}
}
}
} |
381 | #ifndef TENSORFLOW_CORE_SUMMARY_SUMMARY_FILE_WRITER_H_
#define TENSORFLOW_CORE_SUMMARY_SUMMARY_FILE_WRITER_H_
#include "tensorflow/core/kernels/summary_interface.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/platform/env.h"
#include "tensorflow/core/platform/types.h"
namespace tensorflow {
Status CreateSummaryFileWriter(int max_queue, int flush_millis,
const string& logdir,
const string& filename_suffix, Env* env,
SummaryWriterInterface** result);
}
#endif
#include "tensorflow/core/summary/summary_file_writer.h"
#include <memory>
#include "absl/strings/match.h"
#include "absl/strings/str_cat.h"
#include "tensorflow/core/framework/graph.pb.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/resource_mgr.h"
#include "tensorflow/core/framework/summary.pb.h"
#include "tensorflow/core/framework/types.h"
#include "tensorflow/core/lib/io/path.h"
#include "tensorflow/core/summary/summary_converter.h"
#include "tensorflow/core/util/events_writer.h"
namespace tensorflow {
namespace {
class SummaryFileWriter : public SummaryWriterInterface {
public:
SummaryFileWriter(int max_queue, int flush_millis, Env* env)
: SummaryWriterInterface(),
is_initialized_(false),
max_queue_(max_queue),
flush_millis_(flush_millis),
env_(env) {}
Status Initialize(const string& logdir, const string& filename_suffix) {
const Status is_dir = env_->IsDirectory(logdir);
if (!is_dir.ok()) {
if (is_dir.code() != tensorflow::error::NOT_FOUND) {
return is_dir;
}
TF_RETURN_IF_ERROR(env_->RecursivelyCreateDir(logdir));
}
int32_t pid = env_->GetProcessId();
static std::atomic<int64_t> file_id_counter(0);
string sep = absl::StartsWith(filename_suffix, ".") ? "" : ".";
const string uniquified_filename_suffix = absl::StrCat(
".", pid, ".", file_id_counter.fetch_add(1), sep, filename_suffix);
mutex_lock ml(mu_);
events_writer_ =
std::make_unique<EventsWriter>(io::JoinPath(logdir, "events"));
TF_RETURN_WITH_CONTEXT_IF_ERROR(
events_writer_->InitWithSuffix(uniquified_filename_suffix),
"Could not initialize events writer.");
last_flush_ = env_->NowMicros();
is_initialized_ = true;
return absl::OkStatus();
}
Status Flush() override {
mutex_lock ml(mu_);
if (!is_initialized_) {
return errors::FailedPrecondition("Class was not properly initialized.");
}
return InternalFlush();
}
~SummaryFileWriter() override {
(void)Flush();
}
Status WriteTensor(int64_t global_step, Tensor t, const string& tag,
const string& serialized_metadata) override {
std::unique_ptr<Event> e{new Event};
e->set_step(global_step);
e->set_wall_time(GetWallTime());
Summary::Value* v = e->mutable_summary()->add_value();
if (t.dtype() == DT_STRING) {
t.AsProtoField(v->mutable_tensor());
} else {
t.AsProtoTensorContent(v->mutable_tensor());
}
v->set_tag(tag);
if (!serialized_metadata.empty()) {
v->mutable_metadata()->ParseFromString(serialized_metadata);
}
return WriteEvent(std::move(e));
}
Status WriteScalar(int64_t global_step, Tensor t,
const string& tag) override {
std::unique_ptr<Event> e{new Event};
e->set_step(global_step);
e->set_wall_time(GetWallTime());
TF_RETURN_IF_ERROR(
AddTensorAsScalarToSummary(t, tag, e->mutable_summary()));
return WriteEvent(std::move(e));
}
Status WriteHistogram(int64_t global_step, Tensor t,
const string& tag) override {
std::unique_ptr<Event> e{new Event};
e->set_step(global_step);
e->set_wall_time(GetWallTime());
TF_RETURN_IF_ERROR(
AddTensorAsHistogramToSummary(t, tag, e->mutable_summary()));
return WriteEvent(std::move(e));
}
Status WriteImage(int64_t global_step, Tensor t, const string& tag,
int max_images, Tensor bad_color) override {
std::unique_ptr<Event> e{new Event};
e->set_step(global_step);
e->set_wall_time(GetWallTime());
TF_RETURN_IF_ERROR(AddTensorAsImageToSummary(t, tag, max_images, bad_color,
e->mutable_summary()));
return WriteEvent(std::move(e));
}
Status WriteAudio(int64_t global_step, Tensor t, const string& tag,
int max_outputs, float sample_rate) override {
std::unique_ptr<Event> e{new Event};
e->set_step(global_step);
e->set_wall_time(GetWallTime());
TF_RETURN_IF_ERROR(AddTensorAsAudioToSummary(
t, tag, max_outputs, sample_rate, e->mutable_summary()));
return WriteEvent(std::move(e));
}
Status WriteGraph(int64_t global_step,
std::unique_ptr<GraphDef> graph) override {
std::unique_ptr<Event> e{new Event};
e->set_step(global_step);
e->set_wall_time(GetWallTime());
graph->SerializeToString(e->mutable_graph_def());
return WriteEvent(std::move(e));
}
Status WriteEvent(std::unique_ptr<Event> event) override {
mutex_lock ml(mu_);
queue_.emplace_back(std::move(event));
if (queue_.size() > max_queue_ ||
env_->NowMicros() - last_flush_ > 1000 * flush_millis_) {
return InternalFlush();
}
return absl::OkStatus();
}
string DebugString() const override { return "SummaryFileWriter"; }
private:
double GetWallTime() {
return static_cast<double>(env_->NowMicros()) / 1.0e6;
}
Status InternalFlush() TF_EXCLUSIVE_LOCKS_REQUIRED(mu_) {
for (const std::unique_ptr<Event>& e : queue_) {
events_writer_->WriteEvent(*e);
}
queue_.clear();
TF_RETURN_WITH_CONTEXT_IF_ERROR(events_writer_->Flush(),
"Could not flush events file.");
last_flush_ = env_->NowMicros();
return absl::OkStatus();
}
bool is_initialized_;
const int max_queue_;
const int flush_millis_;
uint64 last_flush_;
Env* env_;
mutex mu_;
std::vector<std::unique_ptr<Event>> queue_ TF_GUARDED_BY(mu_);
std::unique_ptr<EventsWriter> events_writer_ TF_GUARDED_BY(mu_);
std::vector<std::pair<string, SummaryMetadata>> registered_summaries_
TF_GUARDED_BY(mu_);
};
}
Status CreateSummaryFileWriter(int max_queue, int flush_millis,
const string& logdir,
const string& filename_suffix, Env* env,
SummaryWriterInterface** result) {
SummaryFileWriter* w = new SummaryFileWriter(max_queue, flush_millis, env);
const Status s = w->Initialize(logdir, filename_suffix);
if (!s.ok()) {
w->Unref();
*result = nullptr;
return s;
}
*result = w;
return absl::OkStatus();
}
} | #include "tensorflow/core/summary/summary_file_writer.h"
#include "tensorflow/core/framework/summary.pb.h"
#include "tensorflow/core/framework/tensor.pb.h"
#include "tensorflow/core/framework/types.h"
#include "tensorflow/core/framework/types.pb.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/core/refcount.h"
#include "tensorflow/core/lib/io/path.h"
#include "tensorflow/core/lib/io/record_reader.h"
#include "tensorflow/core/platform/env.h"
#include "tensorflow/core/platform/test.h"
#include "tensorflow/core/util/event.pb.h"
namespace tensorflow {
namespace {
class FakeClockEnv : public EnvWrapper {
public:
FakeClockEnv() : EnvWrapper(Env::Default()), current_millis_(0) {}
void AdvanceByMillis(const uint64 millis) { current_millis_ += millis; }
uint64 NowMicros() const override { return current_millis_ * 1000; }
uint64 NowSeconds() const override { return current_millis_ * 1000; }
private:
uint64 current_millis_;
};
class SummaryFileWriterTest : public ::testing::Test {
protected:
Status SummaryTestHelper(
const string& test_name,
const std::function<Status(SummaryWriterInterface*)>& writer_fn,
const std::function<void(const Event&)>& test_fn) {
static std::set<string>* tests = new std::set<string>();
CHECK(tests->insert(test_name).second) << ": " << test_name;
SummaryWriterInterface* writer;
TF_CHECK_OK(CreateSummaryFileWriter(1, 1, testing::TmpDir(), test_name,
&env_, &writer));
core::ScopedUnref deleter(writer);
TF_CHECK_OK(writer_fn(writer));
TF_CHECK_OK(writer->Flush());
std::vector<string> files;
TF_CHECK_OK(env_.GetChildren(testing::TmpDir(), &files));
bool found = false;
for (const string& f : files) {
if (absl::StrContains(f, test_name)) {
if (found) {
return errors::Unknown("Found more than one file for ", test_name);
}
found = true;
std::unique_ptr<RandomAccessFile> read_file;
TF_CHECK_OK(env_.NewRandomAccessFile(io::JoinPath(testing::TmpDir(), f),
&read_file));
io::RecordReader reader(read_file.get(), io::RecordReaderOptions());
tstring record;
uint64 offset = 0;
TF_CHECK_OK(
reader.ReadRecord(&offset,
&record));
TF_CHECK_OK(reader.ReadRecord(&offset, &record));
Event e;
e.ParseFromString(record);
test_fn(e);
}
}
if (!found) {
return errors::Unknown("Found no file for ", test_name);
}
return absl::OkStatus();
}
FakeClockEnv env_;
};
TEST_F(SummaryFileWriterTest, WriteTensor) {
TF_CHECK_OK(SummaryTestHelper("tensor_test",
[](SummaryWriterInterface* writer) {
Tensor one(DT_FLOAT, TensorShape({}));
one.scalar<float>()() = 1.0;
TF_RETURN_IF_ERROR(writer->WriteTensor(
2, one, "name",
SummaryMetadata().SerializeAsString()));
TF_RETURN_IF_ERROR(writer->Flush());
return absl::OkStatus();
},
[](const Event& e) {
EXPECT_EQ(e.step(), 2);
CHECK_EQ(e.summary().value_size(), 1);
EXPECT_EQ(e.summary().value(0).tag(), "name");
}));
TF_CHECK_OK(SummaryTestHelper(
"string_tensor_test",
[](SummaryWriterInterface* writer) {
Tensor hello(DT_STRING, TensorShape({}));
hello.scalar<tstring>()() = "hello";
TF_RETURN_IF_ERROR(writer->WriteTensor(
2, hello, "name", SummaryMetadata().SerializeAsString()));
TF_RETURN_IF_ERROR(writer->Flush());
return absl::OkStatus();
},
[](const Event& e) {
EXPECT_EQ(e.step(), 2);
CHECK_EQ(e.summary().value_size(), 1);
EXPECT_EQ(e.summary().value(0).tag(), "name");
EXPECT_EQ(e.summary().value(0).tensor().dtype(), DT_STRING);
EXPECT_EQ(e.summary().value(0).tensor().string_val()[0], "hello");
}));
}
TEST_F(SummaryFileWriterTest, WriteScalar) {
TF_CHECK_OK(SummaryTestHelper(
"scalar_test",
[](SummaryWriterInterface* writer) {
Tensor one(DT_FLOAT, TensorShape({}));
one.scalar<float>()() = 1.0;
TF_RETURN_IF_ERROR(writer->WriteScalar(2, one, "name"));
TF_RETURN_IF_ERROR(writer->Flush());
return absl::OkStatus();
},
[](const Event& e) {
EXPECT_EQ(e.step(), 2);
CHECK_EQ(e.summary().value_size(), 1);
EXPECT_EQ(e.summary().value(0).tag(), "name");
EXPECT_EQ(e.summary().value(0).simple_value(), 1.0);
}));
}
TEST_F(SummaryFileWriterTest, WriteHistogram) {
TF_CHECK_OK(SummaryTestHelper("hist_test",
[](SummaryWriterInterface* writer) {
Tensor one(DT_FLOAT, TensorShape({}));
one.scalar<float>()() = 1.0;
TF_RETURN_IF_ERROR(
writer->WriteHistogram(2, one, "name"));
TF_RETURN_IF_ERROR(writer->Flush());
return absl::OkStatus();
},
[](const Event& e) {
EXPECT_EQ(e.step(), 2);
CHECK_EQ(e.summary().value_size(), 1);
EXPECT_EQ(e.summary().value(0).tag(), "name");
EXPECT_TRUE(e.summary().value(0).has_histo());
}));
}
namespace {
template <typename T>
static Status CreateImage(SummaryWriterInterface* writer) {
Tensor bad_color(DT_UINT8, TensorShape({1}));
bad_color.scalar<uint8>()() = 0;
Tensor one(DataTypeToEnum<T>::v(), TensorShape({1, 1, 1, 1}));
one.scalar<T>()() = T(1);
TF_RETURN_IF_ERROR(writer->WriteImage(2, one, "name", 1, bad_color));
TF_RETURN_IF_ERROR(writer->Flush());
return absl::OkStatus();
}
static void CheckImage(const Event& e) {
EXPECT_EQ(e.step(), 2);
CHECK_EQ(e.summary().value_size(), 1);
EXPECT_EQ(e.summary().value(0).tag(), "name/image");
CHECK(e.summary().value(0).has_image());
EXPECT_EQ(e.summary().value(0).image().height(), 1);
EXPECT_EQ(e.summary().value(0).image().width(), 1);
EXPECT_EQ(e.summary().value(0).image().colorspace(), 1);
}
}
TEST_F(SummaryFileWriterTest, WriteImageUInt8) {
TF_CHECK_OK(
SummaryTestHelper("image_test_uint8", CreateImage<uint8>, CheckImage));
}
TEST_F(SummaryFileWriterTest, WriteImageFloat) {
TF_CHECK_OK(
SummaryTestHelper("image_test_float", CreateImage<float>, CheckImage));
}
TEST_F(SummaryFileWriterTest, WriteImageHalf) {
TF_CHECK_OK(SummaryTestHelper("image_test_half", CreateImage<Eigen::half>,
CheckImage));
}
TEST_F(SummaryFileWriterTest, WriteImageDouble) {
TF_CHECK_OK(
SummaryTestHelper("image_test_double", CreateImage<double>, CheckImage));
}
TEST_F(SummaryFileWriterTest, WriteAudio) {
TF_CHECK_OK(SummaryTestHelper(
"audio_test",
[](SummaryWriterInterface* writer) {
Tensor one(DT_FLOAT, TensorShape({1, 1}));
one.scalar<float>()() = 1.0;
TF_RETURN_IF_ERROR(writer->WriteAudio(2, one, "name", 1, 1));
TF_RETURN_IF_ERROR(writer->Flush());
return absl::OkStatus();
},
[](const Event& e) {
EXPECT_EQ(e.step(), 2);
CHECK_EQ(e.summary().value_size(), 1);
EXPECT_EQ(e.summary().value(0).tag(), "name/audio");
CHECK(e.summary().value(0).has_audio());
}));
}
TEST_F(SummaryFileWriterTest, WriteEvent) {
TF_CHECK_OK(
SummaryTestHelper("event_test",
[](SummaryWriterInterface* writer) {
std::unique_ptr<Event> e{new Event};
e->set_step(7);
e->mutable_summary()->add_value()->set_tag("hi");
TF_RETURN_IF_ERROR(writer->WriteEvent(std::move(e)));
TF_RETURN_IF_ERROR(writer->Flush());
return absl::OkStatus();
},
[](const Event& e) {
EXPECT_EQ(e.step(), 7);
CHECK_EQ(e.summary().value_size(), 1);
EXPECT_EQ(e.summary().value(0).tag(), "hi");
}));
}
TEST_F(SummaryFileWriterTest, WallTime) {
env_.AdvanceByMillis(7023);
TF_CHECK_OK(SummaryTestHelper(
"wall_time_test",
[](SummaryWriterInterface* writer) {
Tensor one(DT_FLOAT, TensorShape({}));
one.scalar<float>()() = 1.0;
TF_RETURN_IF_ERROR(writer->WriteScalar(2, one, "name"));
TF_RETURN_IF_ERROR(writer->Flush());
return absl::OkStatus();
},
[](const Event& e) { EXPECT_EQ(e.wall_time(), 7.023); }));
}
TEST_F(SummaryFileWriterTest, AvoidFilenameCollision) {
string test_name = "avoid_filename_collision_test";
int num_files = 10;
for (int i = 0; i < num_files; i++) {
SummaryWriterInterface* writer;
TF_CHECK_OK(CreateSummaryFileWriter(1, 1, testing::TmpDir(), test_name,
&env_, &writer));
core::ScopedUnref deleter(writer);
}
std::vector<string> files;
TF_CHECK_OK(env_.GetChildren(testing::TmpDir(), &files));
files.erase(std::remove_if(files.begin(), files.end(),
[test_name](string f) {
return !absl::StrContains(f, test_name);
}),
files.end());
EXPECT_EQ(num_files, files.size())
<< "files = [" << absl::StrJoin(files, ", ") << "]";
}
}
} |
382 | #ifndef STORAGE_LEVELDB_TABLE_FILTER_BLOCK_H_
#define STORAGE_LEVELDB_TABLE_FILTER_BLOCK_H_
#include <cstddef>
#include <cstdint>
#include <string>
#include <vector>
#include "leveldb/slice.h"
#include "util/hash.h"
namespace leveldb {
class FilterPolicy;
class FilterBlockBuilder {
public:
explicit FilterBlockBuilder(const FilterPolicy*);
FilterBlockBuilder(const FilterBlockBuilder&) = delete;
FilterBlockBuilder& operator=(const FilterBlockBuilder&) = delete;
void StartBlock(uint64_t block_offset);
void AddKey(const Slice& key);
Slice Finish();
private:
void GenerateFilter();
const FilterPolicy* policy_;
std::string keys_;
std::vector<size_t> start_;
std::string result_;
std::vector<Slice> tmp_keys_;
std::vector<uint32_t> filter_offsets_;
};
class FilterBlockReader {
public:
FilterBlockReader(const FilterPolicy* policy, const Slice& contents);
bool KeyMayMatch(uint64_t block_offset, const Slice& key);
private:
const FilterPolicy* policy_;
const char* data_;
const char* offset_;
size_t num_;
size_t base_lg_;
};
}
#endif
#include "table/filter_block.h"
#include "leveldb/filter_policy.h"
#include "util/coding.h"
namespace leveldb {
static const size_t kFilterBaseLg = 11;
static const size_t kFilterBase = 1 << kFilterBaseLg;
FilterBlockBuilder::FilterBlockBuilder(const FilterPolicy* policy)
: policy_(policy) {}
void FilterBlockBuilder::StartBlock(uint64_t block_offset) {
uint64_t filter_index = (block_offset / kFilterBase);
assert(filter_index >= filter_offsets_.size());
while (filter_index > filter_offsets_.size()) {
GenerateFilter();
}
}
void FilterBlockBuilder::AddKey(const Slice& key) {
Slice k = key;
start_.push_back(keys_.size());
keys_.append(k.data(), k.size());
}
Slice FilterBlockBuilder::Finish() {
if (!start_.empty()) {
GenerateFilter();
}
const uint32_t array_offset = result_.size();
for (size_t i = 0; i < filter_offsets_.size(); i++) {
PutFixed32(&result_, filter_offsets_[i]);
}
PutFixed32(&result_, array_offset);
result_.push_back(kFilterBaseLg);
return Slice(result_);
}
void FilterBlockBuilder::GenerateFilter() {
const size_t num_keys = start_.size();
if (num_keys == 0) {
filter_offsets_.push_back(result_.size());
return;
}
start_.push_back(keys_.size());
tmp_keys_.resize(num_keys);
for (size_t i = 0; i < num_keys; i++) {
const char* base = keys_.data() + start_[i];
size_t length = start_[i + 1] - start_[i];
tmp_keys_[i] = Slice(base, length);
}
filter_offsets_.push_back(result_.size());
policy_->CreateFilter(&tmp_keys_[0], static_cast<int>(num_keys), &result_);
tmp_keys_.clear();
keys_.clear();
start_.clear();
}
FilterBlockReader::FilterBlockReader(const FilterPolicy* policy,
const Slice& contents)
: policy_(policy), data_(nullptr), offset_(nullptr), num_(0), base_lg_(0) {
size_t n = contents.size();
if (n < 5) return;
base_lg_ = contents[n - 1];
uint32_t last_word = DecodeFixed32(contents.data() + n - 5);
if (last_word > n - 5) return;
data_ = contents.data();
offset_ = data_ + last_word;
num_ = (n - 5 - last_word) / 4;
}
bool FilterBlockReader::KeyMayMatch(uint64_t block_offset, const Slice& key) {
uint64_t index = block_offset >> base_lg_;
if (index < num_) {
uint32_t start = DecodeFixed32(offset_ + index * 4);
uint32_t limit = DecodeFixed32(offset_ + index * 4 + 4);
if (start <= limit && limit <= static_cast<size_t>(offset_ - data_)) {
Slice filter = Slice(data_ + start, limit - start);
return policy_->KeyMayMatch(key, filter);
} else if (start == limit) {
return false;
}
}
return true;
}
} | #include "table/filter_block.h"
#include "gtest/gtest.h"
#include "leveldb/filter_policy.h"
#include "util/coding.h"
#include "util/hash.h"
#include "util/logging.h"
#include "util/testutil.h"
namespace leveldb {
class TestHashFilter : public FilterPolicy {
public:
const char* Name() const override { return "TestHashFilter"; }
void CreateFilter(const Slice* keys, int n, std::string* dst) const override {
for (int i = 0; i < n; i++) {
uint32_t h = Hash(keys[i].data(), keys[i].size(), 1);
PutFixed32(dst, h);
}
}
bool KeyMayMatch(const Slice& key, const Slice& filter) const override {
uint32_t h = Hash(key.data(), key.size(), 1);
for (size_t i = 0; i + 4 <= filter.size(); i += 4) {
if (h == DecodeFixed32(filter.data() + i)) {
return true;
}
}
return false;
}
};
class FilterBlockTest : public testing::Test {
public:
TestHashFilter policy_;
};
TEST_F(FilterBlockTest, EmptyBuilder) {
FilterBlockBuilder builder(&policy_);
Slice block = builder.Finish();
ASSERT_EQ("\\x00\\x00\\x00\\x00\\x0b", EscapeString(block));
FilterBlockReader reader(&policy_, block);
ASSERT_TRUE(reader.KeyMayMatch(0, "foo"));
ASSERT_TRUE(reader.KeyMayMatch(100000, "foo"));
}
TEST_F(FilterBlockTest, SingleChunk) {
FilterBlockBuilder builder(&policy_);
builder.StartBlock(100);
builder.AddKey("foo");
builder.AddKey("bar");
builder.AddKey("box");
builder.StartBlock(200);
builder.AddKey("box");
builder.StartBlock(300);
builder.AddKey("hello");
Slice block = builder.Finish();
FilterBlockReader reader(&policy_, block);
ASSERT_TRUE(reader.KeyMayMatch(100, "foo"));
ASSERT_TRUE(reader.KeyMayMatch(100, "bar"));
ASSERT_TRUE(reader.KeyMayMatch(100, "box"));
ASSERT_TRUE(reader.KeyMayMatch(100, "hello"));
ASSERT_TRUE(reader.KeyMayMatch(100, "foo"));
ASSERT_TRUE(!reader.KeyMayMatch(100, "missing"));
ASSERT_TRUE(!reader.KeyMayMatch(100, "other"));
}
TEST_F(FilterBlockTest, MultiChunk) {
FilterBlockBuilder builder(&policy_);
builder.StartBlock(0);
builder.AddKey("foo");
builder.StartBlock(2000);
builder.AddKey("bar");
builder.StartBlock(3100);
builder.AddKey("box");
builder.StartBlock(9000);
builder.AddKey("box");
builder.AddKey("hello");
Slice block = builder.Finish();
FilterBlockReader reader(&policy_, block);
ASSERT_TRUE(reader.KeyMayMatch(0, "foo"));
ASSERT_TRUE(reader.KeyMayMatch(2000, "bar"));
ASSERT_TRUE(!reader.KeyMayMatch(0, "box"));
ASSERT_TRUE(!reader.KeyMayMatch(0, "hello"));
ASSERT_TRUE(reader.KeyMayMatch(3100, "box"));
ASSERT_TRUE(!reader.KeyMayMatch(3100, "foo"));
ASSERT_TRUE(!reader.KeyMayMatch(3100, "bar"));
ASSERT_TRUE(!reader.KeyMayMatch(3100, "hello"));
ASSERT_TRUE(!reader.KeyMayMatch(4100, "foo"));
ASSERT_TRUE(!reader.KeyMayMatch(4100, "bar"));
ASSERT_TRUE(!reader.KeyMayMatch(4100, "box"));
ASSERT_TRUE(!reader.KeyMayMatch(4100, "hello"));
ASSERT_TRUE(reader.KeyMayMatch(9000, "box"));
ASSERT_TRUE(reader.KeyMayMatch(9000, "hello"));
ASSERT_TRUE(!reader.KeyMayMatch(9000, "foo"));
ASSERT_TRUE(!reader.KeyMayMatch(9000, "bar"));
}
} |
383 | #ifndef TENSORFLOW_CORE_TFRT_SAVED_MODEL_SAVED_MODEL_H_
#define TENSORFLOW_CORE_TFRT_SAVED_MODEL_SAVED_MODEL_H_
#include <cstdint>
#include <functional>
#include <limits>
#include <memory>
#include <optional>
#include <string>
#include <unordered_set>
#include <utility>
#include <vector>
#include "absl/container/flat_hash_map.h"
#include "absl/strings/string_view.h"
#include "absl/types/span.h"
#include "tensorflow/core/framework/graph.pb.h"
#include "tensorflow/core/framework/tensor.pb.h"
#include "tensorflow/core/platform/thread_annotations.h"
#include "tensorflow/core/protobuf/config.pb.h"
#include "tensorflow/core/protobuf/meta_graph.pb.h"
#include "tensorflow/core/tfrt/fallback/fallback_state.h"
#include "tensorflow/core/tfrt/graph_executor/graph_execution_options.h"
#include "tensorflow/core/tfrt/graph_executor/graph_executor.h"
#include "tensorflow/core/tfrt/runtime/runtime.h"
#include "tensorflow/core/tfrt/saved_model/saved_model_util.h"
#include "tsl/platform/protobuf.h"
#include "tfrt/host_context/function.h"
#include "tfrt/host_context/request_deadline_tracker.h"
#include "tfrt/host_context/resource_context.h"
namespace tfrt {
class BEFFile;
class HostContext;
}
namespace tensorflow {
namespace tfrt_stub {
class FunctionMetadata {
public:
explicit FunctionMetadata(const internal::Signature* signature)
: signature_(signature) {
assert(signature);
}
const std::vector<std::string>& GetInputNames() const {
return signature_->input_names;
}
const std::vector<TensorSpec>& GetInputSpecs() const {
return signature_->input_specs;
}
const std::vector<std::string>& GetOutputNames() const {
return signature_->output_names;
}
const std::vector<TensorSpec>& GetOutputSpecs() const {
return signature_->output_specs;
}
const protobuf::Map<std::string, TensorProto>& GetDefaultInputs() const {
return signature_->default_inputs;
}
private:
friend class SavedModelImpl;
const internal::Signature* signature_ = nullptr;
};
class SavedModel {
public:
struct Options {
explicit Options(const Runtime* rt) : graph_execution_options(rt) {}
bool enable_lazy_loading = false;
bool maybe_load_from_mla = false;
bool lazy_loading_use_graph_executor = false;
bool aot_generation = false;
GraphExecutionOptions graph_execution_options;
};
using RunOptions = GraphExecutionRunOptions;
explicit SavedModel(const Runtime* runtime) : options_(runtime) {
DCHECK(runtime);
}
explicit SavedModel(Options options,
std::unique_ptr<GraphExecutor> graph_executor)
: options_(std::move(options)),
graph_executor_(std::move(graph_executor)) {}
virtual ~SavedModel();
const SessionMetadata& model_metadata() const {
return options_.graph_execution_options.model_metadata;
}
const Runtime& runtime() const {
DCHECK(options_.graph_execution_options.runtime);
return *options_.graph_execution_options.runtime;
}
tfrt::HostContext* GetHostContext() const;
GraphExecutor& graph_executor() const { return *graph_executor_; }
virtual const tensorflow::MetaGraphDef& GetMetaGraphDef() const = 0;
virtual std::vector<std::string> GetFunctionNames() const = 0;
virtual std::optional<FunctionMetadata> GetFunctionMetadata(
absl::string_view func_name) const = 0;
virtual tensorflow::Status Run(const RunOptions& run_options,
absl::string_view name,
absl::Span<const tensorflow::Tensor> inputs,
std::vector<tensorflow::Tensor>* outputs) = 0;
virtual tensorflow::Status RunMultipleSignatures(
const RunOptions& run_options, absl::Span<const std::string> names,
absl::Span<const std::vector<tensorflow::Tensor>> multi_inputs,
std::vector<std::vector<tensorflow::Tensor>>* multi_outputs) = 0;
virtual tensorflow::Status RunByTensorNames(
const RunOptions& run_options,
absl::Span<const std::pair<std::string, tensorflow::Tensor>> inputs,
absl::Span<const std::string> output_tensor_names,
absl::Span<const std::string> target_node_names,
std::vector<tensorflow::Tensor>* outputs) = 0;
protected:
const FallbackState& fallback_state() const {
return graph_executor_->fallback_state();
}
FallbackState& fallback_state() { return graph_executor_->fallback_state(); }
const Options options_;
std::unique_ptr<GraphExecutor> graph_executor_;
};
using SignatureMap = absl::flat_hash_map<std::string, internal::Signature>;
using ::tensorflow::StatusOr;
class SavedModelImpl final : public SavedModel {
public:
struct JoinedSignature;
static absl::StatusOr<std::unique_ptr<SavedModel>> LoadSavedModel(
Options options, absl::string_view saved_model_dir,
const std::unordered_set<std::string>& tags);
static absl::StatusOr<std::unique_ptr<SavedModel>> LoadSavedModel(
Options options, tensorflow::MetaGraphDef meta_graph_def,
absl::string_view saved_model_dir);
SavedModelImpl(
Options options, SymbolUids symbol_uids,
tensorflow::MetaGraphDef meta_graph_def, tfrt::BefBuffer bef,
tfrt::RCReference<tfrt::BEFFile> bef_file, mlrt::bc::Buffer bytecode,
std::optional<mlrt::LoadedExecutable> loaded_executable,
absl::flat_hash_map<std::string, internal::Signature> signatures,
std::unique_ptr<OpKernelRunnerTable> runner_table,
std::unique_ptr<tfd::FallbackResourceArray> resource_array,
std::unique_ptr<GraphExecutor> graph_executor);
~SavedModelImpl() override = default;
SavedModelImpl(const SavedModelImpl&) = delete;
SavedModelImpl& operator=(const SavedModelImpl&) = delete;
const tensorflow::MetaGraphDef& GetMetaGraphDef() const override;
std::vector<std::string> GetFunctionNames() const override;
std::optional<FunctionMetadata> GetFunctionMetadata(
absl::string_view func_name) const override;
tensorflow::Status Run(const RunOptions& run_options, absl::string_view name,
absl::Span<const tensorflow::Tensor> inputs,
std::vector<tensorflow::Tensor>* outputs) override;
tensorflow::Status RunMultipleSignatures(
const RunOptions& run_options, absl::Span<const std::string> names,
absl::Span<const std::vector<tensorflow::Tensor>> multi_inputs,
std::vector<std::vector<tensorflow::Tensor>>* multi_outputs) override;
tensorflow::Status RunByTensorNames(
const RunOptions& run_options,
absl::Span<const std::pair<std::string, tensorflow::Tensor>> inputs,
absl::Span<const std::string> output_tensor_names,
absl::Span<const std::string> target_node_names,
std::vector<tensorflow::Tensor>* outputs) override;
private:
struct LoadingResult {
std::string name;
SymbolUids symbol_uids;
mlrt::bc::Buffer bytecode_buffer;
std::unique_ptr<mlrt::LoadedExecutable> bytecode_executable;
tfrt::BefBuffer bef;
tfrt::RCReference<tfrt::BEFFile> bef_file;
std::unique_ptr<OpKernelRunnerTable> runner_table;
std::unique_ptr<tfd::FallbackResourceArray> resource_array;
std::unique_ptr<tfrt::ResourceContext> resource_context;
};
absl::StatusOr<mlir::OwningOpRef<mlir::ModuleOp>> ImportSubgraph(
mlir::MLIRContext* context, absl::string_view name,
const tensorflow::GraphImportConfig::InputArrays& input_nodes,
const std::vector<std::string>& output_nodes,
const std::vector<std::string>& target_nodes);
absl::StatusOr<std::reference_wrapper<const SavedModelImpl::LoadingResult>>
LoadJoinedSignature(const JoinedSignature& joined_signature)
TF_EXCLUSIVE_LOCKS_REQUIRED(loading_result_cache_mu_);
absl::StatusOr<std::reference_wrapper<const SavedModelImpl::LoadingResult>>
GetOrCreateLoadingResult(const RunOptions& run_options,
absl::Span<const std::string> names)
TF_LOCKS_EXCLUDED(loading_result_cache_mu_);
SymbolUids symbol_uids_;
tensorflow::MetaGraphDef meta_graph_def_;
tfrt::BefBuffer bef_;
tfrt::RCReference<tfrt::BEFFile> bef_file_;
mlrt::bc::Buffer bytecode_;
std::optional<mlrt::LoadedExecutable> loaded_executable_;
tfrt::RequestDeadlineTracker req_deadline_tracker_;
absl::flat_hash_map<std::string, internal::Signature> signatures_;
std::unique_ptr<OpKernelRunnerTable> runner_table_;
std::unique_ptr<tfd::FallbackResourceArray> resource_array_;
tensorflow::mutex loading_result_cache_mu_;
absl::flat_hash_map<std::string ,
std::unique_ptr<LoadingResult>>
loading_result_cache_ TF_GUARDED_BY(loading_result_cache_mu_);
};
class SavedModelMiraImpl;
}
}
namespace tfrt {
using SavedModel = ::tensorflow::tfrt_stub::SavedModel;
using SavedModelImpl = ::tensorflow::tfrt_stub::SavedModelImpl;
using SavedModelMiraImpl = ::tensorflow::tfrt_stub::SavedModelMiraImpl;
using TensorSpec = ::tensorflow::tfrt_stub::TensorSpec;
using FunctionMetadata = ::tensorflow::tfrt_stub::FunctionMetadata;
namespace internal {
using Signature = ::tensorflow::tfrt_stub::internal::Signature;
}
}
#endif
#include "tensorflow/core/tfrt/saved_model/saved_model.h"
#include <algorithm>
#include <cstddef>
#include <cstdint>
#include <functional>
#include <iterator>
#include <memory>
#include <optional>
#include <string>
#include <unordered_set>
#include <utility>
#include <vector>
#include "absl/cleanup/cleanup.h"
#include "absl/container/flat_hash_set.h"
#include "absl/log/check.h"
#include "absl/log/log.h"
#include "absl/status/status.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_join.h"
#include "absl/strings/string_view.h"
#include "absl/time/clock.h"
#include "absl/time/time.h"
#include "absl/types/span.h"
#include "mlir/Dialect/Func/Extensions/AllExtensions.h"
#include "mlir/IR/DialectRegistry.h"
#include "mlir/IR/MLIRContext.h"
#include "mlir/IR/OwningOpRef.h"
#include "tensorflow/compiler/jit/flags.h"
#include "tensorflow/compiler/mlir/tensorflow/translate/import_model.h"
#include "tensorflow/compiler/mlir/tensorflow/translate/mlir_roundtrip_flags.h"
#include "tensorflow/compiler/mlir/tensorflow/translate/tf_mlir_translate.h"
#include "tensorflow/compiler/mlir/tfrt/saved_model/saved_model.h"
#include "tensorflow/compiler/mlir/tfrt/transforms/mlrt/import_model.h"
#include "tensorflow/compiler/mlir/tfrt/translate/import_model.h"
#include "tensorflow/compiler/mlir/tfrt/translate/tfrt_compile_options.h"
#include "xla/status_macros.h"
#include "tensorflow/core/framework/function.pb.h"
#include "tensorflow/core/framework/metrics.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor.pb.h"
#include "tensorflow/core/lib/monitoring/counter.h"
#include "tensorflow/core/lib/monitoring/gauge.h"
#include "tensorflow/core/platform/env.h"
#include "tensorflow/core/platform/errors.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/mutex.h"
#include "tensorflow/core/platform/status.h"
#include "tensorflow/core/platform/statusor.h"
#include "tensorflow/core/protobuf/meta_graph.pb.h"
#include "tensorflow/core/protobuf/rewriter_config.pb.h"
#include "tensorflow/core/runtime_fallback/kernel/kernel_fallback_compat_request_state.h"
#include "tensorflow/core/tfrt/fallback/fallback_state.h"
#include "tensorflow/core/tfrt/fallback/op_kernel_runner.h"
#include "tensorflow/core/tfrt/graph_executor/export_mlir.h"
#include "tensorflow/core/tfrt/graph_executor/graph_execution_options.h"
#include "tensorflow/core/tfrt/graph_executor/graph_executor.h"
#include "tensorflow/core/tfrt/mlrt/bytecode/bytecode.h"
#include "tensorflow/core/tfrt/mlrt/bytecode/executable.h"
#include "tensorflow/core/tfrt/mlrt/interpreter/context.h"
#include "tensorflow/core/tfrt/mlrt/kernel/batch_kernel.h"
#include "tensorflow/core/tfrt/mlrt/kernel/kernel.h"
#include "tensorflow/core/tfrt/runtime/runtime.h"
#include "tensorflow/core/tfrt/saved_model/saved_model_util.h"
#include "tensorflow/core/tfrt/saved_model/utils/serialize_utils.h"
#include "tensorflow/core/tfrt/stubs/model_config_stub.h"
#include "tensorflow/core/tfrt/utils/utils.h"
#include "tsl/platform/errors.h"
#include "tsl/platform/statusor.h"
#include "tfrt/bef/bef_buffer.h"
#include "tfrt/bef_executor/bef_file.h"
#include "tfrt/core_runtime/core_runtime.h"
#include "tfrt/host_context/execution_context.h"
#include "tfrt/host_context/function.h"
#include "tfrt/host_context/host_context.h"
#include "tfrt/host_context/kernel_registry.h"
#include "tfrt/host_context/request_deadline_tracker.h"
#include "tfrt/host_context/resource_context.h"
#include "tfrt/metrics/common_metrics.h"
#include "tfrt/support/ref_count.h"
namespace tensorflow {
namespace tfrt_stub {
namespace {
constexpr absl::string_view kSignatureJoiningDelimiter = "+";
auto* lazy_loading_count = monitoring::Counter<3>::New(
"/tensorflow/tfrt/lazy_loading_count", "The total number of lazy loadings.",
"model_name", "model_version", "use_graph_executor");
auto* saved_model_import_time_seconds =
tensorflow::monitoring::Gauge<int64_t, 1>::New(
"/tensorflow/tfrt/saved_model/import_time",
"Record the MLIR import time for the savedmodel.", "model_name");
auto* saved_model_compile_time_seconds =
tensorflow::monitoring::Gauge<int64_t, 1>::New(
"/tensorflow/tfrt/saved_model/compile_time",
"Record the compilation time for the savedmodel.", "model_name");
auto* saved_model_init_time_seconds =
tensorflow::monitoring::Gauge<int64_t, 1>::New(
"/tensorflow/tfrt/saved_model/init_time",
"Record the initialization time for the savedmodel.", "model_name");
auto* saved_model_input_spec_validation_failure =
tensorflow::monitoring::Gauge<bool, 1>::New(
"/tensorflow/tfrt/saved_model/input_spec_validation_failure",
"Record the models that failed input spec validation.", "model_name");
tensorflow::Status RunBytecodeInitializers(
const GraphExecutionOptions& options,
const InitializersAndSignatures& initializers_and_signatures,
const mlrt::LoadedExecutable& loaded_executable,
tfrt::ResourceContext* resource_context, OpKernelRunnerTable* runner_table,
tfd::FallbackResourceArray* resource_array, FallbackState& fallback_state,
const bool provide_inputs) {
TF_ASSIGN_OR_RETURN(
auto request_info,
CreateRequestInfo(options, {},
options.runtime->work_queue(), resource_context,
nullptr, runner_table,
resource_array, fallback_state,
fallback_state.process_function_library_runtime()));
std::vector<tensorflow::Tensor> outputs;
if (auto function = loaded_executable.GetFunction("_tfrt_fallback_init")) {
TF_RETURN_IF_ERROR(RunMlrtFunction(
function, loaded_executable, request_info->tfrt_request_context,
*request_info->request_queue, {}, &outputs,
nullptr));
}
for (const auto& p : initializers_and_signatures.initializers) {
const auto& initializer_name = p.name;
std::vector<tensorflow::Tensor> outputs;
const std::vector<tensorflow::Tensor> empty_inputs;
const std::vector<tensorflow::Tensor>& initializer_inputs =
provide_inputs ? p.inputs : empty_inputs;
TF_RETURN_IF_ERROR(GraphExecutionRunOnFunction(
options, {}, initializer_name, {},
nullptr, &loaded_executable, initializer_inputs, &outputs,
resource_context,
nullptr, runner_table, resource_array,
*options.runtime, fallback_state,
fallback_state.process_function_library_runtime(),
nullptr,
std::nullopt));
DCHECK(outputs.empty());
}
if (auto function = loaded_executable.GetFunction("_tfrt_resource_init")) {
TF_RETURN_IF_ERROR(RunMlrtFunction(
function, loaded_executable, request_info->tfrt_request_context,
*request_info->request_queue, {}, &outputs,
nullptr));
}
return absl::OkStatus();
}
tensorflow::Status RunBefInitializers(
const GraphExecutionOptions& options,
const InitializersAndSignatures& initializers_and_signatures,
tfrt::BEFFile* bef_file, tfrt::ResourceContext* resource_context,
OpKernelRunnerTable* runner_table,
tfd::FallbackResourceArray* resource_array, FallbackState& fallback_state,
const bool provide_inputs) {
DCHECK(options.runtime);
TF_ASSIGN_OR_RETURN(
auto request_info,
CreateRequestInfo(options, {},
options.runtime->work_queue(), resource_context,
nullptr, runner_table,
resource_array, fallback_state,
fallback_state.process_function_library_runtime()));
tfrt::ExecutionContext exec_ctx(request_info->tfrt_request_context);
TF_RETURN_IF_ERROR(
RunRuntimeInitializer(exec_ctx, bef_file, "_tfrt_fallback_init"));
for (const auto& p : initializers_and_signatures.initializers) {
const auto& initializer_name = p.name;
auto* func = bef_file->GetFunction(initializer_name);
DCHECK(func);
std::vector<tensorflow::Tensor> outputs;
const std::vector<tensorflow::Tensor> empty_inputs;
const std::vector<tensorflow::Tensor>& initializer_inputs =
provide_inputs ? p.inputs : empty_inputs;
TF_RETURN_IF_ERROR(GraphExecutionRunOnFunction(
options, {}, initializer_name, {}, func,
nullptr, initializer_inputs, &outputs,
resource_context,
nullptr, runner_table, resource_array,
*options.runtime, fallback_state,
fallback_state.process_function_library_runtime(),
nullptr,
std::nullopt));
DCHECK(outputs.empty());
}
TF_RETURN_IF_ERROR(
RunRuntimeInitializer(exec_ctx, bef_file, "_tfrt_resource_init"));
return absl::OkStatus();
}
tensorflow::Status IsInputSpecsCorrect(
absl::string_view name, const internal::Signature& signature,
absl::Span<const tensorflow::Tensor> inputs) {
TF_RET_CHECK(signature.input_specs.size() == inputs.size())
<< "signature " << name
<< " input size is wrong, expected: " << signature.input_specs.size()
<< ", actual: " << inputs.size();
for (size_t i = 0; i < inputs.size(); ++i) {
const auto& expected_input_spec = signature.input_specs[i];
TF_RET_CHECK(expected_input_spec.dtype == inputs[i].dtype())
<< "signature " << name
<< " input dtype is wrong, expected: " << expected_input_spec.dtype
<< ", actual: " << inputs[i].dtype();
TF_RET_CHECK(expected_input_spec.shape.IsCompatibleWith(inputs[i].shape()))
<< "signature " << name
<< " input shape is wrong, expected : " << expected_input_spec.shape
<< ", actual: " << inputs[i].shape();
}
return absl::OkStatus();
}
tensorflow::Status CheckInputSpecs(
const tensorflow::SessionMetadata& model_metadata,
const SavedModel::RunOptions& run_options, absl::string_view signature_name,
const internal::Signature& signature,
absl::Span<const tensorflow::Tensor> input_tensors) {
if (!run_options.validate_input_specs &&
!run_options.validate_input_specs_dry_run) {
return absl::OkStatus();
}
auto status = IsInputSpecsCorrect(signature_name, signature, input_tensors);
if (!status.ok()) {
saved_model_input_spec_validation_failure
->GetCell(
absl::StrCat(model_metadata.name(), ":", model_metadata.version()))
->Set(true);
const auto error_string = absl::StrCat(
"model: ", model_metadata.name(),
", version: ", model_metadata.version(), ", error: ", status.message());
if (!run_options.validate_input_specs_dry_run) {
return tensorflow::errors::InvalidArgument(error_string);
}
LOG_EVERY_N_SEC(WARNING, 5)
<< "TFRT input specs validation failed, " << error_string;
}
return absl::OkStatus();
}
tensorflow::Status PreprocessSignature(
const tensorflow::SessionMetadata& model_metadata,
const SavedModel::RunOptions& run_options, absl::string_view signature_name,
const tensorflow::SignatureDef& signature_def,
const internal::Signature& signature,
absl::Span<const tensorflow::Tensor> input_tensors,
absl::flat_hash_set<std::string>* visited_feed_tensor_names,
std::vector<std::pair<std::string, tensorflow::Tensor>>& inputs,
std::vector<std::string>& output_tensor_names) {
const auto& input_names = signature.input_names;
TF_RETURN_IF_ERROR(CheckInputSpecs(model_metadata, run_options,
signature_name, signature, input_tensors));
TF_RET_CHECK(input_tensors.size() == signature_def.inputs().size())
<< "Incorrect input size for signature: " << signature_name
<< ": expected " << signature_def.inputs().size() << ", but got "
<< input_tensors.size();
DCHECK_EQ(input_names.size(), signature_def.inputs().size());
for (int i = 0; i < input_tensors.size(); ++i) {
const auto& tensor_info = signature_def.inputs().at(input_names[i]);
TF_RET_CHECK(tensor_info.encoding_case() == tensorflow::TensorInfo::kName)
<< "Only dense tensor is supported, but got encoding case "
<< tensor_info.encoding_case();
const auto& tensor_name = tensor_info.name();
if (visited_feed_tensor_names &&
!visited_feed_tensor_names->insert(tensor_name).second)
continue;
inputs.push_back(std::make_pair(tensor_name, input_tensors[i]));
}
for (const auto& output_key : signature.output_names) {
const auto& tensor_info = signature_def.outputs().at(output_key);
VLOG(1) << "Importing Signature Output: output_key = " << output_key
<< ", tensor_info = " << tensor_info.DebugString();
TF_RET_CHECK(tensor_info.encoding_case() == tensorflow::TensorInfo::kName)
<< "Only dense tensor is supported, but got encoding case "
<< tensor_info.encoding_case();
output_tensor_names.push_back(tensor_info.name());
}
return absl::OkStatus();
}
bool AotPackageExists(absl::string_view saved_model_dir) {
Env* env = Env::Default();
const std::string aot_package_path = GetAotPackagePath(saved_model_dir);
const std::string aot_mlir_path = GetMlirFilePath(aot_package_path);
const std::string aot_bef_path = GetBefFilePath(aot_package_path);
return env->FileExists(aot_package_path).ok() &&
env->FileExists(aot_mlir_path).ok() &&
env->FileExists(aot_bef_path).ok();
}
}
SavedModel::~SavedModel() = default;
tfrt::HostContext* SavedModel::GetHostContext() const {
return runtime().core_runtime()->GetHostContext();
}
namespace {
void GetSignaturesFromSignatureDef(
SignatureMap& signatures,
const google::protobuf::Map<std::string, tensorflow::SignatureDef>& signature_defs,
const SavedModel::Options& options) {
for (const auto& p : signature_defs) {
const std::string& signature_name = p.first;
const tensorflow::SignatureDef& signature_def = p.second;
DCHECK(signatures.find(signature_name) == signatures.end());
auto& signature = signatures[signature_name];
signature.input_names.reserve(signature_def.inputs().size());
signature.input_specs.reserve(signature_def.inputs().size());
for (const auto& p : signature_def.inputs()) {
const std::string& input_tensor_name = p.first;
const tensorflow::TensorInfo& tensor_info = p.second;
signature.input_names.push_back(input_tensor_name);
signature.input_specs.push_back(
TensorSpec(tensor_info.dtype(), tensor_info.tensor_shape()));
}
signature.input_devices = std::vector<std::string>(
signature_def.inputs().size(),
options.graph_execution_options.compile_options.default_device);
signature.output_names.reserve(signature_def.outputs().size());
signature.output_specs.reserve(signature_def.outputs().size());
for (const auto& p : signature_def.outputs()) {
const std::string& output_tensor_name = p.first;
const tensorflow::TensorInfo& tensor_info = p.second;
signature.output_names.push_back(output_tensor_name);
signature.output_specs.push_back(
TensorSpec(tensor_info.dtype(), tensor_info.tensor_shape()));
}
}
}
void GetDefaultInputValue(
const google::protobuf::Map<std::string, tensorflow::SignatureDef>& signature_defs,
ModelRuntimeContext& context, SignatureMap& signatures) {
bool load_from_signature_def = false;
for (const auto& [name, signature_def] : signature_defs) {
auto itr = signatures.find(name);
if (itr == signatures.end()) {
continue;
}
LOG(INFO) << "Model signature identified for default inputs";
if (signature_def.defaults().empty()) continue;
LOG(INFO) << "Loading default inputs for signature: " << name
<< " from Signature def";
load_from_signature_def = true;
signatures[name].default_inputs = signature_def.defaults();
}
if (load_from_signature_def) return;
GetDefaultInputsFromModelConfig(context, signatures);
}
void UpdateCompileOptions(SavedModel::Options& options) {
if (options.graph_execution_options.enable_tfrt_gpu) {
options.graph_execution_options.compile_options.decompose_resource_ops =
false;
}
options.graph_execution_options.compile_options
.fuse_get_resource_ops_in_hoist | #include <string>
#include <vector>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "tensorflow/cc/saved_model/loader.h"
#include "tensorflow/core/lib/core/status_test_util.h"
#include "tensorflow/core/platform/resource_loader.h"
#include "tensorflow/core/tfrt/saved_model/saved_model_testutil.h"
namespace tensorflow {
namespace tfrt_stub {
namespace {
TEST(SavedModelTest, BasicError) {
std::string saved_model_dir = tensorflow::GetDataDependencyFilepath(
"tensorflow/core/runtime_fallback/test/saved_model/basic_v1");
TFRTSavedModelTest test(saved_model_dir);
std::vector<tensorflow::Tensor> inputs;
inputs.push_back(
CreateTfTensor<int32_t>({1, 3}, {1, 1, 1}));
std::vector<tensorflow::Tensor> outputs;
EXPECT_FALSE(
test.GetSavedModel()->Run({}, "serving_default", inputs, &outputs).ok());
}
}
}
} |
384 | #ifndef TENSORSTORE_PROTO_ARRAY_H_
#define TENSORSTORE_PROTO_ARRAY_H_
#include "absl/status/status.h"
#include "tensorstore/array.h"
#include "tensorstore/index.h"
#include "tensorstore/proto/array.pb.h"
#include "tensorstore/strided_layout.h"
#include "tensorstore/util/result.h"
namespace tensorstore {
void EncodeToProtoImpl(::tensorstore::proto::Array& proto,
OffsetArrayView<const void> array);
Result<SharedArray<void, dynamic_rank, offset_origin>> ParseArrayFromProto(
const ::tensorstore::proto::Array& proto,
ArrayOriginKind origin_kind = offset_origin,
DimensionIndex rank_constraint = dynamic_rank);
template <typename Element, DimensionIndex Rank, ArrayOriginKind OriginKind,
ContainerKind LayoutCKind>
void EncodeToProto(
::tensorstore::proto::Array& proto,
const Array<Shared<Element>, Rank, OriginKind, LayoutCKind>& value) {
EncodeToProtoImpl(proto, value);
}
}
#endif
#include "tensorstore/proto/array.h"
#include <algorithm>
#include <array>
#include <cstddef>
#include <cstdint>
#include <limits>
#include <string>
#include <type_traits>
#include "absl/status/status.h"
#include "riegeli/bytes/string_reader.h"
#include "riegeli/bytes/string_writer.h"
#include "tensorstore/array.h"
#include "tensorstore/contiguous_layout.h"
#include "tensorstore/data_type.h"
#include "tensorstore/index.h"
#include "tensorstore/index_interval.h"
#include "tensorstore/internal/elementwise_function.h"
#include "tensorstore/internal/integer_overflow.h"
#include "tensorstore/internal/unaligned_data_type_functions.h"
#include "tensorstore/proto/array.pb.h"
#include "tensorstore/rank.h"
#include "tensorstore/strided_layout.h"
#include "tensorstore/util/dimension_set.h"
#include "tensorstore/util/iterate.h"
#include "tensorstore/util/result.h"
#include "tensorstore/util/str_cat.h"
namespace tensorstore {
namespace {
struct WriteProtoImpl {
tensorstore::proto::Array& proto;
void operator()(const double* item, void*) { proto.add_double_data(*item); }
void operator()(const float* item, void*) { proto.add_float_data(*item); }
void operator()(const int16_t* item, void*) { proto.add_int_data(*item); }
void operator()(const int32_t* item, void*) { proto.add_int_data(*item); }
void operator()(const int64_t* item, void*) { proto.add_int_data(*item); }
void operator()(const uint16_t* item, void*) { proto.add_uint_data(*item); }
void operator()(const uint32_t* item, void*) { proto.add_uint_data(*item); }
void operator()(const uint64_t* item, void*) { proto.add_uint_data(*item); }
};
struct ReadProtoImpl {
const tensorstore::proto::Array& proto;
size_t index = 0;
size_t error_count = 0;
void operator()(double* item, void*) { *item = proto.double_data(index++); }
void operator()(float* item, void*) { *item = proto.float_data(index++); }
void operator()(int16_t* item, void*) {
auto i = proto.int_data(index++);
*item = static_cast<int16_t>(i);
if (i > std::numeric_limits<int16_t>::max() ||
i < std::numeric_limits<int16_t>::min()) {
error_count++;
}
}
void operator()(int32_t* item, void*) {
auto i = proto.int_data(index++);
*item = static_cast<int32_t>(i);
if (i > std::numeric_limits<int32_t>::max() ||
i < std::numeric_limits<int32_t>::min()) {
error_count++;
}
}
void operator()(int64_t* item, void*) { *item = proto.int_data(index++); }
void operator()(uint16_t* item, void*) {
auto i = proto.uint_data(index++);
*item = static_cast<uint16_t>(i);
if (i > std::numeric_limits<uint16_t>::max()) {
error_count++;
}
}
void operator()(uint32_t* item, void*) {
auto i = proto.uint_data(index++);
*item = static_cast<uint32_t>(i);
if (i > std::numeric_limits<uint32_t>::max()) {
error_count++;
}
}
void operator()(uint64_t* item, void*) { *item = proto.uint_data(index++); }
};
struct ProtoArrayDataTypeFunctions {
const internal::ElementwiseFunction<1, void*>* write_fn = nullptr;
const internal::ElementwiseFunction<1, void*>* read_fn = nullptr;
};
const std::array<ProtoArrayDataTypeFunctions, kNumDataTypeIds> kProtoFunctions =
MapCanonicalDataTypes([](auto dtype) {
using T = typename decltype(dtype)::Element;
ProtoArrayDataTypeFunctions functions;
if constexpr (std::is_invocable_v<ReadProtoImpl, T*, void*>) {
functions.write_fn =
internal::SimpleElementwiseFunction<WriteProtoImpl(const T),
void*>();
functions.read_fn =
internal::SimpleElementwiseFunction<ReadProtoImpl(T), void*>();
}
return functions;
});
}
void EncodeToProtoImpl(::tensorstore::proto::Array& proto,
OffsetArrayView<const void> array) {
const auto dtype = array.dtype();
proto.set_dtype(std::string(dtype.name()));
{
bool all_zero = true;
for (Index x : array.origin()) {
proto.add_origin(x);
all_zero &= (x == 0);
}
if (all_zero) proto.clear_origin();
}
for (Index x : array.shape()) {
proto.add_shape(x);
}
{
DimensionSet zero_byte_strides(false);
for (DimensionIndex i = 0; i < array.rank(); i++) {
zero_byte_strides[i] =
(array.byte_strides()[i] == 0 && array.shape()[i] != 1);
}
if (zero_byte_strides) {
proto.set_zero_byte_strides_bitset(zero_byte_strides.to_uint());
}
}
const size_t index = static_cast<size_t>(dtype.id());
if (kProtoFunctions[index].write_fn) {
if (dtype.id() == DataTypeIdOf<int16_t> ||
dtype.id() == DataTypeIdOf<int32_t> ||
dtype.id() == DataTypeIdOf<int64_t>) {
proto.mutable_int_data()->Reserve(array.num_elements());
} else if (dtype.id() == DataTypeIdOf<uint16_t> ||
dtype.id() == DataTypeIdOf<uint32_t> ||
dtype.id() == DataTypeIdOf<uint64_t>) {
proto.mutable_uint_data()->Reserve(array.num_elements());
} else if (dtype.id() == DataTypeIdOf<double>) {
proto.mutable_double_data()->Reserve(array.num_elements());
} else if (dtype.id() == DataTypeIdOf<float>) {
proto.mutable_float_data()->Reserve(array.num_elements());
}
WriteProtoImpl impl{proto};
internal::IterateOverArrays({kProtoFunctions[index].write_fn, &impl},
nullptr,
{c_order, skip_repeated_elements}, array);
} else {
proto.mutable_void_data()->reserve(dtype.size() * array.num_elements());
riegeli::StringWriter writer(proto.mutable_void_data());
internal::IterateOverArrays(
{&internal::kUnalignedDataTypeFunctions[index].write_native_endian,
&writer},
nullptr, {c_order, skip_repeated_elements}, array);
writer.Close();
}
}
Result<SharedArray<void, dynamic_rank, offset_origin>> ParseArrayFromProto(
const ::tensorstore::proto::Array& proto, ArrayOriginKind origin_kind,
DimensionIndex rank_constraint) {
SharedArray<void, dynamic_rank, offset_origin> array;
DataType dtype = GetDataType(proto.dtype());
if (!dtype.valid()) {
return absl::DataLossError(
"Cannot deserialize array with unspecified data type");
}
const size_t rank = proto.shape_size();
if (rank_constraint != dynamic_rank && rank != rank_constraint) {
return absl::InvalidArgumentError("Proto array rank mismatch");
}
if (rank > kMaxRank) {
return absl::InvalidArgumentError("Proto rank exceeds maximum rank");
}
array.layout().set_rank(rank);
std::copy(proto.shape().begin(), proto.shape().end(),
array.layout().shape().begin());
std::fill(array.layout().origin().begin(), array.layout().origin().end(),
Index(0));
if (proto.origin_size() > 0 &&
std::any_of(proto.origin().begin(), proto.origin().end(),
[](auto x) { return x != 0; })) {
if (origin_kind == zero_origin) {
return absl::InvalidArgumentError(
"Proto zero_origin array has non-zero origin");
}
if (proto.origin_size() != rank) {
return absl::InvalidArgumentError("Proto origin/rank mismatch");
}
std::copy(proto.origin().begin(), proto.origin().end(),
array.layout().origin().begin());
}
Index num_elements = 1;
{
DimensionSet zero_byte_strides =
(proto.has_zero_byte_strides_bitset())
? DimensionSet::FromUint(proto.zero_byte_strides_bitset())
: DimensionSet(false);
for (DimensionIndex i = rank - 1; i >= 0; --i) {
if (!IndexInterval::ValidSized(array.origin()[i], array.shape()[i])) {
return absl::InvalidArgumentError(tensorstore::StrCat(
"Proto origin and shape of {", array.origin()[i], ", ",
array.shape()[i],
"} do not specify a valid IndexInterval for rank ", i));
}
if (zero_byte_strides[i]) {
array.layout().byte_strides()[i] = 0;
} else {
array.layout().byte_strides()[i] = 1;
if (internal::MulOverflow(num_elements, array.shape()[i],
&num_elements)) {
return absl::DataLossError(
tensorstore::StrCat("Invalid array shape ", array.shape()));
}
}
}
}
array.element_pointer() = tensorstore::AllocateArrayElementsLike<void>(
array.layout(), array.byte_strides().data(),
{c_order, skip_repeated_elements}, default_init, dtype);
const size_t index = static_cast<size_t>(dtype.id());
if (kProtoFunctions[index].read_fn && proto.void_data().empty()) {
if ((dtype.id() == DataTypeIdOf<int16_t> ||
dtype.id() == DataTypeIdOf<int32_t> ||
dtype.id() == DataTypeIdOf<int64_t>)&&proto.int_data_size() !=
num_elements) {
return absl::DataLossError("proto int_data incomplete");
}
if ((dtype.id() == DataTypeIdOf<uint16_t> ||
dtype.id() == DataTypeIdOf<uint32_t> ||
dtype.id() == DataTypeIdOf<uint64_t>)&&proto.uint_data_size() !=
num_elements) {
return absl::DataLossError("proto uint_data incomplete");
}
if (dtype.id() == DataTypeIdOf<double> &&
proto.double_data_size() != num_elements) {
return absl::DataLossError("proto double_data incomplete");
}
if (dtype.id() == DataTypeIdOf<float> &&
proto.float_data_size() != num_elements) {
return absl::DataLossError("proto float_data incomplete");
}
ReadProtoImpl impl{proto};
internal::IterateOverArrays({kProtoFunctions[index].read_fn, &impl},
nullptr,
{c_order, skip_repeated_elements}, array);
if (impl.error_count > 0) {
return absl::DataLossError("Array element truncated");
}
} else {
riegeli::StringReader reader(proto.void_data());
internal::IterateOverArrays(
{&internal::kUnalignedDataTypeFunctions[index].read_native_endian,
&reader},
nullptr, {c_order, skip_repeated_elements}, array);
if (!reader.VerifyEndAndClose()) return reader.status();
}
return array;
}
} | #include "tensorstore/proto/array.h"
#include <memory>
#include <random>
#include <string>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "absl/status/status.h"
#include "tensorstore/array.h"
#include "tensorstore/contiguous_layout.h"
#include "tensorstore/data_type.h"
#include "tensorstore/index.h"
#include "tensorstore/index_space/index_transform_testutil.h"
#include "tensorstore/internal/data_type_random_generator.h"
#include "tensorstore/internal/testing/random_seed.h"
#include "tensorstore/proto/array.pb.h"
#include "tensorstore/proto/protobuf_matchers.h"
#include "tensorstore/strided_layout.h"
#include "tensorstore/util/status_testutil.h"
namespace {
using ::protobuf_matchers::EqualsProto;
using ::tensorstore::Index;
using ::tensorstore::kInfIndex;
using ::tensorstore::MatchesStatus;
using ::tensorstore::ParseArrayFromProto;
using ::tensorstore::StridedLayout;
template <typename Proto>
Proto ParseProtoOrDie(const std::string& asciipb) {
return protobuf_matchers::internal::MakePartialProtoFromAscii<Proto>(asciipb);
}
template <typename T>
auto DoEncode(const T& array) {
::tensorstore::proto::Array proto;
::tensorstore::EncodeToProto(proto, array);
return proto;
}
TEST(ArrayProtoTest, Basic) {
auto array = tensorstore::MakeArray<Index>({{{1, 0, 2, 2}, {4, 5, 6, 7}}});
auto proto = ParseProtoOrDie<::tensorstore::proto::Array>(R"pb(
dtype: "int64"
shape: [ 1, 2, 4 ]
int_data: [ 1, 0, 2, 2, 4, 5, 6, 7 ]
)pb");
EXPECT_THAT(DoEncode(array), EqualsProto(proto));
TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto copy, ParseArrayFromProto(proto));
ASSERT_TRUE(copy.valid());
EXPECT_EQ(copy.layout(), array.layout());
EXPECT_THAT(copy, testing::Eq(array));
}
TEST(ArrayProtoTest, BasicVoidData) {
auto array =
tensorstore::MakeOffsetArray<bool>({3, 1, -2}, {{{true}}, {{false}}});
auto proto = ParseProtoOrDie<::tensorstore::proto::Array>(R"pb(
dtype: "bool"
shape: [ 2, 1, 1 ]
origin: [ 3, 1, -2 ]
void_data: "\x01\x00"
)pb");
EXPECT_THAT(DoEncode(array), EqualsProto(proto));
TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto copy, ParseArrayFromProto(proto));
ASSERT_TRUE(copy.valid());
EXPECT_EQ(copy.layout(), array.layout());
EXPECT_THAT(copy, testing::Eq(array));
}
TEST(ArrayProtoTest, DecodeRank0) {
auto proto = ParseProtoOrDie<::tensorstore::proto::Array>(R"pb(
dtype: "int64"
int_data: [ 3 ]
)pb");
TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto copy, ParseArrayFromProto(proto));
EXPECT_TRUE(copy.valid());
EXPECT_THAT(copy.rank(), testing::Eq(0));
}
TEST(ArrayProtoTest, ZeroStrides) {
int data[] = {1, 2, 3, 4, 5, 6};
tensorstore::SharedArray<int> array(
std::shared_ptr<int>(std::shared_ptr<void>(), &data[0]),
tensorstore::StridedLayout<>({kInfIndex + 1, 2, 3, kInfIndex + 1},
{0, 3 * sizeof(int), sizeof(int), 0}));
auto proto = ParseProtoOrDie<::tensorstore::proto::Array>(R"pb(
dtype: "int32"
shape: [ 4611686018427387904, 2, 3, 4611686018427387904 ]
zero_byte_strides_bitset: 9
int_data: [ 1, 2, 3, 4, 5, 6 ]
)pb");
EXPECT_THAT(DoEncode(array), EqualsProto(proto));
TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto copy, ParseArrayFromProto(proto));
ASSERT_TRUE(copy.valid());
ASSERT_EQ(copy.layout(), array.layout());
EXPECT_EQ(array, copy);
}
TEST(ArrayProtoTest, Errors) {
EXPECT_THAT(
ParseArrayFromProto(ParseProtoOrDie<::tensorstore::proto::Array>(R"pb(
dtype: "foo"
int_data: [ 3 ]
)pb")),
MatchesStatus(absl::StatusCode::kDataLoss));
EXPECT_THAT(
ParseArrayFromProto(ParseProtoOrDie<::tensorstore::proto::Array>(R"pb(
dtype: "int32"
int_data: [ 3 ]
)pb"),
tensorstore::offset_origin, 2),
MatchesStatus(absl::StatusCode::kInvalidArgument));
EXPECT_THAT(
ParseArrayFromProto(ParseProtoOrDie<::tensorstore::proto::Array>(R"pb(
dtype: "int32"
shape: [
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
]
)pb")),
MatchesStatus(absl::StatusCode::kInvalidArgument));
EXPECT_THAT(
ParseArrayFromProto(ParseProtoOrDie<::tensorstore::proto::Array>(R"pb(
dtype: "int32"
shape: [ 1, 2, 3 ]
origin: [ 1, 2, 3 ]
)pb"),
tensorstore::zero_origin),
MatchesStatus(absl::StatusCode::kInvalidArgument));
EXPECT_THAT(
ParseArrayFromProto(ParseProtoOrDie<::tensorstore::proto::Array>(R"pb(
dtype: "int32"
shape: [ 1, 2, 3 ]
origin: [ 1, 2 ]
)pb")),
MatchesStatus(absl::StatusCode::kInvalidArgument));
EXPECT_THAT(
ParseArrayFromProto(ParseProtoOrDie<::tensorstore::proto::Array>(R"pb(
dtype: "int32"
shape: [ 1, -2, 3 ]
)pb")),
MatchesStatus(absl::StatusCode::kInvalidArgument));
EXPECT_THAT(
ParseArrayFromProto(ParseProtoOrDie<::tensorstore::proto::Array>(R"pb(
dtype: "int32"
shape: [ 2147483647, 2147483647, 2147483647 ]
)pb")),
MatchesStatus(absl::StatusCode::kDataLoss));
EXPECT_THAT(
ParseArrayFromProto(ParseProtoOrDie<::tensorstore::proto::Array>(R"pb(
dtype: "int64"
int_data: [ 3, 4 ]
)pb")),
MatchesStatus(absl::StatusCode::kDataLoss));
EXPECT_THAT(
ParseArrayFromProto(ParseProtoOrDie<::tensorstore::proto::Array>(R"pb(
dtype: "int64"
shape: 2
int_data: [ 3 ]
)pb")),
MatchesStatus(absl::StatusCode::kDataLoss));
EXPECT_THAT(
ParseArrayFromProto(ParseProtoOrDie<::tensorstore::proto::Array>(R"pb(
dtype: "uint64"
shape: 2
)pb")),
MatchesStatus(absl::StatusCode::kDataLoss));
EXPECT_THAT(
ParseArrayFromProto(ParseProtoOrDie<::tensorstore::proto::Array>(R"pb(
dtype: "double"
shape: 2
)pb")),
MatchesStatus(absl::StatusCode::kDataLoss));
EXPECT_THAT(
ParseArrayFromProto(ParseProtoOrDie<::tensorstore::proto::Array>(R"pb(
dtype: "float"
shape: 2
)pb")),
MatchesStatus(absl::StatusCode::kDataLoss));
}
class RandomArrayProtoTest
: public ::testing::TestWithParam<tensorstore::DataType> {};
INSTANTIATE_TEST_SUITE_P(DataTypes, RandomArrayProtoTest,
::testing::ValuesIn(tensorstore::kDataTypes));
TEST_P(RandomArrayProtoTest, COrder) {
auto dtype = GetParam();
for (int iteration = 0; iteration < 100; ++iteration) {
std::minstd_rand gen{tensorstore::internal_testing::GetRandomSeedForTest(
"TENSORSTORE_PROTO_ARRAY_TEST_SEED")};
auto box = tensorstore::internal::MakeRandomBox(gen);
auto array = tensorstore::internal::MakeRandomArray(gen, box, dtype,
tensorstore::c_order);
auto proto = DoEncode(array);
TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto copy, ParseArrayFromProto(proto));
EXPECT_THAT(copy, testing::Eq(array));
}
}
TEST_P(RandomArrayProtoTest, FOrder) {
auto dtype = GetParam();
for (int iteration = 0; iteration < 100; ++iteration) {
std::minstd_rand gen{tensorstore::internal_testing::GetRandomSeedForTest(
"TENSORSTORE_PROTO_ARRAY_TEST_SEED")};
auto box = tensorstore::internal::MakeRandomBox(gen);
auto array = tensorstore::internal::MakeRandomArray(
gen, box, dtype, tensorstore::fortran_order);
auto proto = DoEncode(array);
TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto copy, ParseArrayFromProto(proto));
EXPECT_THAT(copy, testing::Eq(array));
}
}
} |
385 | #ifndef TENSORSTORE_PROTO_PROTO_BINDER_H_
#define TENSORSTORE_PROTO_PROTO_BINDER_H_
#include <type_traits>
#include "absl/status/status.h"
#include "google/protobuf/message.h"
#include "tensorstore/internal/json_binding/json_binding.h"
#include "tensorstore/json_serialization_options_base.h"
namespace tensorstore {
namespace internal_json_binding {
struct JsonProtoBinderBase {
absl::Status operator()(std::true_type ,
const NoOptions& options, google::protobuf::Message* obj,
::nlohmann::json* j) const;
absl::Status operator()(std::false_type ,
const NoOptions& options, const google::protobuf::Message* obj,
::nlohmann::json* j) const;
};
struct AsciiProtoBinderBase {
absl::Status operator()(std::true_type ,
const NoOptions& options, google::protobuf::Message* obj,
::nlohmann::json* j) const;
absl::Status operator()(std::false_type ,
const NoOptions& options, const google::protobuf::Message* obj,
::nlohmann::json* j) const;
};
template <typename MessageType>
struct JsonProtoBinder : private JsonProtoBinderBase {
inline absl::Status operator()(std::true_type ,
const NoOptions& options, MessageType* obj,
::nlohmann::json* j) const {
return JsonProtoBinderBase::operator()(std::true_type{}, options, obj, j);
}
inline absl::Status operator()(std::false_type ,
const NoOptions& options,
const MessageType* obj,
::nlohmann::json* j) const {
return JsonProtoBinderBase::operator()(std::false_type{}, options, obj, j);
}
};
template <typename MessageType>
struct AsciiProtoBinder : private AsciiProtoBinderBase {
inline absl::Status operator()(std::true_type ,
const NoOptions& options, MessageType* obj,
::nlohmann::json* j) const {
return AsciiProtoBinderBase::operator()(std::true_type{}, options, obj, j);
}
inline absl::Status operator()(std::false_type ,
const NoOptions& options,
const MessageType* obj,
::nlohmann::json* j) const {
return AsciiProtoBinderBase::operator()(std::false_type{}, options, obj, j);
}
};
}
}
#endif
#include "tensorstore/proto/proto_binder.h"
#include <string>
#include <type_traits>
#include <utility>
#include "absl/status/status.h"
#include <nlohmann/json.hpp>
#include "google/protobuf/descriptor.h"
#include "google/protobuf/message.h"
#include "google/protobuf/text_format.h"
#include "google/protobuf/util/json_util.h"
#include "tensorstore/internal/json/value_as.h"
#include "tensorstore/internal/json_binding/json_binding.h"
#include "tensorstore/json_serialization_options_base.h"
#include "tensorstore/proto/proto_util.h"
#include "tensorstore/util/str_cat.h"
namespace tensorstore {
namespace internal_json_binding {
absl::Status JsonProtoBinderBase::operator()(std::true_type ,
const NoOptions& options,
google::protobuf::Message* obj,
::nlohmann::json* j) const {
if (!j->template get_ptr<::nlohmann::json::object_t*>()) {
return internal_json::ExpectedError(*j, "object");
}
std::string json_ascii = j->dump();
auto status = google::protobuf::util::JsonStringToMessage(json_ascii, obj);
if (status.ok()) {
return absl::OkStatus();
}
return absl::InvalidArgumentError(tensorstore::StrCat(
"Expected JSON protocol buffer ", obj->GetDescriptor()->name(),
" object, but received ", j->dump(), " with error ",
std::string_view(status.message().data(), status.message().size())));
}
absl::Status JsonProtoBinderBase::operator()(std::false_type ,
const NoOptions& options,
const google::protobuf::Message* obj,
::nlohmann::json* j) const {
std::string json_ascii;
auto status = google::protobuf::util::MessageToJsonString(*obj, &json_ascii);
if (!status.ok()) {
return absl::InternalError(
std::string_view(status.message().data(), status.message().size()));
}
auto j_parse = ::nlohmann::json::parse(json_ascii, nullptr, false);
if (j_parse.template get_ptr<::nlohmann::json::object_t*>()) {
*j = std::move(j_parse);
return absl::OkStatus();
}
return absl::InternalError("Failed to serialize field as JSON proto");
}
absl::Status AsciiProtoBinderBase::operator()(std::true_type,
const NoOptions& options,
google::protobuf::Message* obj,
::nlohmann::json* j) const {
auto* str = j->template get_ptr<const std::string*>();
if (!str) {
return internal_json::ExpectedError(*j, "string");
}
if (TryParseTextProto(*str, obj)) {
return absl::OkStatus();
}
return absl::InvalidArgumentError(tensorstore::StrCat(
"Expected ASCII protocol buffer ", obj->GetDescriptor()->name(),
" object, but received ", *str));
}
absl::Status AsciiProtoBinderBase::operator()(std::false_type,
const NoOptions& options,
const google::protobuf::Message* obj,
::nlohmann::json* j) const {
std::string obj_text;
google::protobuf::TextFormat::PrintToString(*obj, &obj_text);
*j = obj_text;
return absl::OkStatus();
}
}
} | #include "tensorstore/proto/proto_binder.h"
#include <string>
#include <type_traits>
#include <gtest/gtest.h>
#include "absl/status/status.h"
#include <nlohmann/json_fwd.hpp>
#include "tensorstore/json_serialization_options.h"
#include "tensorstore/proto/array.pb.h"
#include "tensorstore/proto/protobuf_matchers.h"
namespace {
using ::protobuf_matchers::EqualsProto;
using ::tensorstore::JsonSerializationOptions;
using ::tensorstore::internal_json_binding::AsciiProtoBinder;
using ::tensorstore::internal_json_binding::JsonProtoBinder;
static inline constexpr JsonProtoBinder<::tensorstore::proto::Array>
ArrayJsonBinder = {};
static inline constexpr AsciiProtoBinder<::tensorstore::proto::Array>
ArrayAsciiBinder = {};
constexpr const char kProto[] = R"(dtype: "int64"
shape: 1
shape: 2
shape: 4
int_data: 1
int_data: 0
int_data: 2
int_data: 2
int_data: 4
int_data: 5
int_data: 6
int_data: 7
)";
TEST(ProtoBinderTest, Ascii) {
JsonSerializationOptions options;
::tensorstore::proto::Array proto;
::nlohmann::json j = std::string(kProto);
EXPECT_TRUE(ArrayAsciiBinder(std::true_type{}, options, &proto, &j).ok());
EXPECT_THAT(proto, EqualsProto(kProto));
::nlohmann::json out;
EXPECT_TRUE(ArrayAsciiBinder(std::false_type{}, options, &proto, &out).ok());
ASSERT_TRUE(out.get_ptr<const std::string*>());
EXPECT_EQ(*out.get_ptr<const std::string*>(), kProto);
}
TEST(ProtoBinderTest, Json) {
JsonSerializationOptions options;
::tensorstore::proto::Array proto;
::nlohmann::json j = ::nlohmann::json{{"dtype", "int64"},
{"shape", {1, 2, 4}},
{"int_data", {1, 0, 2, 2, 4, 5, 6, 7}}};
EXPECT_TRUE(ArrayJsonBinder(std::true_type{}, options, &proto, &j).ok());
EXPECT_THAT(proto, EqualsProto(kProto));
::nlohmann::json out;
EXPECT_TRUE(ArrayJsonBinder(std::false_type{}, options, &proto, &out).ok());
::nlohmann::json expected{
{"dtype", "int64"},
{"shape", {"1", "2", "4"}},
{"intData", {"1", "0", "2", "2", "4", "5", "6", "7"}}};
EXPECT_EQ(out, expected);
}
} |
386 | #ifndef QUICHE_QUIC_TEST_TOOLS_SIMULATOR_QUIC_ENDPOINT_H_
#define QUICHE_QUIC_TEST_TOOLS_SIMULATOR_QUIC_ENDPOINT_H_
#include "absl/strings/string_view.h"
#include "quiche/quic/core/crypto/null_decrypter.h"
#include "quiche/quic/core/crypto/null_encrypter.h"
#include "quiche/quic/core/quic_connection.h"
#include "quiche/quic/core/quic_packet_writer.h"
#include "quiche/quic/core/quic_packets.h"
#include "quiche/quic/core/quic_stream_frame_data_producer.h"
#include "quiche/quic/core/quic_trace_visitor.h"
#include "quiche/quic/test_tools/simple_session_notifier.h"
#include "quiche/quic/test_tools/simulator/link.h"
#include "quiche/quic/test_tools/simulator/queue.h"
#include "quiche/quic/test_tools/simulator/quic_endpoint_base.h"
namespace quic {
namespace simulator {
class QuicEndpoint : public QuicEndpointBase,
public QuicConnectionVisitorInterface,
public SessionNotifierInterface {
public:
QuicEndpoint(Simulator* simulator, std::string name, std::string peer_name,
Perspective perspective, QuicConnectionId connection_id);
QuicByteCount bytes_to_transfer() const;
QuicByteCount bytes_transferred() const;
QuicByteCount bytes_received() const;
bool wrong_data_received() const { return wrong_data_received_; }
void AddBytesToTransfer(QuicByteCount bytes);
void OnStreamFrame(const QuicStreamFrame& frame) override;
void OnCryptoFrame(const QuicCryptoFrame& frame) override;
void OnCanWrite() override;
bool WillingAndAbleToWrite() const override;
bool ShouldKeepConnectionAlive() const override;
std::string GetStreamsInfoForLogging() const override { return ""; }
void OnWindowUpdateFrame(const QuicWindowUpdateFrame& ) override {}
void OnBlockedFrame(const QuicBlockedFrame& ) override {}
void OnRstStream(const QuicRstStreamFrame& ) override {}
void OnGoAway(const QuicGoAwayFrame& ) override {}
void OnMessageReceived(absl::string_view ) override {}
void OnHandshakeDoneReceived() override {}
void OnNewTokenReceived(absl::string_view ) override {}
void OnConnectionClosed(const QuicConnectionCloseFrame& ,
ConnectionCloseSource ) override {}
void OnWriteBlocked() override {}
void OnSuccessfulVersionNegotiation(
const ParsedQuicVersion& ) override {}
void OnPacketReceived(const QuicSocketAddress& ,
const QuicSocketAddress& ,
bool ) override {}
void OnCongestionWindowChange(QuicTime ) override {}
void OnConnectionMigration(AddressChangeType ) override {}
void OnPathDegrading() override {}
void OnForwardProgressMadeAfterPathDegrading() override {}
void OnAckNeedsRetransmittableFrame() override {}
void SendAckFrequency(const QuicAckFrequencyFrame& ) override {}
void SendNewConnectionId(const QuicNewConnectionIdFrame& ) override {
}
void SendRetireConnectionId(uint64_t ) override {}
bool MaybeReserveConnectionId(
const QuicConnectionId& ) override {
return true;
}
void OnServerConnectionIdRetired(
const QuicConnectionId& ) override {}
bool AllowSelfAddressChange() const override;
HandshakeState GetHandshakeState() const override;
bool OnMaxStreamsFrame(const QuicMaxStreamsFrame& ) override {
return true;
}
bool OnStreamsBlockedFrame(
const QuicStreamsBlockedFrame& ) override {
return true;
}
void OnStopSendingFrame(const QuicStopSendingFrame& ) override {}
void OnPacketDecrypted(EncryptionLevel ) override {}
void OnOneRttPacketAcknowledged() override {}
void OnHandshakePacketSent() override {}
void OnKeyUpdate(KeyUpdateReason ) override {}
std::unique_ptr<QuicDecrypter> AdvanceKeysAndCreateCurrentOneRttDecrypter()
override {
return nullptr;
}
std::unique_ptr<QuicEncrypter> CreateCurrentOneRttEncrypter() override {
return nullptr;
}
void BeforeConnectionCloseSent() override {}
bool ValidateToken(absl::string_view ) override { return true; }
bool MaybeSendAddressToken() override { return false; }
void CreateContextForMultiPortPath(
std::unique_ptr<MultiPortPathContextObserver> )
override {}
void MigrateToMultiPortPath(
std::unique_ptr<QuicPathValidationContext> ) override {}
void OnServerPreferredAddressAvailable(
const QuicSocketAddress& ) override {}
void MaybeBundleOpportunistically() override {}
QuicByteCount GetFlowControlSendWindowSize(QuicStreamId ) override {
return std::numeric_limits<QuicByteCount>::max();
}
bool OnFrameAcked(const QuicFrame& frame, QuicTime::Delta ack_delay_time,
QuicTime receive_timestamp) override;
void OnStreamFrameRetransmitted(const QuicStreamFrame& ) override {}
void OnFrameLost(const QuicFrame& frame) override;
bool RetransmitFrames(const QuicFrames& frames,
TransmissionType type) override;
bool IsFrameOutstanding(const QuicFrame& frame) const override;
bool HasUnackedCryptoData() const override;
bool HasUnackedStreamData() const override;
private:
class DataProducer : public QuicStreamFrameDataProducer {
public:
WriteStreamDataResult WriteStreamData(QuicStreamId id,
QuicStreamOffset offset,
QuicByteCount data_length,
QuicDataWriter* writer) override;
bool WriteCryptoData(EncryptionLevel level, QuicStreamOffset offset,
QuicByteCount data_length,
QuicDataWriter* writer) override;
};
std::unique_ptr<QuicConnection> CreateConnection(
Simulator* simulator, std::string name, std::string peer_name,
Perspective perspective, QuicConnectionId connection_id);
void WriteStreamData();
DataProducer producer_;
QuicByteCount bytes_to_transfer_;
QuicByteCount bytes_transferred_;
bool wrong_data_received_;
QuicIntervalSet<QuicStreamOffset> offsets_received_;
std::unique_ptr<test::SimpleSessionNotifier> notifier_;
};
}
}
#endif
#include "quiche/quic/test_tools/simulator/quic_endpoint.h"
#include <algorithm>
#include <memory>
#include <string>
#include <utility>
#include "quiche/quic/core/crypto/crypto_handshake_message.h"
#include "quiche/quic/core/crypto/crypto_protocol.h"
#include "quiche/quic/core/quic_data_writer.h"
#include "quiche/quic/platform/api/quic_test_output.h"
#include "quiche/quic/test_tools/quic_config_peer.h"
#include "quiche/quic/test_tools/quic_connection_peer.h"
#include "quiche/quic/test_tools/quic_test_utils.h"
#include "quiche/quic/test_tools/simulator/simulator.h"
namespace quic {
namespace simulator {
const QuicStreamId kDataStream = 3;
const QuicByteCount kWriteChunkSize = 128 * 1024;
const char kStreamDataContents = 'Q';
QuicEndpoint::QuicEndpoint(Simulator* simulator, std::string name,
std::string peer_name, Perspective perspective,
QuicConnectionId connection_id)
: QuicEndpointBase(simulator, name, peer_name),
bytes_to_transfer_(0),
bytes_transferred_(0),
wrong_data_received_(false),
notifier_(nullptr) {
connection_ = std::make_unique<QuicConnection>(
connection_id, GetAddressFromName(name), GetAddressFromName(peer_name),
simulator, simulator->GetAlarmFactory(), &writer_, false, perspective,
ParsedVersionOfIndex(CurrentSupportedVersions(), 0),
connection_id_generator_);
connection_->set_visitor(this);
connection_->SetEncrypter(ENCRYPTION_FORWARD_SECURE,
std::make_unique<quic::test::TaggingEncrypter>(
ENCRYPTION_FORWARD_SECURE));
connection_->SetEncrypter(ENCRYPTION_INITIAL, nullptr);
if (connection_->version().KnowsWhichDecrypterToUse()) {
connection_->InstallDecrypter(
ENCRYPTION_FORWARD_SECURE,
std::make_unique<quic::test::StrictTaggingDecrypter>(
ENCRYPTION_FORWARD_SECURE));
connection_->RemoveDecrypter(ENCRYPTION_INITIAL);
} else {
connection_->SetDecrypter(
ENCRYPTION_FORWARD_SECURE,
std::make_unique<quic::test::StrictTaggingDecrypter>(
ENCRYPTION_FORWARD_SECURE));
}
connection_->SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
connection_->OnHandshakeComplete();
if (perspective == Perspective::IS_SERVER) {
test::QuicConnectionPeer::SetNegotiatedVersion(connection_.get());
}
test::QuicConnectionPeer::SetAddressValidated(connection_.get());
connection_->SetDataProducer(&producer_);
connection_->SetSessionNotifier(this);
notifier_ = std::make_unique<test::SimpleSessionNotifier>(connection_.get());
std::string error;
CryptoHandshakeMessage peer_hello;
peer_hello.SetValue(kICSL,
static_cast<uint32_t>(kMaximumIdleTimeoutSecs - 1));
peer_hello.SetValue(kMIBS,
static_cast<uint32_t>(kDefaultMaxStreamsPerConnection));
QuicConfig config;
QuicErrorCode error_code = config.ProcessPeerHello(
peer_hello, perspective == Perspective::IS_CLIENT ? SERVER : CLIENT,
&error);
QUICHE_DCHECK_EQ(error_code, QUIC_NO_ERROR)
<< "Configuration failed: " << error;
if (connection_->version().UsesTls()) {
if (connection_->perspective() == Perspective::IS_CLIENT) {
test::QuicConfigPeer::SetReceivedOriginalConnectionId(
&config, connection_->connection_id());
test::QuicConfigPeer::SetReceivedInitialSourceConnectionId(
&config, connection_->connection_id());
} else {
test::QuicConfigPeer::SetReceivedInitialSourceConnectionId(
&config, connection_->client_connection_id());
}
}
connection_->SetFromConfig(config);
connection_->DisableMtuDiscovery();
}
QuicByteCount QuicEndpoint::bytes_received() const {
QuicByteCount total = 0;
for (auto& interval : offsets_received_) {
total += interval.max() - interval.min();
}
return total;
}
QuicByteCount QuicEndpoint::bytes_to_transfer() const {
if (notifier_ != nullptr) {
return notifier_->StreamBytesToSend();
}
return bytes_to_transfer_;
}
QuicByteCount QuicEndpoint::bytes_transferred() const {
if (notifier_ != nullptr) {
return notifier_->StreamBytesSent();
}
return bytes_transferred_;
}
void QuicEndpoint::AddBytesToTransfer(QuicByteCount bytes) {
if (notifier_ != nullptr) {
if (notifier_->HasBufferedStreamData()) {
Schedule(clock_->Now());
}
notifier_->WriteOrBufferData(kDataStream, bytes, NO_FIN);
return;
}
if (bytes_to_transfer_ > 0) {
Schedule(clock_->Now());
}
bytes_to_transfer_ += bytes;
WriteStreamData();
}
void QuicEndpoint::OnStreamFrame(const QuicStreamFrame& frame) {
QUICHE_DCHECK(frame.stream_id == kDataStream);
for (size_t i = 0; i < frame.data_length; i++) {
if (frame.data_buffer[i] != kStreamDataContents) {
wrong_data_received_ = true;
}
}
offsets_received_.Add(frame.offset, frame.offset + frame.data_length);
QUICHE_DCHECK_LE(offsets_received_.Size(), 1000u);
}
void QuicEndpoint::OnCryptoFrame(const QuicCryptoFrame& ) {}
void QuicEndpoint::OnCanWrite() {
if (notifier_ != nullptr) {
notifier_->OnCanWrite();
return;
}
WriteStreamData();
}
bool QuicEndpoint::WillingAndAbleToWrite() const {
if (notifier_ != nullptr) {
return notifier_->WillingToWrite();
}
return bytes_to_transfer_ != 0;
}
bool QuicEndpoint::ShouldKeepConnectionAlive() const { return true; }
bool QuicEndpoint::AllowSelfAddressChange() const { return false; }
bool QuicEndpoint::OnFrameAcked(const QuicFrame& frame,
QuicTime::Delta ack_delay_time,
QuicTime receive_timestamp) {
if (notifier_ != nullptr) {
return notifier_->OnFrameAcked(frame, ack_delay_time, receive_timestamp);
}
return false;
}
void QuicEndpoint::OnFrameLost(const QuicFrame& frame) {
QUICHE_DCHECK(notifier_);
notifier_->OnFrameLost(frame);
}
bool QuicEndpoint::RetransmitFrames(const QuicFrames& frames,
TransmissionType type) {
QUICHE_DCHECK(notifier_);
return notifier_->RetransmitFrames(frames, type);
}
bool QuicEndpoint::IsFrameOutstanding(const QuicFrame& frame) const {
QUICHE_DCHECK(notifier_);
return notifier_->IsFrameOutstanding(frame);
}
bool QuicEndpoint::HasUnackedCryptoData() const { return false; }
bool QuicEndpoint::HasUnackedStreamData() const {
if (notifier_ != nullptr) {
return notifier_->HasUnackedStreamData();
}
return false;
}
HandshakeState QuicEndpoint::GetHandshakeState() const {
return HANDSHAKE_COMPLETE;
}
WriteStreamDataResult QuicEndpoint::DataProducer::WriteStreamData(
QuicStreamId , QuicStreamOffset , QuicByteCount data_length,
QuicDataWriter* writer) {
writer->WriteRepeatedByte(kStreamDataContents, data_length);
return WRITE_SUCCESS;
}
bool QuicEndpoint::DataProducer::WriteCryptoData(EncryptionLevel ,
QuicStreamOffset ,
QuicByteCount ,
QuicDataWriter* ) {
QUIC_BUG(quic_bug_10157_1)
<< "QuicEndpoint::DataProducer::WriteCryptoData is unimplemented";
return false;
}
void QuicEndpoint::WriteStreamData() {
QuicConnection::ScopedPacketFlusher flusher(connection_.get());
while (bytes_to_transfer_ > 0) {
const size_t transmission_size =
std::min(kWriteChunkSize, bytes_to_transfer_);
QuicConsumedData consumed_data = connection_->SendStreamData(
kDataStream, transmission_size, bytes_transferred_, NO_FIN);
QUICHE_DCHECK(consumed_data.bytes_consumed <= transmission_size);
bytes_transferred_ += consumed_data.bytes_consumed;
bytes_to_transfer_ -= consumed_data.bytes_consumed;
if (consumed_data.bytes_consumed != transmission_size) {
return;
}
}
}
}
} | #include "quiche/quic/test_tools/simulator/quic_endpoint.h"
#include <memory>
#include <utility>
#include "quiche/quic/platform/api/quic_flags.h"
#include "quiche/quic/platform/api/quic_test.h"
#include "quiche/quic/test_tools/quic_connection_peer.h"
#include "quiche/quic/test_tools/quic_test_utils.h"
#include "quiche/quic/test_tools/simulator/simulator.h"
#include "quiche/quic/test_tools/simulator/switch.h"
using ::testing::_;
using ::testing::NiceMock;
using ::testing::Return;
namespace quic {
namespace simulator {
const QuicBandwidth kDefaultBandwidth =
QuicBandwidth::FromKBitsPerSecond(10 * 1000);
const QuicTime::Delta kDefaultPropagationDelay =
QuicTime::Delta::FromMilliseconds(20);
const QuicByteCount kDefaultBdp = kDefaultBandwidth * kDefaultPropagationDelay;
class QuicEndpointTest : public quic::test::QuicTest {
public:
QuicEndpointTest()
: simulator_(), switch_(&simulator_, "Switch", 8, kDefaultBdp * 2) {}
protected:
Simulator simulator_;
Switch switch_;
std::unique_ptr<SymmetricLink> Link(Endpoint* a, Endpoint* b) {
return std::make_unique<SymmetricLink>(a, b, kDefaultBandwidth,
kDefaultPropagationDelay);
}
std::unique_ptr<SymmetricLink> CustomLink(Endpoint* a, Endpoint* b,
uint64_t extra_rtt_ms) {
return std::make_unique<SymmetricLink>(
a, b, kDefaultBandwidth,
kDefaultPropagationDelay +
QuicTime::Delta::FromMilliseconds(extra_rtt_ms));
}
};
TEST_F(QuicEndpointTest, OneWayTransmission) {
QuicEndpoint endpoint_a(&simulator_, "Endpoint A", "Endpoint B",
Perspective::IS_CLIENT, test::TestConnectionId(42));
QuicEndpoint endpoint_b(&simulator_, "Endpoint B", "Endpoint A",
Perspective::IS_SERVER, test::TestConnectionId(42));
auto link_a = Link(&endpoint_a, switch_.port(1));
auto link_b = Link(&endpoint_b, switch_.port(2));
endpoint_a.AddBytesToTransfer(600);
QuicTime end_time =
simulator_.GetClock()->Now() + QuicTime::Delta::FromMilliseconds(1000);
simulator_.RunUntil(
[this, end_time]() { return simulator_.GetClock()->Now() >= end_time; });
EXPECT_EQ(600u, endpoint_a.bytes_transferred());
ASSERT_EQ(600u, endpoint_b.bytes_received());
EXPECT_FALSE(endpoint_a.wrong_data_received());
EXPECT_FALSE(endpoint_b.wrong_data_received());
endpoint_a.AddBytesToTransfer(2 * 1024 * 1024);
end_time = simulator_.GetClock()->Now() + QuicTime::Delta::FromSeconds(5);
simulator_.RunUntil(
[this, end_time]() { return simulator_.GetClock()->Now() >= end_time; });
const QuicByteCount total_bytes_transferred = 600 + 2 * 1024 * 1024;
EXPECT_EQ(total_bytes_transferred, endpoint_a.bytes_transferred());
EXPECT_EQ(total_bytes_transferred, endpoint_b.bytes_received());
EXPECT_EQ(0u, endpoint_a.write_blocked_count());
EXPECT_FALSE(endpoint_a.wrong_data_received());
EXPECT_FALSE(endpoint_b.wrong_data_received());
}
TEST_F(QuicEndpointTest, WriteBlocked) {
QuicEndpoint endpoint_a(&simulator_, "Endpoint A", "Endpoint B",
Perspective::IS_CLIENT, test::TestConnectionId(42));
QuicEndpoint endpoint_b(&simulator_, "Endpoint B", "Endpoint A",
Perspective::IS_SERVER, test::TestConnectionId(42));
auto link_a = Link(&endpoint_a, switch_.port(1));
auto link_b = Link(&endpoint_b, switch_.port(2));
auto* sender = new NiceMock<test::MockSendAlgorithm>();
EXPECT_CALL(*sender, CanSend(_)).WillRepeatedly(Return(true));
EXPECT_CALL(*sender, PacingRate(_))
.WillRepeatedly(Return(10 * kDefaultBandwidth));
EXPECT_CALL(*sender, BandwidthEstimate())
.WillRepeatedly(Return(10 * kDefaultBandwidth));
EXPECT_CALL(*sender, GetCongestionWindow())
.WillRepeatedly(Return(kMaxOutgoingPacketSize *
GetQuicFlag(quic_max_congestion_window)));
test::QuicConnectionPeer::SetSendAlgorithm(endpoint_a.connection(), sender);
QuicByteCount bytes_to_transfer = 3 * 1024 * 1024;
endpoint_a.AddBytesToTransfer(bytes_to_transfer);
QuicTime end_time =
simulator_.GetClock()->Now() + QuicTime::Delta::FromSeconds(30);
simulator_.RunUntil([this, &endpoint_b, bytes_to_transfer, end_time]() {
return endpoint_b.bytes_received() == bytes_to_transfer ||
simulator_.GetClock()->Now() >= end_time;
});
EXPECT_EQ(bytes_to_transfer, endpoint_a.bytes_transferred());
EXPECT_EQ(bytes_to_transfer, endpoint_b.bytes_received());
EXPECT_GT(endpoint_a.write_blocked_count(), 0u);
EXPECT_FALSE(endpoint_a.wrong_data_received());
EXPECT_FALSE(endpoint_b.wrong_data_received());
}
TEST_F(QuicEndpointTest, TwoWayTransmission) {
QuicEndpoint endpoint_a(&simulator_, "Endpoint A", "Endpoint B",
Perspective::IS_CLIENT, test::TestConnectionId(42));
QuicEndpoint endpoint_b(&simulator_, "Endpoint B", "Endpoint A",
Perspective::IS_SERVER, test::TestConnectionId(42));
auto link_a = Link(&endpoint_a, switch_.port(1));
auto link_b = Link(&endpoint_b, switch_.port(2));
endpoint_a.RecordTrace();
endpoint_b.RecordTrace();
endpoint_a.AddBytesToTransfer(1024 * 1024);
endpoint_b.AddBytesToTransfer(1024 * 1024);
QuicTime end_time =
simulator_.GetClock()->Now() + QuicTime::Delta::FromSeconds(5);
simulator_.RunUntil(
[this, end_time]() { return simulator_.GetClock()->Now() >= end_time; });
EXPECT_EQ(1024u * 1024u, endpoint_a.bytes_transferred());
EXPECT_EQ(1024u * 1024u, endpoint_b.bytes_transferred());
EXPECT_EQ(1024u * 1024u, endpoint_a.bytes_received());
EXPECT_EQ(1024u * 1024u, endpoint_b.bytes_received());
EXPECT_FALSE(endpoint_a.wrong_data_received());
EXPECT_FALSE(endpoint_b.wrong_data_received());
}
TEST_F(QuicEndpointTest, Competition) {
auto endpoint_a = std::make_unique<QuicEndpoint>(
&simulator_, "Endpoint A", "Endpoint D (A)", Perspective::IS_CLIENT,
test::TestConnectionId(42));
auto endpoint_b = std::make_unique<QuicEndpoint>(
&simulator_, "Endpoint B", "Endpoint D (B)", Perspective::IS_CLIENT,
test::TestConnectionId(43));
auto endpoint_c = std::make_unique<QuicEndpoint>(
&simulator_, "Endpoint C", "Endpoint D (C)", Perspective::IS_CLIENT,
test::TestConnectionId(44));
auto endpoint_d_a = std::make_unique<QuicEndpoint>(
&simulator_, "Endpoint D (A)", "Endpoint A", Perspective::IS_SERVER,
test::TestConnectionId(42));
auto endpoint_d_b = std::make_unique<QuicEndpoint>(
&simulator_, "Endpoint D (B)", "Endpoint B", Perspective::IS_SERVER,
test::TestConnectionId(43));
auto endpoint_d_c = std::make_unique<QuicEndpoint>(
&simulator_, "Endpoint D (C)", "Endpoint C", Perspective::IS_SERVER,
test::TestConnectionId(44));
QuicEndpointMultiplexer endpoint_d(
"Endpoint D",
{endpoint_d_a.get(), endpoint_d_b.get(), endpoint_d_c.get()});
auto link_a = CustomLink(endpoint_a.get(), switch_.port(1), 0);
auto link_b = CustomLink(endpoint_b.get(), switch_.port(2), 1);
auto link_c = CustomLink(endpoint_c.get(), switch_.port(3), 2);
auto link_d = Link(&endpoint_d, switch_.port(4));
endpoint_a->AddBytesToTransfer(2 * 1024 * 1024);
endpoint_b->AddBytesToTransfer(2 * 1024 * 1024);
endpoint_c->AddBytesToTransfer(2 * 1024 * 1024);
QuicTime end_time =
simulator_.GetClock()->Now() + QuicTime::Delta::FromSeconds(12);
simulator_.RunUntil(
[this, end_time]() { return simulator_.GetClock()->Now() >= end_time; });
for (QuicEndpoint* endpoint :
{endpoint_a.get(), endpoint_b.get(), endpoint_c.get()}) {
EXPECT_EQ(2u * 1024u * 1024u, endpoint->bytes_transferred());
EXPECT_GE(endpoint->connection()->GetStats().packets_lost, 0u);
}
for (QuicEndpoint* endpoint :
{endpoint_d_a.get(), endpoint_d_b.get(), endpoint_d_c.get()}) {
EXPECT_EQ(2u * 1024u * 1024u, endpoint->bytes_received());
EXPECT_FALSE(endpoint->wrong_data_received());
}
}
}
} |
387 | #ifndef TENSORFLOW_CORE_GRAPPLER_UTILS_TRANSITIVE_FANIN_H_
#define TENSORFLOW_CORE_GRAPPLER_UTILS_TRANSITIVE_FANIN_H_
#include <unordered_map>
#include <vector>
#include "tensorflow/core/framework/graph.pb.h"
#include "tensorflow/core/lib/core/status.h"
namespace tensorflow {
namespace grappler {
Status ComputeTransitiveFanin(
const GraphDef& graph, const std::vector<string>& terminal_nodes,
std::unordered_map<string, const NodeDef*>* name_to_fanin_node,
std::vector<const NodeDef*>* fanin_nodes);
Status ComputeTransitiveFanin(const GraphDef& graph,
const std::vector<string>& terminal_nodes,
std::vector<const NodeDef*>* fanin_nodes);
Status SetTransitiveFaninGraph(const GraphDef& input_graph,
GraphDef* output_graph,
const std::vector<string>& terminal_nodes);
}
}
#endif
#include "tensorflow/core/grappler/utils/transitive_fanin.h"
#include <queue>
#include <vector>
#include "tensorflow/core/framework/node_def_util.h"
#include "tensorflow/core/grappler/utils.h"
#include "tensorflow/core/platform/errors.h"
namespace tensorflow {
namespace grappler {
Status ComputeTransitiveFanin(
const GraphDef& graph, const std::vector<string>& terminal_nodes,
std::unordered_map<string, const NodeDef*>* name_to_fanin_node,
std::vector<const NodeDef*>* fanin_nodes) {
std::unordered_map<string, const NodeDef*> name_to_node;
std::unordered_map<string, const NodeDef*> name_to_send;
for (const auto& node : graph.node()) {
name_to_node[node.name()] = &node;
if (node.op() == "_Send") {
const auto& attr = node.attr();
name_to_send[attr.at("tensor_name").s()] = &node;
}
}
std::vector<const NodeDef*> queue;
for (const string& root : terminal_nodes) {
const NodeDef* node = name_to_node[NodeName(root)];
if (!node) {
return errors::InvalidArgument("Graph does not contain terminal node ",
root, ".");
}
queue.push_back(node);
}
std::unordered_set<const NodeDef*> visited;
while (!queue.empty()) {
const NodeDef* node = queue.back();
queue.pop_back();
if (!visited.insert(node).second) {
continue;
}
fanin_nodes->push_back(node);
if (name_to_fanin_node) {
name_to_fanin_node->insert(
std::pair<string, const NodeDef*>(node->name(), node));
}
for (const string& input : node->input()) {
const NodeDef* in = name_to_node[NodeName(input)];
if (!in) {
return errors::InvalidArgument("Graph does not contain input ",
NodeName(input), " of node ",
node->name(), ".");
}
queue.push_back(in);
}
if (node->op() == "_Recv") {
const auto& attr = node->attr();
const NodeDef* send = name_to_send[attr.at("tensor_name").s()];
if (send) {
queue.push_back(send);
}
}
}
return absl::OkStatus();
}
Status ComputeTransitiveFanin(const GraphDef& graph,
const std::vector<string>& terminal_nodes,
std::vector<const NodeDef*>* fanin_nodes) {
return ComputeTransitiveFanin(graph, terminal_nodes, nullptr, fanin_nodes);
}
Status SetTransitiveFaninGraph(const GraphDef& input_graph,
GraphDef* output_graph,
const std::vector<string>& terminal_nodes) {
std::vector<const NodeDef*> keep;
TF_RETURN_IF_ERROR(
ComputeTransitiveFanin(input_graph, terminal_nodes, &keep));
output_graph->mutable_node()->Reserve(keep.size());
for (int i = keep.size() - 1; i >= 0; --i) {
*output_graph->add_node() = *keep[i];
}
return absl::OkStatus();
}
}
} | #include "tensorflow/core/grappler/utils/transitive_fanin.h"
#include <vector>
#include "tensorflow/core/framework/graph.pb.h"
#include "tensorflow/core/framework/node_def.pb.h"
#include "tensorflow/core/grappler/utils.h"
#include "tensorflow/core/lib/core/status_test_util.h"
#include "tensorflow/core/platform/test.h"
namespace tensorflow {
namespace grappler {
namespace {
class TransitiveFaninTest : public ::testing::Test {
protected:
struct NodeConfig {
NodeConfig(string name, std::vector<string> inputs)
: name(std::move(name)), inputs(std::move(inputs)) {}
NodeConfig(string name, string op, std::vector<string> inputs)
: name(std::move(name)), op(std::move(op)), inputs(std::move(inputs)) {}
string name;
string op;
std::vector<string> inputs;
};
static GraphDef CreateGraph(const std::vector<NodeConfig>& nodes) {
GraphDef graph;
for (const NodeConfig& node : nodes) {
NodeDef node_def;
node_def.set_name(node.name);
node_def.set_op(node.op);
for (const string& input : node.inputs) {
node_def.add_input(input);
}
*graph.add_node() = std::move(node_def);
}
return graph;
}
};
TEST_F(TransitiveFaninTest, NoPruning) {
GraphDef graph = CreateGraph({
{"1", {"2"}},
{"2", {"3"}},
{"3", {"4"}},
{"4", {}}
});
GraphDef output_graph;
const std::vector<string> terminal_nodes = {"1"};
TF_EXPECT_OK(SetTransitiveFaninGraph(graph, &output_graph, terminal_nodes));
NodeMap node_map(&output_graph);
ASSERT_TRUE(node_map.NodeExists("1"));
ASSERT_TRUE(node_map.NodeExists("2"));
ASSERT_TRUE(node_map.NodeExists("3"));
ASSERT_TRUE(node_map.NodeExists("4"));
}
TEST_F(TransitiveFaninTest, PruneNodesUnreachableFromSingleTerminalNode) {
GraphDef graph = CreateGraph({
{"1", {"2"}},
{"2", {"3"}},
{"3", {"4"}},
{"4", {}},
{"5", {"1"}}
});
GraphDef output_graph;
const std::vector<string> terminal_nodes = {"1"};
TF_EXPECT_OK(SetTransitiveFaninGraph(graph, &output_graph, terminal_nodes));
NodeMap node_map(&output_graph);
ASSERT_TRUE(node_map.NodeExists("1"));
ASSERT_TRUE(node_map.NodeExists("2"));
ASSERT_TRUE(node_map.NodeExists("3"));
ASSERT_TRUE(node_map.NodeExists("4"));
ASSERT_FALSE(node_map.NodeExists("5"));
}
TEST_F(TransitiveFaninTest, PruneNodesUnreachableFromMultipleTerminalNodes) {
GraphDef graph = CreateGraph({
{"1", {"2"}},
{"2", {"3"}},
{"3", {"4"}},
{"4", {}},
{"5", {"2"}},
{"6", {"1"}}
});
GraphDef output_graph;
const std::vector<string> terminal_nodes = {"1", "5"};
TF_EXPECT_OK(SetTransitiveFaninGraph(graph, &output_graph, terminal_nodes));
NodeMap node_map(&output_graph);
ASSERT_TRUE(node_map.NodeExists("1"));
ASSERT_TRUE(node_map.NodeExists("2"));
ASSERT_TRUE(node_map.NodeExists("3"));
ASSERT_TRUE(node_map.NodeExists("4"));
ASSERT_TRUE(node_map.NodeExists("5"));
ASSERT_FALSE(node_map.NodeExists("6"));
}
TEST_F(TransitiveFaninTest, InvalidGraphOrTerminalNodes) {
GraphDef graph = CreateGraph({
{"1", {"2"}},
{"2", {"3"}},
{"3", {"4"}},
{"4", {}},
{"5", {"6"}},
{"7", {"8"}}
});
GraphDef output_graph;
const std::vector<string> terminal_nodes = {"1", "5"};
auto s = SetTransitiveFaninGraph(graph, &output_graph, terminal_nodes);
EXPECT_FALSE(s.ok());
EXPECT_EQ(s.message(), "Graph does not contain input 6 of node 5.");
const std::vector<string> invalid_terminal_nodes = {"0", "1", "5"};
s = SetTransitiveFaninGraph(graph, &output_graph, invalid_terminal_nodes);
EXPECT_FALSE(s.ok());
EXPECT_EQ(s.message(), "Graph does not contain terminal node 0.");
}
}
}
} |
388 | #ifndef TENSORFLOW_CORE_KERNELS_DATA_EXPERIMENTAL_DIRECTED_INTERLEAVE_DATASET_OP_H_
#define TENSORFLOW_CORE_KERNELS_DATA_EXPERIMENTAL_DIRECTED_INTERLEAVE_DATASET_OP_H_
#include "tensorflow/core/framework/dataset.h"
namespace tensorflow {
namespace data {
namespace experimental {
class DirectedInterleaveDatasetOp : public DatasetOpKernel {
public:
static constexpr const char* const kDatasetType = "DirectedInterleave";
static constexpr const char* const kSelectorInputDataset =
"selector_input_dataset";
static constexpr const char* const kDataInputDatasets = "data_input_datasets";
static constexpr const char* const kOutputTypes = "output_types";
static constexpr const char* const kOutputShapes = "output_shapes";
static constexpr const char* const kNumInputDatasets = "N";
static constexpr const char* const kStopOnEmptyDataset =
"stop_on_empty_dataset";
explicit DirectedInterleaveDatasetOp(OpKernelConstruction* ctx);
protected:
void MakeDataset(OpKernelContext* ctx, DatasetBase** output) override;
private:
class Dataset;
bool stop_on_empty_dataset_ = false;
};
}
}
}
#endif
#include "tensorflow/core/kernels/data/experimental/directed_interleave_dataset_op.h"
#include <string>
#include <utility>
#include "tensorflow/core/data/name_utils.h"
#include "tensorflow/core/data/split_utils.h"
#include "tensorflow/core/framework/partial_tensor_shape.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/lib/hash/hash.h"
#include "tensorflow/core/platform/errors.h"
namespace tensorflow {
namespace data {
namespace experimental {
constexpr const char* const
DirectedInterleaveDatasetOp::kDatasetType;
constexpr const char* const
DirectedInterleaveDatasetOp::kSelectorInputDataset;
constexpr const char* const
DirectedInterleaveDatasetOp::kDataInputDatasets;
constexpr const char* const
DirectedInterleaveDatasetOp::kStopOnEmptyDataset;
constexpr const char* const
DirectedInterleaveDatasetOp::kOutputTypes;
constexpr const char* const
DirectedInterleaveDatasetOp::kOutputShapes;
constexpr const char* const
DirectedInterleaveDatasetOp::kNumInputDatasets;
constexpr char kCycleLength[] = "cycle_length";
constexpr char kDataInputImplEmpty[] = "data_input_impl_empty";
constexpr char kSelectorInputImplEmpty[] = "selector_input_impl_empty";
class DirectedInterleaveDatasetOp::Dataset : public DatasetBase {
public:
Dataset(OpKernelContext* ctx, const DatasetBase* selector_input,
std::vector<DatasetBase*> data_inputs, bool stop_on_empty_dataset)
: DatasetBase(DatasetContext(ctx)),
selector_input_(selector_input),
data_inputs_(std::move(data_inputs)),
stop_on_empty_dataset_(stop_on_empty_dataset) {
selector_input_->Ref();
output_shapes_ = data_inputs_[0]->output_shapes();
data_inputs_[0]->Ref();
for (size_t i = 1; i < data_inputs_.size(); ++i) {
const DatasetBase* data_input = data_inputs_[i];
data_input->Ref();
for (size_t j = 0; j < output_shapes_.size(); ++j) {
output_shapes_[j] = MostSpecificCompatibleShape(
output_shapes_[j], data_input->output_shapes()[j]);
}
}
}
~Dataset() override {
selector_input_->Unref();
for (DatasetBase* data_input : data_inputs_) {
data_input->Unref();
}
}
std::unique_ptr<IteratorBase> MakeIteratorInternal(
const string& prefix) const override {
return std::make_unique<Iterator>(Iterator::Params{
this, name_utils::IteratorPrefix(kDatasetType, prefix)});
}
Status MakeSplitProviders(std::vector<std::unique_ptr<SplitProvider>>*
split_providers) const override {
TF_ASSIGN_OR_RETURN(*split_providers, GetSplitProviders(this));
return absl::OkStatus();
}
const DataTypeVector& output_dtypes() const override {
return data_inputs_[0]->output_dtypes();
}
const std::vector<PartialTensorShape>& output_shapes() const override {
return output_shapes_;
}
string DebugString() const override {
return name_utils::DatasetDebugString(kDatasetType);
}
int64_t CardinalityInternal(CardinalityOptions options) const override {
for (const auto& input : data_inputs_) {
int64_t n = input->Cardinality(options);
if (n == kInfiniteCardinality) {
return n;
}
}
return kUnknownCardinality;
}
Status InputDatasets(std::vector<const DatasetBase*>* inputs) const override {
inputs->push_back(selector_input_);
for (const auto& data_input : data_inputs_) {
inputs->push_back(data_input);
}
return absl::OkStatus();
}
Status CheckExternalState() const override {
for (const auto& input : data_inputs_) {
TF_RETURN_IF_ERROR(input->CheckExternalState());
}
return selector_input_->CheckExternalState();
}
protected:
Status AsGraphDefInternal(SerializationContext* ctx,
DatasetGraphDefBuilder* b,
Node** output) const override {
Node* selector_input_node;
TF_RETURN_IF_ERROR(
b->AddInputDataset(ctx, selector_input_, &selector_input_node));
std::vector<Node*> data_input_nodes(data_inputs_.size());
for (size_t i = 0; i < data_inputs_.size(); ++i) {
TF_RETURN_IF_ERROR(
b->AddInputDataset(ctx, data_inputs_[i], &data_input_nodes[i]));
}
AttrValue stop_on_empty_dataset_attr;
b->BuildAttrValue(stop_on_empty_dataset_, &stop_on_empty_dataset_attr);
TF_RETURN_IF_ERROR(b->AddDataset(
this,
{{0, selector_input_node}},
{{1, data_input_nodes}},
{std::make_pair(kStopOnEmptyDataset, stop_on_empty_dataset_attr)},
output));
return absl::OkStatus();
}
private:
class Iterator : public DatasetIterator<Dataset> {
public:
explicit Iterator(const Params& params)
: DatasetIterator<Dataset>(params),
num_active_inputs_(params.dataset->data_inputs_.size()) {}
bool SymbolicCheckpointCompatible() const override { return true; }
Status Initialize(IteratorContext* ctx) override {
mutex_lock l(mu_);
TF_ASSIGN_OR_RETURN(input_contexts_,
CreateInputIteratorContexts(ctx, dataset()));
TF_RETURN_IF_ERROR(dataset()->selector_input_->MakeIterator(
&input_contexts_[0], this, prefix(), &selector_input_impl_));
ctx->MergeCheckpoint(input_contexts_[0].checkpoint());
data_input_impls_.resize(dataset()->data_inputs_.size());
for (size_t i = 0; i < data_input_impls_.size(); ++i) {
const DatasetBase* data_input = dataset()->data_inputs_[i];
TF_RETURN_IF_ERROR(data_input->MakeIterator(
&input_contexts_[i + 1], this,
strings::StrCat(prefix(), "[", i, "]"), &data_input_impls_[i]));
ctx->MergeCheckpoint(input_contexts_[i + 1].checkpoint());
}
return absl::OkStatus();
}
Status GetNextInternal(IteratorContext* ctx,
std::vector<Tensor>* out_tensors,
bool* end_of_sequence) override {
mutex_lock l(mu_);
if (!selector_input_impl_) {
*end_of_sequence = true;
return absl::OkStatus();
}
while (true) {
std::vector<Tensor> selector_result;
*end_of_sequence = false;
TF_RETURN_IF_ERROR(selector_input_impl_->GetNext(
&input_contexts_[0], &selector_result, end_of_sequence));
ctx->MergeCheckpoint(input_contexts_[0].checkpoint());
if (*end_of_sequence) {
ResetInputs();
return absl::OkStatus();
}
int64_t selected_input = selector_result[0].scalar<int64_t>()();
if (selected_input < 0 || selected_input >= data_input_impls_.size()) {
return errors::InvalidArgument(
"Selector index out of range: ", selected_input,
" >= ", data_input_impls_.size());
}
if (data_input_impls_[selected_input]) {
bool end_of_selected_input = false;
TF_RETURN_IF_ERROR(data_input_impls_[selected_input]->GetNext(
&input_contexts_[selected_input + 1], out_tensors,
&end_of_selected_input));
ctx->MergeCheckpoint(
input_contexts_[selected_input + 1].checkpoint());
if (!end_of_selected_input) {
return absl::OkStatus();
}
ctx->PurgeCheckpoint(data_input_impls_[selected_input]->prefix());
if (dataset()->stop_on_empty_dataset_) {
*end_of_sequence = true;
ResetInputs();
return absl::OkStatus();
}
data_input_impls_[selected_input].reset();
--num_active_inputs_;
if (num_active_inputs_ == 0) {
selector_input_impl_.reset();
*end_of_sequence = true;
return absl::OkStatus();
}
}
VLOG(2) << "DirectedInterleave selected an exhausted input: "
<< selected_input;
}
}
protected:
std::shared_ptr<model::Node> CreateNode(
IteratorContext* ctx, model::Node::Args args) const override {
return model::MakeInterleaveManyNode(
std::move(args),
{model::MakeNonTunableParameter(kCycleLength, 1)});
}
Status SaveInternal(SerializationContext* ctx,
IteratorStateWriter* writer) override {
mutex_lock l(mu_);
TF_RETURN_IF_ERROR(
writer->WriteScalar(full_name(kSelectorInputImplEmpty),
static_cast<int64_t>(!selector_input_impl_)));
if (selector_input_impl_) {
TF_RETURN_IF_ERROR(SaveInput(ctx, writer, selector_input_impl_));
}
for (size_t i = 0; i < data_input_impls_.size(); ++i) {
const auto& data_input_impl = data_input_impls_[i];
TF_RETURN_IF_ERROR(writer->WriteScalar(
full_name(strings::StrCat(kDataInputImplEmpty, "[", i, "]")),
static_cast<int64_t>(!data_input_impl)));
if (data_input_impl) {
TF_RETURN_IF_ERROR(SaveInput(ctx, writer, data_input_impl));
}
}
return absl::OkStatus();
}
Status RestoreInternal(IteratorContext* ctx,
IteratorStateReader* reader) override {
mutex_lock l(mu_);
int64_t input_empty;
TF_RETURN_IF_ERROR(
reader->ReadScalar(full_name(kSelectorInputImplEmpty), &input_empty));
if (!static_cast<bool>(input_empty)) {
TF_RETURN_IF_ERROR(RestoreInput(ctx, reader, selector_input_impl_));
} else {
selector_input_impl_.reset();
}
for (size_t i = 0; i < data_input_impls_.size(); ++i) {
TF_RETURN_IF_ERROR(reader->ReadScalar(
full_name(strings::StrCat(kDataInputImplEmpty, "[", i, "]")),
&input_empty));
if (!static_cast<bool>(input_empty)) {
TF_RETURN_IF_ERROR(RestoreInput(ctx, reader, data_input_impls_[i]));
} else {
data_input_impls_[i].reset();
}
}
return absl::OkStatus();
}
private:
void ResetInputs() TF_EXCLUSIVE_LOCKS_REQUIRED(mu_) {
selector_input_impl_.reset();
for (auto& data_input_impl : data_input_impls_) {
data_input_impl.reset();
}
num_active_inputs_ = 0;
}
mutex mu_;
std::vector<IteratorContext> input_contexts_;
std::unique_ptr<IteratorBase> selector_input_impl_ TF_GUARDED_BY(mu_);
std::vector<std::unique_ptr<IteratorBase>> data_input_impls_
TF_GUARDED_BY(mu_);
int64_t num_active_inputs_ TF_GUARDED_BY(mu_);
};
static PartialTensorShape MostSpecificCompatibleShape(
const PartialTensorShape& ts1, const PartialTensorShape& ts2) {
PartialTensorShape output_tensorshape;
if (ts1.dims() != ts2.dims() || ts1.unknown_rank() || ts2.unknown_rank())
return output_tensorshape;
auto dims1 = ts1.dim_sizes();
auto dims2 = ts2.dim_sizes();
for (int d = 0; d < ts1.dims(); ++d) {
if (dims1[d] == dims2[d])
output_tensorshape.Concatenate(dims1[d]);
else
output_tensorshape.Concatenate(-1);
}
return output_tensorshape;
}
const DatasetBase* const selector_input_;
const std::vector<DatasetBase*> data_inputs_;
std::vector<PartialTensorShape> output_shapes_;
const bool stop_on_empty_dataset_;
};
DirectedInterleaveDatasetOp::DirectedInterleaveDatasetOp(
OpKernelConstruction* ctx)
: DatasetOpKernel(ctx) {
if (ctx->HasAttr(kStopOnEmptyDataset)) {
OP_REQUIRES_OK(ctx,
ctx->GetAttr(kStopOnEmptyDataset, &stop_on_empty_dataset_));
}
}
void DirectedInterleaveDatasetOp::MakeDataset(OpKernelContext* ctx,
DatasetBase** output) {
DatasetBase* selector_input;
OP_REQUIRES_OK(ctx,
GetDatasetFromVariantTensor(ctx->input(0), &selector_input));
OP_REQUIRES(
ctx,
selector_input->output_dtypes().size() == 1 &&
selector_input->output_dtypes()[0] == DT_INT64 &&
selector_input->output_shapes().size() == 1 &&
selector_input->output_shapes()[0].IsCompatibleWith(
PartialTensorShape({})),
errors::InvalidArgument(
"The selector input must be a dataset of scalar int64 elements."));
std::vector<DatasetBase*> data_inputs;
for (size_t i = 1; i < ctx->num_inputs(); ++i) {
DatasetBase* input;
OP_REQUIRES_OK(ctx, GetDatasetFromVariantTensor(ctx->input(i), &input));
data_inputs.push_back(input);
OP_REQUIRES(ctx, data_inputs[0]->output_dtypes() == input->output_dtypes(),
errors::InvalidArgument(
"All inputs must have the same output_dtypes. First input "
"has types ",
DataTypeVectorString(data_inputs[0]->output_dtypes()),
", and input ", i - 1, " has types ",
DataTypeVectorString(input->output_dtypes())));
}
*output = new Dataset(ctx, selector_input, std::move(data_inputs),
stop_on_empty_dataset_);
}
namespace {
REGISTER_KERNEL_BUILDER(Name("DirectedInterleaveDataset").Device(DEVICE_CPU),
DirectedInterleaveDatasetOp);
REGISTER_KERNEL_BUILDER(
Name("ExperimentalDirectedInterleaveDataset").Device(DEVICE_CPU),
DirectedInterleaveDatasetOp);
}
}
}
} | #include "tensorflow/core/kernels/data/experimental/directed_interleave_dataset_op.h"
#include "tensorflow/core/data/dataset_test_base.h"
namespace tensorflow {
namespace data {
namespace experimental {
namespace {
constexpr char kNodeName[] = "directed_interleave_dataset";
class DirectedInterleaveDatasetParams : public DatasetParams {
public:
template <typename S, typename T>
DirectedInterleaveDatasetParams(S selector_input_dataset_params,
std::vector<T> input_dataset_params_vec,
bool stop_on_empty_dataset,
DataTypeVector output_dtypes,
std::vector<PartialTensorShape> output_shapes,
int num_input_datasets, string node_name)
: DatasetParams(std::move(output_dtypes), std::move(output_shapes),
std::move(node_name)),
stop_on_empty_dataset_(stop_on_empty_dataset),
num_input_datasets_(input_dataset_params_vec.size()) {
input_dataset_params_.push_back(
std::make_unique<S>(selector_input_dataset_params));
for (auto input_dataset_params : input_dataset_params_vec) {
input_dataset_params_.push_back(
std::make_unique<T>(input_dataset_params));
}
if (!input_dataset_params_vec.empty()) {
iterator_prefix_ = name_utils::IteratorPrefix(
input_dataset_params_vec[0].dataset_type(),
input_dataset_params_vec[0].iterator_prefix());
}
}
std::vector<Tensor> GetInputTensors() const override { return {}; }
Status GetInputNames(std::vector<string>* input_names) const override {
input_names->clear();
input_names->emplace_back(
DirectedInterleaveDatasetOp::kSelectorInputDataset);
for (int i = 0; i < num_input_datasets_; ++i) {
input_names->emplace_back(absl::StrCat(
DirectedInterleaveDatasetOp::kDataInputDatasets, "_", i));
}
return absl::OkStatus();
}
Status GetAttributes(AttributeVector* attr_vector) const override {
attr_vector->clear();
attr_vector->emplace_back(DirectedInterleaveDatasetOp::kOutputTypes,
output_dtypes_);
attr_vector->emplace_back(DirectedInterleaveDatasetOp::kOutputShapes,
output_shapes_);
attr_vector->emplace_back(DirectedInterleaveDatasetOp::kNumInputDatasets,
num_input_datasets_);
attr_vector->emplace_back(DirectedInterleaveDatasetOp::kStopOnEmptyDataset,
stop_on_empty_dataset_);
return absl::OkStatus();
}
string dataset_type() const override {
return DirectedInterleaveDatasetOp::kDatasetType;
}
private:
bool stop_on_empty_dataset_;
int32 num_input_datasets_;
};
class DirectedInterleaveDatasetOpTest : public DatasetOpsTestBase {};
DirectedInterleaveDatasetParams AlternateInputsParams() {
auto selector_input_dataset_params = TensorSliceDatasetParams(
{CreateTensor<int64_t>(TensorShape{6},
{0, 1, 0, 1, 0, 1})},
"tensor_slice");
return DirectedInterleaveDatasetParams(
selector_input_dataset_params,
std::vector<RangeDatasetParams>{RangeDatasetParams(0, 3, 1),
RangeDatasetParams(10, 13, 1)},
false,
{DT_INT64, DT_INT64},
{PartialTensorShape({}), PartialTensorShape({})},
2,
kNodeName);
}
DirectedInterleaveDatasetParams SelectExhaustedInputParams() {
auto selector_input_dataset_params = TensorSliceDatasetParams(
{CreateTensor<int64_t>(TensorShape{6},
{0, 1, 0, 1, 0, 1})},
"tensor_slice");
return DirectedInterleaveDatasetParams(
selector_input_dataset_params,
std::vector<RangeDatasetParams>{RangeDatasetParams(0, 2, 1),
RangeDatasetParams(10, 13, 1)},
false,
{DT_INT64, DT_INT64},
{PartialTensorShape({}), PartialTensorShape({})},
2,
kNodeName);
}
DirectedInterleaveDatasetParams OneInputDatasetParams() {
auto selector_input_dataset_params = TensorSliceDatasetParams(
{CreateTensor<int64_t>(TensorShape{6},
{0, 0, 0, 0, 0, 0})},
"tensor_slice");
return DirectedInterleaveDatasetParams(
selector_input_dataset_params,
std::vector<RangeDatasetParams>{RangeDatasetParams(0, 6, 1)},
false,
{DT_INT64},
{PartialTensorShape({})},
1,
kNodeName);
}
DirectedInterleaveDatasetParams ZeroInputDatasetParams() {
auto selector_input_dataset_params = TensorSliceDatasetParams(
{CreateTensor<int64_t>(TensorShape{6},
{0, 0, 0, 0, 0, 0})},
"tensor_slice");
return DirectedInterleaveDatasetParams(
selector_input_dataset_params,
std::vector<RangeDatasetParams>{},
false,
{DT_INT64},
{PartialTensorShape({})},
0,
kNodeName);
}
DirectedInterleaveDatasetParams StopOnEmptyDatasetParams() {
auto selector_input_dataset_params = TensorSliceDatasetParams(
{CreateTensor<int64_t>(TensorShape{6},
{0, 0, 0, 0, 0, 1})},
"tensor_slice");
return DirectedInterleaveDatasetParams(
selector_input_dataset_params,
std::vector<RangeDatasetParams>{RangeDatasetParams(0, 3, 1),
RangeDatasetParams(10, 50, 1)},
true,
{DT_INT64, DT_INT64},
{PartialTensorShape({}), PartialTensorShape({})},
2,
kNodeName);
}
DirectedInterleaveDatasetParams SkipEmptyDatasetParams() {
auto selector_input_dataset_params = TensorSliceDatasetParams(
{CreateTensor<int64_t>(TensorShape{6},
{0, 0, 0, 0, 0, 1})},
"tensor_slice");
return DirectedInterleaveDatasetParams(
selector_input_dataset_params,
std::vector<RangeDatasetParams>{RangeDatasetParams(0, 3, 1),
RangeDatasetParams(10, 50, 1)},
false,
{DT_INT64, DT_INT64},
{PartialTensorShape({}), PartialTensorShape({})},
2,
kNodeName);
}
DirectedInterleaveDatasetParams EmptyInputDatasetParams() {
auto selector_input_dataset_params = TensorSliceDatasetParams(
{CreateTensor<int64_t>(TensorShape{6},
{0, 0, 0, 0, 0, 0})},
"tensor_slice");
return DirectedInterleaveDatasetParams(
selector_input_dataset_params,
std::vector<RangeDatasetParams>{RangeDatasetParams(0, 0, 1),
RangeDatasetParams(10, 50, 1)},
true,
{DT_INT64},
{PartialTensorShape({})},
0,
kNodeName);
}
DirectedInterleaveDatasetParams LargeNumInputDatasetsParams() {
auto selector_input_dataset_params = TensorSliceDatasetParams(
{CreateTensor<int64_t>(TensorShape{6},
{0, 1, 0, 1, 0, 1})},
"tensor_slice");
return DirectedInterleaveDatasetParams(
selector_input_dataset_params,
std::vector<RangeDatasetParams>{RangeDatasetParams(0, 3, 1),
RangeDatasetParams(10, 13, 1)},
false,
{DT_INT64, DT_INT64},
{PartialTensorShape({}), PartialTensorShape({})},
5,
kNodeName);
}
DirectedInterleaveDatasetParams SmallNumInputDatasetsParams() {
auto selector_input_dataset_params = TensorSliceDatasetParams(
{CreateTensor<int64_t>(TensorShape{6},
{0, 1, 0, 1, 0, 1})},
"tensor_slice");
return DirectedInterleaveDatasetParams(
selector_input_dataset_params,
std::vector<RangeDatasetParams>{RangeDatasetParams(0, 3, 1),
RangeDatasetParams(10, 13, 1)},
false,
{DT_INT64, DT_INT64},
{PartialTensorShape({}), PartialTensorShape({})},
1,
kNodeName);
}
DirectedInterleaveDatasetParams InvalidSelectorOuputDataType() {
auto selector_input_dataset_params = TensorSliceDatasetParams(
{CreateTensor<int32>(TensorShape{6}, {0, 1, 0, 1, 0, 1})},
"tensor_slice");
return DirectedInterleaveDatasetParams(
selector_input_dataset_params,
std::vector<RangeDatasetParams>{RangeDatasetParams(0, 3, 1),
RangeDatasetParams(10, 13, 1)},
false,
{DT_INT64, DT_INT64},
{PartialTensorShape({}), PartialTensorShape({})},
2,
kNodeName);
}
DirectedInterleaveDatasetParams InvalidSelectorOuputShape() {
auto selector_input_dataset_params = TensorSliceDatasetParams(
{CreateTensor<int64_t>(TensorShape{6, 1},
{0, 1, 0, 1, 0, 1})},
"tensor_slice");
return DirectedInterleaveDatasetParams(
selector_input_dataset_params,
std::vector<RangeDatasetParams>{RangeDatasetParams(0, 3, 1),
RangeDatasetParams(10, 13, 1)},
false,
{DT_INT64, DT_INT64},
{PartialTensorShape({}), PartialTensorShape({})},
2,
kNodeName);
}
DirectedInterleaveDatasetParams InvalidSelectorValues() {
auto selector_input_dataset_params = TensorSliceDatasetParams(
{CreateTensor<int64_t>(TensorShape{6},
{2, 1, 0, 1, 0, 1})},
"tensor_slice");
return DirectedInterleaveDatasetParams(
selector_input_dataset_params,
std::vector<RangeDatasetParams>{RangeDatasetParams(0, 3, 1),
RangeDatasetParams(10, 13, 1)},
false,
{DT_INT64, DT_INT64},
{PartialTensorShape({}), PartialTensorShape({})},
2,
kNodeName);
}
DirectedInterleaveDatasetParams InvalidInputDatasetsDataType() {
auto selector_input_dataset_params = TensorSliceDatasetParams(
{CreateTensor<int64_t>(TensorShape{6},
{0, 1, 0, 1, 0, 1})},
"tensor_slice");
return DirectedInterleaveDatasetParams(
selector_input_dataset_params,
std::vector<RangeDatasetParams>{
RangeDatasetParams(0, 3, 1, {DT_INT32}),
RangeDatasetParams(10, 13, 1, {DT_INT64})},
false,
{DT_INT64, DT_INT64},
{PartialTensorShape({}), PartialTensorShape({})},
2,
kNodeName);
}
std::vector<GetNextTestCase<DirectedInterleaveDatasetParams>>
GetNextTestCases() {
return {{AlternateInputsParams(),
{CreateTensors<int64_t>(
TensorShape({}), {{0}, {10}, {1}, {11}, {2}, {12}})}},
{SelectExhaustedInputParams(),
{CreateTensors<int64_t>(
TensorShape({}), {{0}, {10}, {1}, {11}, {12}})}},
{OneInputDatasetParams(),
{CreateTensors<int64_t>(
TensorShape({}), {{0}, {1}, {2}, {3}, {4}, {5}})}},
{StopOnEmptyDatasetParams(),
{CreateTensors<int64_t>(TensorShape({}),
{{0}, {1}, {2}})}},
{SkipEmptyDatasetParams(),
{CreateTensors<int64_t>(
TensorShape({}), {{0}, {1}, {2}, {10}})}},
{EmptyInputDatasetParams(),
{CreateTensors<int64_t>(TensorShape({}), {})}},
{LargeNumInputDatasetsParams(),
{CreateTensors<int64_t>(
TensorShape({}), {{0}, {10}, {1}, {11}, {2}, {12}})}},
{SmallNumInputDatasetsParams(),
{CreateTensors<int64_t>(
TensorShape({}), {{0}, {10}, {1}, {11}, {2}, {12}})}}};
}
ITERATOR_GET_NEXT_TEST_P(DirectedInterleaveDatasetOpTest,
DirectedInterleaveDatasetParams, GetNextTestCases())
TEST_F(DirectedInterleaveDatasetOpTest, DatasetNodeName) {
auto dataset_params = AlternateInputsParams();
TF_ASSERT_OK(Initialize(dataset_params));
TF_ASSERT_OK(CheckDatasetNodeName(dataset_params.node_name()));
}
TEST_F(DirectedInterleaveDatasetOpTest, DatasetTypeString) {
auto dataset_params = AlternateInputsParams();
TF_ASSERT_OK(Initialize(dataset_params));
TF_ASSERT_OK(CheckDatasetTypeString(
name_utils::OpName(DirectedInterleaveDatasetOp::kDatasetType)));
}
TEST_F(DirectedInterleaveDatasetOpTest, DatasetOutputDtypes) {
auto dataset_params = AlternateInputsParams();
TF_ASSERT_OK(Initialize(dataset_params));
TF_ASSERT_OK(CheckDatasetOutputDtypes({DT_INT64}));
}
TEST_F(DirectedInterleaveDatasetOpTest, DatasetOutputShapes) {
auto dataset_params = AlternateInputsParams();
TF_ASSERT_OK(Initialize(dataset_params));
TF_ASSERT_OK(CheckDatasetOutputShapes({PartialTensorShape({})}));
}
TEST_F(DirectedInterleaveDatasetOpTest, Cardinality) {
auto dataset_params = AlternateInputsParams();
TF_ASSERT_OK(Initialize(dataset_params));
TF_ASSERT_OK(CheckDatasetCardinality(kUnknownCardinality));
}
TEST_F(DirectedInterleaveDatasetOpTest, IteratorOutputDtypes) {
auto dataset_params = AlternateInputsParams();
TF_ASSERT_OK(Initialize(dataset_params));
TF_ASSERT_OK(CheckIteratorOutputDtypes({DT_INT64}));
}
TEST_F(DirectedInterleaveDatasetOpTest, IteratorOutputShapes) {
auto dataset_params = AlternateInputsParams();
TF_ASSERT_OK(Initialize(dataset_params));
TF_ASSERT_OK(CheckIteratorOutputShapes({PartialTensorShape({})}));
}
TEST_F(DirectedInterleaveDatasetOpTest, IteratorPrefix) {
auto dataset_params = AlternateInputsParams();
TF_ASSERT_OK(Initialize(dataset_params));
TF_ASSERT_OK(CheckIteratorPrefix(
name_utils::IteratorPrefix(DirectedInterleaveDatasetOp::kDatasetType,
dataset_params.iterator_prefix())));
}
std::vector<IteratorSaveAndRestoreTestCase<DirectedInterleaveDatasetParams>>
IteratorSaveAndRestoreTestCases() {
return {
{AlternateInputsParams(),
{0, 5, 8},
CreateTensors<int64_t>(TensorShape{}, {{0}, {10}, {1}, {11}, {2}, {12}}),
true},
{SelectExhaustedInputParams(),
{0, 4, 8},
CreateTensors<int64_t>(TensorShape{}, {{0}, {10}, {1}, {11}, {12}}),
true},
{OneInputDatasetParams(),
{0, 5, 8},
{CreateTensors<int64_t>(TensorShape({}),
{{0}, {1}, {2}, {3}, {4}, {5}})}},
{StopOnEmptyDatasetParams(),
{0, 2, 4},
{CreateTensors<int64_t>(TensorShape({}), {{0}, {1}, {2}})}},
{SkipEmptyDatasetParams(),
{0, 2, 4},
{CreateTensors<int64_t>(TensorShape({}), {{0}, {1}, {2}, {10}})}},
{EmptyInputDatasetParams(),
{0, 2, 4},
{CreateTensors<int64_t>(TensorShape({}), {})}},
{LargeNumInputDatasetsParams(),
{0, 5, 8},
{CreateTensors<int64_t>(TensorShape({}),
{{0}, {10}, {1}, {11}, {2}, {12}})}},
{SmallNumInputDatasetsParams(),
{0, 5, 8},
{CreateTensors<int64_t>(TensorShape({}),
{{0}, {10}, {1}, {11}, {2}, {12}})}}};
}
ITERATOR_SAVE_AND_RESTORE_TEST_P(DirectedInterleaveDatasetOpTest,
DirectedInterleaveDatasetParams,
IteratorSaveAndRestoreTestCases())
TEST_F(DirectedInterleaveDatasetOpTest, InvalidArguments) {
std::vector<DirectedInterleaveDatasetParams> invalid_params_vec = {
InvalidSelectorOuputDataType(), InvalidSelectorOuputShape(),
InvalidInputDatasetsDataType(), ZeroInputDatasetParams()};
for (auto& dataset_params : invalid_params_vec) {
EXPECT_EQ(Initialize(dataset_params).code(),
absl::StatusCode::kInvalidArgument);
}
}
TEST_F(DirectedInterleaveDatasetOpTest, InvalidSelectorValues) {
auto dataset_params = InvalidSelectorValues();
TF_ASSERT_OK(Initialize(dataset_params));
bool end_of_sequence = false;
std::vector<Tensor> next;
EXPECT_EQ(
iterator_->GetNext(iterator_ctx_.get(), &next, &end_of_sequence).code(),
absl::StatusCode::kInvalidArgument);
}
}
}
}
} |
389 | #ifndef LANGSVR_SESSION_H_
#define LANGSVR_SESSION_H_
#include <functional>
#include <future>
#include <string>
#include <string_view>
#include <type_traits>
#include <unordered_map>
#include <utility>
#include "langsvr/json/builder.h"
#include "langsvr/json/value.h"
#include "langsvr/lsp/lsp.h"
#include "langsvr/lsp/message_kind.h"
#include "langsvr/one_of.h"
#include "langsvr/result.h"
namespace langsvr {
class Session {
struct RequestHandler {
std::function<Result<json::Builder::Member>(const json::Value&, json::Builder&)> function;
std::function<void()> post_send;
};
struct NotificationHandler {
std::function<Result<SuccessType>(const json::Value&)> function;
};
public:
using Sender = std::function<Result<SuccessType>(std::string_view)>;
void SetSender(Sender&& sender) { sender_ = std::move(sender); }
Result<SuccessType> Receive(std::string_view json);
template <typename T>
auto Send(T&& message) {
using Message = std::decay_t<T>;
static constexpr bool kIsRequest = Message::kMessageKind == lsp::MessageKind::kRequest;
static constexpr bool kIsNotification =
Message::kMessageKind == lsp::MessageKind::kNotification;
static_assert(kIsRequest || kIsNotification);
if constexpr (kIsRequest) {
return SendRequest(std::forward<T>(message));
} else {
return SendNotification(std::forward<T>(message));
}
}
template <typename T>
Result<std::future<typename std::decay_t<T>::ResultType>> SendRequest(T&& request) {
using Request = std::decay_t<T>;
auto b = json::Builder::Create();
auto id = next_request_id_++;
std::vector<json::Builder::Member> members{
json::Builder::Member{"id", b->I64(id)},
json::Builder::Member{"method", b->String(Request::kMethod)},
};
if constexpr (Request::kHasParams) {
auto params = Encode(request, *b.get());
if (params != Success) {
return params.Failure();
}
members.push_back(json::Builder::Member{"params", params.Get()});
}
using ResponseResultType = typename Request::ResultType;
using ResponseSuccessType = typename Request::SuccessType;
using ResponseFailureType = typename Request::FailureType;
auto promise = std::make_shared<std::promise<ResponseResultType>>();
response_handlers_.emplace(
id, [promise](const json::Value& response) -> Result<SuccessType> {
if (auto result_json = response.Get(kResponseResult); result_json == Success) {
ResponseSuccessType result;
if (auto res = lsp::Decode(*result_json.Get(), result); res != Success) {
return res.Failure();
}
promise->set_value(ResponseResultType{std::move(result)});
return Success;
}
if constexpr (std::is_same_v<ResponseFailureType, void>) {
return Failure{"response missing 'result'"};
} else {
ResponseFailureType error;
auto error_json = response.Get(kResponseError);
if (error_json != Success) {
return error_json.Failure();
}
if (auto res = lsp::Decode(*error_json.Get(), error); res != Success) {
return res.Failure();
}
promise->set_value(ResponseResultType{std::move(error)});
}
return Success;
});
auto send = SendJson(b->Object(members)->Json());
if (send != Success) {
return send.Failure();
}
return promise->get_future();
}
template <typename T>
Result<SuccessType> SendNotification(T&& notification) {
using Notification = std::decay_t<T>;
auto b = json::Builder::Create();
std::vector<json::Builder::Member> members{
json::Builder::Member{"method", b->String(Notification::kMethod)},
};
if constexpr (Notification::kHasParams) {
auto params = Encode(notification, *b.get());
if (params != Success) {
return params.Failure();
}
members.push_back(json::Builder::Member{"params", params.Get()});
}
return SendJson(b->Object(members)->Json());
}
class RegisteredRequestHandler {
public:
void OnPostSend(std::function<void()>&& callback) {
handler.post_send = std::move(callback);
}
private:
friend class Session;
RegisteredRequestHandler(RequestHandler& h) : handler{h} {}
RegisteredRequestHandler(const RegisteredRequestHandler&) = delete;
RegisteredRequestHandler& operator=(const RegisteredRequestHandler&) = delete;
RequestHandler& handler;
};
template <typename F>
auto Register(F&& callback) {
using Sig = SignatureOf<F>;
static_assert(Sig::parameter_count == 1);
using Message = typename Sig::template parameter<0>;
static constexpr bool kIsRequest = Message::kMessageKind == lsp::MessageKind::kRequest;
static constexpr bool kIsNotification =
Message::kMessageKind == lsp::MessageKind::kNotification;
static_assert(kIsRequest || kIsNotification);
auto method = std::string(Message::kMethod);
if constexpr (kIsRequest) {
auto& handler = request_handlers_[method];
handler.function = [f = std::forward<F>(callback)](
const json::Value& object,
json::Builder& json_builder) -> Result<json::Builder::Member> {
Message request;
if constexpr (Message::kHasParams) {
auto params = object.Get("params");
if (params != Success) {
return params.Failure();
}
if (auto res = Decode(*params.Get(), request); res != Success) {
return res.Failure();
}
}
auto res = f(request);
using RES_TYPE = std::decay_t<decltype(res)>;
using RequestSuccessType = typename Message::SuccessType;
using RequestFailureType = typename Message::FailureType;
if constexpr (IsResult<RES_TYPE>) {
using ResultSuccessType = typename RES_TYPE::ResultSuccess;
using ResultFailureType = typename RES_TYPE::ResultFailure;
static_assert(
std::is_same_v<ResultSuccessType, RequestSuccessType>,
"request handler Result<> success return type does not match Request's "
"Result type");
static_assert(std::is_same_v<ResultFailureType, RequestFailureType>,
"request handler Result<> failure return type does not match "
"Request's Failure type");
if (res == Success) {
auto enc = Encode(res.Get(), json_builder);
if (enc != Success) {
return enc.Failure();
}
return json::Builder::Member{std::string(kResponseResult), enc.Get()};
} else {
auto enc = Encode(res.Failure(), json_builder);
if (enc != Success) {
return enc.Failure();
}
return json::Builder::Member{std::string(kResponseError), enc.Get()};
}
} else {
static_assert((std::is_same_v<RES_TYPE, RequestSuccessType> ||
std::is_same_v<RES_TYPE, RequestFailureType>),
"request handler return type is not supported");
auto enc = Encode(res, json_builder);
if (enc != Success) {
return enc.Failure();
}
return json::Builder::Member{
std::string(std::is_same_v<RES_TYPE, RequestSuccessType> ? kResponseResult
: kResponseError),
enc.Get()};
}
};
return RegisteredRequestHandler{handler};
} else if constexpr (kIsNotification) {
auto& handler = notification_handlers_[method];
handler.function =
[f = std::forward<F>(callback)](const json::Value& object) -> Result<SuccessType> {
Message notification;
if constexpr (Message::kHasParams) {
auto params = object.Get("params");
if (params != Success) {
return params.Failure();
}
if (auto res = Decode(*params.Get(), notification); res != Success) {
return res.Failure();
}
}
return f(notification);
};
return;
}
}
private:
static constexpr std::string_view kResponseResult = "result";
static constexpr std::string_view kResponseError = "error";
Result<SuccessType> SendJson(std::string_view msg);
Sender sender_;
std::unordered_map<std::string, RequestHandler> request_handlers_;
std::unordered_map<std::string, NotificationHandler> notification_handlers_;
std::unordered_map<json::I64, std::function<Result<SuccessType>(const json::Value&)>>
response_handlers_;
json::I64 next_request_id_ = 1;
};
}
#endif
#include "langsvr/session.h"
#include <string>
#include "langsvr/json/builder.h"
namespace langsvr {
Result<SuccessType> Session::Receive(std::string_view json) {
auto json_builder = json::Builder::Create();
auto object = json_builder->Parse(json);
if (object != Success) {
return object.Failure();
}
auto method = object.Get()->Get<json::String>("method");
if (method != Success) {
auto id = object.Get()->Get<json::I64>("id");
if (id != Success) {
return id.Failure();
}
auto handler_it = response_handlers_.find(id.Get());
if (handler_it == response_handlers_.end()) {
return Failure{"received response for unknown request with ID " +
std::to_string(id.Get())};
}
auto handler = std::move(handler_it->second);
response_handlers_.erase(handler_it);
return handler(*object.Get());
}
if (object.Get()->Has("id")) {
auto id = object.Get()->Get<json::I64>("id");
if (id != Success) {
return id.Failure();
}
auto it = request_handlers_.find(method.Get());
if (it == request_handlers_.end()) {
return Failure{"no handler registered for request method '" + method.Get() + "'"};
}
auto& request_handler = it->second;
auto result = request_handler.function(*object.Get(), *json_builder.get());
if (result != Success) {
return result.Failure();
}
std::array response_members{
json::Builder::Member{"id", json_builder->I64(id.Get())},
result.Get(),
};
auto* response = json_builder->Object(response_members);
if (auto res = SendJson(response->Json()); res != Success) {
return res.Failure();
}
if (request_handler.post_send) {
request_handler.post_send();
}
} else {
auto it = notification_handlers_.find(method.Get());
if (it == notification_handlers_.end()) {
return Failure{"no handler registered for request method '" + method.Get() + "'"};
}
auto& notification_handler = it->second;
return notification_handler.function(*object.Get());
}
return Success;
}
Result<SuccessType> Session::SendJson(std::string_view msg) {
if (!sender_) [[unlikely]] {
return Failure{"no sender set"};
}
return sender_(msg);
}
} | #include "langsvr/lsp/lsp.h"
#include "langsvr/session.h"
#include <gtest/gtest.h>
#include "langsvr/json/builder.h"
#include "langsvr/lsp/decode.h"
#include "gmock/gmock.h"
#include "langsvr/result.h"
namespace langsvr {
namespace {
Result<lsp::InitializeRequest> GetInitializeRequest() {
static constexpr std::string_view kJSON =
R"({"processId":71875,"clientInfo":{"name":"My Awesome Editor","version":"1.2.3"},"locale":"en-gb","rootPath":"/home/bob/src/langsvr","rootUri":"file:
auto b = json::Builder::Create();
auto msg = b->Parse(kJSON);
if (msg != Success) {
return msg.Failure();
}
lsp::InitializeRequest request;
if (auto res = lsp::Decode(*msg.Get(), request); res != Success) {
return res.Failure();
}
return request;
}
TEST(Session, InitializeRequest_ResultOrFailure) {
auto request = GetInitializeRequest();
ASSERT_EQ(request, Success);
Session server_session;
Session client_session;
client_session.SetSender([&](std::string_view msg) { return server_session.Receive(msg); });
server_session.SetSender([&](std::string_view msg) { return client_session.Receive(msg); });
bool handler_called = false;
server_session.Register([&](const lsp::InitializeRequest& init)
-> Result<lsp::InitializeResult, lsp::InitializeError> {
handler_called = true;
EXPECT_EQ(request, init);
lsp::InitializeResult res;
res.capabilities.hover_provider = true;
return res;
});
auto response_future = client_session.Send(request.Get());
ASSERT_EQ(response_future, Success);
EXPECT_TRUE(handler_called);
auto response = response_future.Get().get();
ASSERT_EQ(response, Success);
lsp::InitializeResult expected;
expected.capabilities.hover_provider = true;
EXPECT_EQ(response.Get(), expected);
}
TEST(Session, InitializeRequest_ResultOnly) {
auto request = GetInitializeRequest();
ASSERT_EQ(request, Success);
Session server_session;
Session client_session;
client_session.SetSender([&](std::string_view msg) { return server_session.Receive(msg); });
server_session.SetSender([&](std::string_view msg) { return client_session.Receive(msg); });
bool handler_called = false;
server_session.Register([&](const lsp::InitializeRequest& init) {
handler_called = true;
EXPECT_EQ(request, init);
lsp::InitializeResult res;
res.capabilities.hover_provider = true;
return res;
});
auto response_future = client_session.Send(request.Get());
ASSERT_EQ(response_future, Success);
EXPECT_TRUE(handler_called);
auto response = response_future.Get().get();
ASSERT_EQ(response, Success);
lsp::InitializeResult expected;
expected.capabilities.hover_provider = true;
EXPECT_EQ(response.Get(), expected);
}
TEST(Session, InitializeRequest_FailureOnly) {
auto request = GetInitializeRequest();
ASSERT_EQ(request, Success);
Session server_session;
Session client_session;
client_session.SetSender([&](std::string_view msg) { return server_session.Receive(msg); });
server_session.SetSender([&](std::string_view msg) { return client_session.Receive(msg); });
bool handler_called = false;
server_session.Register([&](const lsp::InitializeRequest& init) {
handler_called = true;
EXPECT_EQ(request, init);
lsp::InitializeError err;
err.retry = true;
return err;
});
auto response_future = client_session.Send(request.Get());
ASSERT_EQ(response_future, Success);
EXPECT_TRUE(handler_called);
auto response = response_future.Get().get();
ASSERT_NE(response, Success);
lsp::InitializeError expected;
expected.retry = true;
EXPECT_EQ(response.Failure(), expected);
}
}
} |
390 | #ifndef TENSORFLOW_LITE_EXPERIMENTAL_SHLO_OPS_SIGN_H_
#define TENSORFLOW_LITE_EXPERIMENTAL_SHLO_OPS_SIGN_H_
#include "absl/status/status.h"
#include "tensorflow/lite/experimental/shlo/tensor.h"
namespace shlo_ref {
struct SignOp {
struct Attributes {};
};
SignOp Create(SignOp::Attributes);
absl::Status Prepare(SignOp& op, const Tensor& input, Tensor& output);
absl::Status Evaluate(SignOp& op, const Tensor& input, Tensor& output);
}
#endif
#include <cmath>
#include "tensorflow/lite/core/c/common.h"
#include "tensorflow/lite/kernels/internal/tensor_ctypes.h"
#include "tensorflow/lite/kernels/kernel_util.h"
namespace tflite {
namespace ops {
namespace builtin {
namespace sign {
TfLiteStatus PointwiseUnaryOpPrepare(TfLiteContext* context, TfLiteNode* node) {
TF_LITE_ENSURE_EQ(context, tflite::NumInputs(node), 1);
const TfLiteTensor* input = tflite::GetInput(context, node, 0);
TfLiteTensor* output = tflite::GetOutput(context, node, 0);
TF_LITE_ENSURE_TYPES_EQ(context, input->type, output->type);
TfLiteIntArray* output_shape = TfLiteIntArrayCopy(input->dims);
return context->ResizeTensor(context, output, output_shape);
}
template <typename Op, typename T>
TfLiteStatus PointwiseUnaryOpDoEval(
TfLiteContext* context,
const TfLiteTensor* input,
TfLiteTensor* output) {
const T* data = tflite::GetTensorData<T>(input);
T* data_output = tflite::GetTensorData<T>(output);
const int64_t num_elements = NumElements(input);
for (int64_t i = 0; i < num_elements; ++i) {
data_output[i] = Op::template Eval<T>(data[i]);
}
return TfLiteStatus::kTfLiteOk;
}
template <typename Op>
TfLiteStatus PointwiseUnaryOpEval(TfLiteContext* context, TfLiteNode* node) {
const TfLiteTensor* input = tflite::GetInput(context, node, 0);
TfLiteTensor* output = tflite::GetOutput(context, node, 0);
switch (output->type) {
case kTfLiteFloat32:
TF_LITE_ENSURE_OK(
context,
(PointwiseUnaryOpDoEval<Op, float>(context, input, output)));
break;
case kTfLiteFloat64:
TF_LITE_ENSURE_OK(
context,
(PointwiseUnaryOpDoEval<Op, double>(context, input, output)));
break;
case kTfLiteInt32:
TF_LITE_ENSURE_OK(context, (PointwiseUnaryOpDoEval<Op, int32_t>(
context, input, output)));
break;
default: {
TF_LITE_KERNEL_LOG(context, "Unsupported datatype for sign output: %s",
TfLiteTypeGetName(output->type));
return TfLiteStatus::kTfLiteError;
}
}
return TfLiteStatus::kTfLiteOk;
}
struct Sign {
template <typename T>
static T Eval(T x) {
if (x > 0) {
return 1;
}
if (x < 0) {
return -1;
}
return 0;
}
};
}
TfLiteRegistration* Register_SIGN() {
static TfLiteRegistration r = {nullptr, nullptr,
sign::PointwiseUnaryOpPrepare,
sign::PointwiseUnaryOpEval<sign::Sign>};
return &r;
}
}
}
} | #include <cmath>
#include <vector>
#include <gtest/gtest.h>
#include "tensorflow/lite/kernels/test_util.h"
#include "tensorflow/lite/schema/schema_generated.h"
namespace tflite {
namespace {
template <typename T>
tflite::TensorType GetTTEnum();
template <>
tflite::TensorType GetTTEnum<float>() {
return tflite::TensorType_FLOAT32;
}
template <>
tflite::TensorType GetTTEnum<double>() {
return tflite::TensorType_FLOAT64;
}
template <>
tflite::TensorType GetTTEnum<int32_t>() {
return tflite::TensorType_INT32;
}
class SignModel : public tflite::SingleOpModel {
public:
SignModel(tflite::TensorData x,
tflite::TensorData output) {
x_ = AddInput(x);
output_ = AddOutput(output);
SetBuiltinOp(BuiltinOperator_SIGN, BuiltinOptions_NONE, 0);
BuildInterpreter({GetShape(x_)});
}
int x_;
int output_;
template <typename T>
std::vector<T> GetOutput(const std::vector<T>& x) {
PopulateTensor<T>(x_, x);
Invoke();
return ExtractVector<T>(output_);
}
};
template <typename Float>
class SignTestFloat : public ::testing::Test {
public:
using FloatType = Float;
};
using TestTypes = ::testing::Types<float, double>;
TYPED_TEST_SUITE(SignTestFloat, TestTypes);
TYPED_TEST(SignTestFloat, TestScalarFloat) {
using Float = typename TestFixture::FloatType;
tflite::TensorData x = {GetTTEnum<Float>(), {}};
tflite::TensorData output = {GetTTEnum<Float>(), {}};
SignModel m(x, output);
auto got = m.GetOutput<Float>({0.0});
ASSERT_EQ(got.size(), 1);
EXPECT_FLOAT_EQ(got[0], 0.0);
ASSERT_FLOAT_EQ(m.GetOutput<Float>({5.0})[0], 1.0);
ASSERT_FLOAT_EQ(m.GetOutput<Float>({-3.0})[0], -1.0);
}
TYPED_TEST(SignTestFloat, TestBatchFloat) {
using Float = typename TestFixture::FloatType;
tflite::TensorData x = {GetTTEnum<Float>(), {4, 2, 1}};
tflite::TensorData output = {GetTTEnum<Float>(), {4, 2, 1}};
SignModel m(x, output);
std::vector<Float> x_data = {0.8, -0.7, 0.6, -0.5, 0.4, -0.3, 0.2, 0.0};
auto got = m.GetOutput<Float>(x_data);
EXPECT_EQ(got, std::vector<Float>(
{1.0, -1.0, 1.0, -1.0, 1.0, -1.0, 1.0, 0.0}));
}
template <typename Int>
class SignTestInt : public ::testing::Test {
public:
using IntType = Int;
};
using TestTypesInt = ::testing::Types<int32_t>;
TYPED_TEST_SUITE(SignTestInt, TestTypesInt);
TYPED_TEST(SignTestInt, TestScalarInt) {
using Int = typename TestFixture::IntType;
tflite::TensorData x = {GetTTEnum<Int>(), {}};
tflite::TensorData output = {GetTTEnum<Int>(), {}};
SignModel m(x, output);
auto got = m.GetOutput<Int>({0});
ASSERT_EQ(got.size(), 1);
EXPECT_EQ(got[0], 0);
ASSERT_EQ(m.GetOutput<Int>({5})[0], 1);
ASSERT_EQ(m.GetOutput<Int>({-3})[0], -1);
}
TYPED_TEST(SignTestInt, TestBatchInt) {
using Int = typename TestFixture::IntType;
tflite::TensorData x = {GetTTEnum<Int>(), {4, 2, 1}};
tflite::TensorData output = {GetTTEnum<Int>(), {4, 2, 1}};
SignModel m(x, output);
EXPECT_EQ(m.GetOutput<Int>({0, -7, 6, -5, 4, -3, 2, 1}),
std::vector<Int>({0, -1, 1, -1, 1, -1, 1, 1}));
}
}
} |
391 | #ifndef QUICHE_QUIC_MOQT_MOQT_SUBSCRIPTION_H_
#define QUICHE_QUIC_MOQT_MOQT_SUBSCRIPTION_H_
#include <cstdint>
#include <optional>
#include <vector>
#include "absl/container/flat_hash_map.h"
#include "absl/status/statusor.h"
#include "absl/strings/string_view.h"
#include "quiche/quic/moqt/moqt_messages.h"
#include "quiche/quic/moqt/moqt_subscribe_windows.h"
#include "quiche/quic/platform/api/quic_bug_tracker.h"
#include "quiche/common/quiche_callbacks.h"
namespace moqt {
class LocalTrack {
public:
class Visitor {
public:
virtual ~Visitor() = default;
using PublishPastObjectsCallback = quiche::SingleUseCallback<void()>;
virtual absl::StatusOr<PublishPastObjectsCallback> OnSubscribeForPast(
const SubscribeWindow& window) = 0;
};
LocalTrack(const FullTrackName& full_track_name,
MoqtForwardingPreference forwarding_preference, Visitor* visitor)
: full_track_name_(full_track_name),
forwarding_preference_(forwarding_preference),
windows_(forwarding_preference),
visitor_(visitor) {}
LocalTrack(const FullTrackName& full_track_name,
MoqtForwardingPreference forwarding_preference, Visitor* visitor,
FullSequence next_sequence)
: full_track_name_(full_track_name),
forwarding_preference_(forwarding_preference),
windows_(forwarding_preference),
next_sequence_(next_sequence),
visitor_(visitor) {}
const FullTrackName& full_track_name() const { return full_track_name_; }
std::optional<uint64_t> track_alias() const { return track_alias_; }
void set_track_alias(uint64_t track_alias) { track_alias_ = track_alias; }
Visitor* visitor() { return visitor_; }
std::vector<SubscribeWindow*> ShouldSend(FullSequence sequence) {
return windows_.SequenceIsSubscribed(sequence);
}
void AddWindow(uint64_t subscribe_id, uint64_t start_group,
uint64_t start_object);
void AddWindow(uint64_t subscribe_id, uint64_t start_group,
uint64_t start_object, uint64_t end_group);
void AddWindow(uint64_t subscribe_id, uint64_t start_group,
uint64_t start_object, uint64_t end_group,
uint64_t end_object);
void DeleteWindow(uint64_t subscribe_id) {
windows_.RemoveWindow(subscribe_id);
}
const FullSequence& next_sequence() const { return next_sequence_; }
void SentSequence(FullSequence sequence, MoqtObjectStatus status);
bool HasSubscriber() const { return !windows_.IsEmpty(); }
SubscribeWindow* GetWindow(uint64_t subscribe_id) {
return windows_.GetWindow(subscribe_id);
}
MoqtForwardingPreference forwarding_preference() const {
return forwarding_preference_;
}
void set_announce_cancel() { announce_canceled_ = true; }
bool canceled() const { return announce_canceled_; }
private:
const FullTrackName full_track_name_;
MoqtForwardingPreference forwarding_preference_;
std::optional<uint64_t> track_alias_;
MoqtSubscribeWindows windows_;
FullSequence next_sequence_ = {0, 0};
absl::flat_hash_map<uint64_t, uint64_t> max_object_ids_;
Visitor* visitor_;
bool announce_canceled_ = false;
};
class RemoteTrack {
public:
class Visitor {
public:
virtual ~Visitor() = default;
virtual void OnReply(
const FullTrackName& full_track_name,
std::optional<absl::string_view> error_reason_phrase) = 0;
virtual void OnObjectFragment(
const FullTrackName& full_track_name, uint64_t group_sequence,
uint64_t object_sequence, uint64_t object_send_order,
MoqtObjectStatus object_status,
MoqtForwardingPreference forwarding_preference,
absl::string_view object, bool end_of_message) = 0;
};
RemoteTrack(const FullTrackName& full_track_name, uint64_t track_alias,
Visitor* visitor)
: full_track_name_(full_track_name),
track_alias_(track_alias),
visitor_(visitor) {}
const FullTrackName& full_track_name() { return full_track_name_; }
uint64_t track_alias() const { return track_alias_; }
Visitor* visitor() { return visitor_; }
bool CheckForwardingPreference(MoqtForwardingPreference preference);
private:
const FullTrackName full_track_name_;
const uint64_t track_alias_;
Visitor* visitor_;
std::optional<MoqtForwardingPreference> forwarding_preference_;
};
}
#endif
#include "quiche/quic/moqt/moqt_track.h"
#include <cstdint>
#include "quiche/quic/moqt/moqt_messages.h"
namespace moqt {
void LocalTrack::AddWindow(uint64_t subscribe_id, uint64_t start_group,
uint64_t start_object) {
QUIC_BUG_IF(quic_bug_subscribe_to_canceled_track, announce_canceled_)
<< "Canceled track got subscription";
windows_.AddWindow(subscribe_id, next_sequence_, start_group, start_object);
}
void LocalTrack::AddWindow(uint64_t subscribe_id, uint64_t start_group,
uint64_t start_object, uint64_t end_group) {
QUIC_BUG_IF(quic_bug_subscribe_to_canceled_track, announce_canceled_)
<< "Canceled track got subscription";
auto it = max_object_ids_.find(end_group);
if (end_group >= next_sequence_.group) {
windows_.AddWindow(subscribe_id, next_sequence_, start_group, start_object,
end_group, UINT64_MAX);
return;
}
windows_.AddWindow(subscribe_id, next_sequence_, start_group, start_object,
end_group, it->second);
}
void LocalTrack::AddWindow(uint64_t subscribe_id, uint64_t start_group,
uint64_t start_object, uint64_t end_group,
uint64_t end_object) {
QUIC_BUG_IF(quic_bug_subscribe_to_canceled_track, announce_canceled_)
<< "Canceled track got subscription";
windows_.AddWindow(subscribe_id, next_sequence_, start_group, start_object,
end_group, end_object);
}
void LocalTrack::SentSequence(FullSequence sequence, MoqtObjectStatus status) {
QUICHE_DCHECK(max_object_ids_.find(sequence.group) == max_object_ids_.end() ||
max_object_ids_[sequence.group] < sequence.object);
switch (status) {
case MoqtObjectStatus::kNormal:
case MoqtObjectStatus::kObjectDoesNotExist:
if (next_sequence_ <= sequence) {
next_sequence_ = sequence.next();
}
break;
case MoqtObjectStatus::kGroupDoesNotExist:
max_object_ids_[sequence.group] = 0;
break;
case MoqtObjectStatus::kEndOfGroup:
max_object_ids_[sequence.group] = sequence.object;
if (next_sequence_ <= sequence) {
next_sequence_ = FullSequence(sequence.group + 1, 0);
}
break;
case MoqtObjectStatus::kEndOfTrack:
max_object_ids_[sequence.group] = sequence.object;
break;
default:
QUICHE_DCHECK(false);
return;
}
}
bool RemoteTrack::CheckForwardingPreference(
MoqtForwardingPreference preference) {
if (forwarding_preference_.has_value()) {
return forwarding_preference_.value() == preference;
}
forwarding_preference_ = preference;
return true;
}
} | #include "quiche/quic/moqt/moqt_track.h"
#include <optional>
#include "absl/strings/string_view.h"
#include "quiche/quic/moqt/moqt_messages.h"
#include "quiche/quic/moqt/moqt_subscribe_windows.h"
#include "quiche/quic/moqt/tools/moqt_mock_visitor.h"
#include "quiche/quic/platform/api/quic_test.h"
namespace moqt {
namespace test {
class LocalTrackTest : public quic::test::QuicTest {
public:
LocalTrackTest()
: track_(FullTrackName("foo", "bar"), MoqtForwardingPreference::kTrack,
&visitor_, FullSequence(4, 1)) {}
LocalTrack track_;
MockLocalTrackVisitor visitor_;
};
TEST_F(LocalTrackTest, Queries) {
EXPECT_EQ(track_.full_track_name(), FullTrackName("foo", "bar"));
EXPECT_EQ(track_.track_alias(), std::nullopt);
EXPECT_EQ(track_.visitor(), &visitor_);
EXPECT_EQ(track_.next_sequence(), FullSequence(4, 1));
track_.SentSequence(FullSequence(4, 0), MoqtObjectStatus::kNormal);
EXPECT_EQ(track_.next_sequence(), FullSequence(4, 1));
track_.SentSequence(FullSequence(4, 1), MoqtObjectStatus::kNormal);
EXPECT_EQ(track_.next_sequence(), FullSequence(4, 2));
track_.SentSequence(FullSequence(4, 2), MoqtObjectStatus::kEndOfGroup);
EXPECT_EQ(track_.next_sequence(), FullSequence(5, 0));
EXPECT_FALSE(track_.HasSubscriber());
EXPECT_EQ(track_.forwarding_preference(), MoqtForwardingPreference::kTrack);
}
TEST_F(LocalTrackTest, SetTrackAlias) {
EXPECT_EQ(track_.track_alias(), std::nullopt);
track_.set_track_alias(6);
EXPECT_EQ(track_.track_alias(), 6);
}
TEST_F(LocalTrackTest, AddGetDeleteWindow) {
track_.AddWindow(0, 4, 1);
EXPECT_EQ(track_.GetWindow(0)->subscribe_id(), 0);
EXPECT_EQ(track_.GetWindow(1), nullptr);
track_.DeleteWindow(0);
EXPECT_EQ(track_.GetWindow(0), nullptr);
}
TEST_F(LocalTrackTest, GroupSubscriptionUsesMaxObjectId) {
track_.SentSequence(FullSequence(0, 0), MoqtObjectStatus::kEndOfGroup);
track_.SentSequence(FullSequence(1, 0), MoqtObjectStatus::kNormal);
track_.SentSequence(FullSequence(1, 1), MoqtObjectStatus::kEndOfGroup);
track_.SentSequence(FullSequence(2, 0), MoqtObjectStatus::kGroupDoesNotExist);
track_.SentSequence(FullSequence(3, 0), MoqtObjectStatus::kNormal);
track_.SentSequence(FullSequence(3, 1), MoqtObjectStatus::kNormal);
track_.SentSequence(FullSequence(3, 2), MoqtObjectStatus::kNormal);
track_.SentSequence(FullSequence(3, 3), MoqtObjectStatus::kEndOfGroup);
track_.SentSequence(FullSequence(4, 0), MoqtObjectStatus::kNormal);
track_.SentSequence(FullSequence(4, 1), MoqtObjectStatus::kNormal);
track_.SentSequence(FullSequence(4, 2), MoqtObjectStatus::kNormal);
track_.SentSequence(FullSequence(4, 3), MoqtObjectStatus::kNormal);
track_.SentSequence(FullSequence(4, 4), MoqtObjectStatus::kNormal);
EXPECT_EQ(track_.next_sequence(), FullSequence(4, 5));
track_.AddWindow(0, 1, 1, 3);
SubscribeWindow* window = track_.GetWindow(0);
EXPECT_TRUE(window->InWindow(FullSequence(3, 3)));
EXPECT_FALSE(window->InWindow(FullSequence(3, 4)));
track_.AddWindow(1, 1, 1, 2);
window = track_.GetWindow(1);
EXPECT_TRUE(window->InWindow(FullSequence(1, 1)));
track_.AddWindow(2, 1, 1, 4);
window = track_.GetWindow(2);
EXPECT_TRUE(window->InWindow(FullSequence(4, 9)));
EXPECT_FALSE(window->InWindow(FullSequence(5, 0)));
}
TEST_F(LocalTrackTest, ShouldSend) {
track_.AddWindow(0, 4, 1);
EXPECT_TRUE(track_.HasSubscriber());
EXPECT_TRUE(track_.ShouldSend(FullSequence(3, 12)).empty());
EXPECT_TRUE(track_.ShouldSend(FullSequence(4, 0)).empty());
EXPECT_EQ(track_.ShouldSend(FullSequence(4, 1)).size(), 1);
EXPECT_EQ(track_.ShouldSend(FullSequence(12, 0)).size(), 1);
}
class RemoteTrackTest : public quic::test::QuicTest {
public:
RemoteTrackTest()
: track_(FullTrackName("foo", "bar"), 5, &visitor_) {}
RemoteTrack track_;
MockRemoteTrackVisitor visitor_;
};
TEST_F(RemoteTrackTest, Queries) {
EXPECT_EQ(track_.full_track_name(), FullTrackName("foo", "bar"));
EXPECT_EQ(track_.track_alias(), 5);
EXPECT_EQ(track_.visitor(), &visitor_);
}
TEST_F(RemoteTrackTest, UpdateForwardingPreference) {
EXPECT_TRUE(
track_.CheckForwardingPreference(MoqtForwardingPreference::kObject));
EXPECT_TRUE(
track_.CheckForwardingPreference(MoqtForwardingPreference::kObject));
EXPECT_FALSE(
track_.CheckForwardingPreference(MoqtForwardingPreference::kDatagram));
}
}
} |
392 | #ifndef TENSORSTORE_INTERNAL_OAUTH2_FIXED_TOKEN_AUTH_PROVIDER_H_
#define TENSORSTORE_INTERNAL_OAUTH2_FIXED_TOKEN_AUTH_PROVIDER_H_
#include <string>
#include "tensorstore/internal/oauth2/auth_provider.h"
#include "tensorstore/internal/oauth2/bearer_token.h"
#include "tensorstore/util/result.h"
namespace tensorstore {
namespace internal_oauth2 {
class FixedTokenAuthProvider : public AuthProvider {
public:
~FixedTokenAuthProvider() override = default;
FixedTokenAuthProvider(std::string token);
Result<BearerTokenWithExpiration> GetToken() override;
private:
std::string token_;
};
}
}
#endif
#include "tensorstore/internal/oauth2/fixed_token_auth_provider.h"
#include "absl/time/time.h"
#include "tensorstore/internal/oauth2/bearer_token.h"
#include "tensorstore/util/result.h"
namespace tensorstore {
namespace internal_oauth2 {
FixedTokenAuthProvider::FixedTokenAuthProvider(std::string token)
: token_(token) {}
Result<BearerTokenWithExpiration> FixedTokenAuthProvider::GetToken() {
return BearerTokenWithExpiration{token_, absl::InfiniteFuture()};
}
}
} | #include "tensorstore/internal/oauth2/fixed_token_auth_provider.h"
#include <gtest/gtest.h>
#include "absl/time/clock.h"
#include "tensorstore/util/result.h"
namespace {
using ::tensorstore::internal_oauth2::FixedTokenAuthProvider;
TEST(FixedTokenAuthProvider, Minimal) {
FixedTokenAuthProvider auth("token");
auto result = auth.GetToken();
EXPECT_TRUE(result.ok());
EXPECT_EQ("token", result->token);
EXPECT_LT(absl::Now(), result->expiration);
}
} |
393 | #ifndef AROLLA_EXPR_ANNOTATION_UTILS_H_
#define AROLLA_EXPR_ANNOTATION_UTILS_H_
#include <string_view>
#include "absl/status/statusor.h"
#include "absl/strings/string_view.h"
#include "absl/types/span.h"
#include "arolla/expr/expr_node.h"
#include "arolla/qtype/qtype.h"
namespace arolla::expr {
absl::StatusOr<bool> IsAnnotation(const ExprNodePtr& node);
absl::StatusOr<bool> IsDetachedAnnotation(const ExprNodePtr& node);
absl::StatusOr<ExprNodePtr> GetDetachedAnnotation(ExprNodePtr node);
absl::StatusOr<ExprNodePtr> AttachAnnotation(const ExprNodePtr& node,
const ExprNodePtr& annotation);
absl::StatusOr<ExprNodePtr> AttachAnnotations(
const ExprNodePtr& node, absl::Span<const ExprNodePtr> annotations);
absl::StatusOr<ExprNodePtr> StripTopmostAnnotations(const ExprNodePtr& expr);
absl::StatusOr<ExprNodePtr> StripAnnotations(const ExprNodePtr& expr);
bool IsQTypeAnnotation(const ExprNodePtr& node);
bool IsNameAnnotation(const ExprNodePtr& node);
bool IsExportAnnotation(const ExprNodePtr& node);
const QType* ReadQTypeAnnotation(const ExprNodePtr& node);
absl::string_view ReadNameAnnotation(const ExprNodePtr& node);
absl::string_view ReadExportAnnotationTag(const ExprNodePtr& node);
ExprNodePtr ReadExportAnnotationValue(const ExprNodePtr& node);
}
#endif
#include "arolla/expr/annotation_utils.h"
#include <utility>
#include "absl/log/check.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_format.h"
#include "absl/strings/string_view.h"
#include "absl/types/span.h"
#include "arolla/expr/annotation_expr_operators.h"
#include "arolla/expr/expr.h"
#include "arolla/expr/expr_debug_string.h"
#include "arolla/expr/expr_node.h"
#include "arolla/expr/expr_operator.h"
#include "arolla/expr/expr_visitor.h"
#include "arolla/expr/registered_expr_operator.h"
#include "arolla/qtype/qtype.h"
#include "arolla/qtype/qtype_traits.h"
#include "arolla/util/text.h"
#include "arolla/util/status_macros_backport.h"
namespace arolla::expr {
absl::StatusOr<bool> IsAnnotation(const ExprNodePtr& node) {
ASSIGN_OR_RETURN(auto op, DecayRegisteredOperator(node->op()));
return !node->node_deps().empty() &&
dynamic_cast<const AnnotationExprOperatorTag*>(op.get()) != nullptr;
}
absl::StatusOr<bool> IsDetachedAnnotation(const ExprNodePtr& node) {
ASSIGN_OR_RETURN(bool is_annotation, IsAnnotation(node));
DCHECK(!is_annotation ||
!node->node_deps().empty());
return is_annotation && node->node_deps()[0]->is_placeholder();
}
absl::StatusOr<ExprNodePtr> GetDetachedAnnotation(ExprNodePtr node) {
ASSIGN_OR_RETURN(bool is_annotation, IsAnnotation(node));
if (!is_annotation) {
return absl::InvalidArgumentError(
absl::StrCat("can not detach annotation from ", GetDebugSnippet(node),
" that is not a valid annotation node"));
}
auto new_deps = node->node_deps();
DCHECK(!new_deps.empty());
new_deps[0] = Placeholder("_");
return WithNewDependencies(node, std::move(new_deps));
}
absl::StatusOr<ExprNodePtr> AttachAnnotation(const ExprNodePtr& node,
const ExprNodePtr& annotation) {
ASSIGN_OR_RETURN(bool is_detached_annotation,
IsDetachedAnnotation(annotation));
if (!is_detached_annotation) {
return absl::InvalidArgumentError(absl::StrCat(
"can not attach a node that is not a detached annotation: %s",
GetDebugSnippet(node)));
}
auto new_deps = annotation->node_deps();
DCHECK(!new_deps.empty());
new_deps[0] = node;
return WithNewDependencies(annotation, std::move(new_deps));
}
absl::StatusOr<ExprNodePtr> AttachAnnotations(
const ExprNodePtr& node, absl::Span<const ExprNodePtr> annotations) {
ExprNodePtr annotated_node = node;
for (const auto& anno : annotations) {
ASSIGN_OR_RETURN(annotated_node, AttachAnnotation(annotated_node, anno));
}
return annotated_node;
}
absl::StatusOr<ExprNodePtr> StripTopmostAnnotations(const ExprNodePtr& expr) {
ExprNodePtr annotationless_expr = expr;
ASSIGN_OR_RETURN(bool is_annotation, IsAnnotation(annotationless_expr));
while (is_annotation) {
if (annotationless_expr->node_deps().empty()) {
return absl::FailedPreconditionError(
absl::StrFormat("incorrect annotation node %s",
GetDebugSnippet(annotationless_expr)));
}
annotationless_expr = annotationless_expr->node_deps()[0];
ASSIGN_OR_RETURN(is_annotation, IsAnnotation(annotationless_expr));
}
return annotationless_expr;
}
absl::StatusOr<ExprNodePtr> StripAnnotations(const ExprNodePtr& expr) {
return Transform(
expr, [](const ExprNodePtr& node) -> absl::StatusOr<ExprNodePtr> {
ASSIGN_OR_RETURN(bool is_annotation, IsAnnotation(node));
DCHECK(!is_annotation ||
!node->node_deps().empty());
return is_annotation ? node->node_deps()[0] : node;
});
}
bool IsQTypeAnnotation(const ExprNodePtr& node) {
auto op = DecayRegisteredOperator(node->op()).value_or(nullptr);
return op != nullptr && typeid(*op) == typeid(QTypeAnnotation) &&
node->node_deps().size() == 2;
}
bool IsNameAnnotation(const ExprNodePtr& node) {
auto op = DecayRegisteredOperator(node->op()).value_or(nullptr);
return op != nullptr && typeid(*op) == typeid(NameAnnotation) &&
node->node_deps().size() == 2;
}
bool IsExportAnnotation(const ExprNodePtr& node) {
auto op = DecayRegisteredOperator(node->op()).value_or(nullptr);
return op != nullptr && ((typeid(*op) == typeid(ExportAnnotation) &&
node->node_deps().size() == 2) ||
(typeid(*op) == typeid(ExportValueAnnotation) &&
node->node_deps().size() == 3));
}
const QType* ReadQTypeAnnotation(const ExprNodePtr& node) {
if (IsQTypeAnnotation(node)) {
DCHECK_EQ(node->node_deps().size(), 2);
if (const auto& qvalue = node->node_deps()[1]->qvalue()) {
if (qvalue->GetType() == GetQTypeQType()) {
return qvalue->UnsafeAs<QTypePtr>();
}
}
}
return nullptr;
}
absl::string_view ReadNameAnnotation(const ExprNodePtr& node) {
if (IsNameAnnotation(node)) {
DCHECK_EQ(node->node_deps().size(), 2);
if (const auto& qvalue = node->node_deps()[1]->qvalue()) {
if (qvalue->GetType() == GetQType<Text>()) {
return qvalue->UnsafeAs<Text>().view();
}
}
}
return "";
}
absl::string_view ReadExportAnnotationTag(const ExprNodePtr& node) {
if (IsExportAnnotation(node)) {
DCHECK_GE(node->node_deps().size(), 2);
if (node->node_deps()[1]->qvalue().has_value() &&
node->node_deps()[1]->qvalue()->GetType() == GetQType<Text>()) {
return node->node_deps()[1]->qvalue()->UnsafeAs<Text>().view();
}
}
return {};
}
ExprNodePtr ReadExportAnnotationValue(const ExprNodePtr& node) {
if (IsExportAnnotation(node)) {
if (node->node_deps().size() == 2) {
return node->node_deps()[0];
} else if (node->node_deps().size() == 3) {
return node->node_deps()[2];
}
}
return nullptr;
}
} | #include "arolla/expr/annotation_utils.h"
#include <memory>
#include <vector>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/types/span.h"
#include "arolla/expr/annotation_expr_operators.h"
#include "arolla/expr/basic_expr_operator.h"
#include "arolla/expr/expr.h"
#include "arolla/expr/expr_node.h"
#include "arolla/expr/expr_operator.h"
#include "arolla/expr/expr_operator_signature.h"
#include "arolla/expr/testing/testing.h"
#include "arolla/qtype/qtype.h"
#include "arolla/qtype/qtype_traits.h"
#include "arolla/util/fingerprint.h"
#include "arolla/util/init_arolla.h"
#include "arolla/util/testing/status_matchers_backport.h"
#include "arolla/util/text.h"
namespace arolla::expr {
namespace {
using ::arolla::testing::EqualsExpr;
using ::arolla::testing::IsOkAndHolds;
using ::arolla::testing::StatusIs;
using ::testing::Eq;
using ::testing::HasSubstr;
class AnnotationOperatorTest : public ::testing::Test {
void SetUp() override { ASSERT_OK(InitArolla()); }
};
class IdentityAnnotation : public AnnotationExprOperatorTag,
public BasicExprOperator {
public:
IdentityAnnotation()
: BasicExprOperator(
"id", ExprOperatorSignature::MakeArgsN(1), "",
FingerprintHasher("arolla::expr::IdentityAnnotation").Finish()) {}
absl::StatusOr<QTypePtr> GetOutputQType(
absl::Span<const QTypePtr> input_qtypes) const override {
return input_qtypes[0];
}
};
TEST_F(AnnotationOperatorTest, SmokeTest) {
const auto with_annotation = std::make_shared<IdentityAnnotation>();
ASSERT_OK_AND_ASSIGN(auto expr, CallOp(with_annotation, {Leaf("x")}));
ASSERT_OK_AND_ASSIGN(auto lower_expr, ToLowerNode(expr));
EXPECT_THAT(lower_expr, EqualsExpr(expr));
ASSERT_OK_AND_ASSIGN(auto typed_expr,
CallOp(with_annotation, {Literal<float>(1.0)}));
EXPECT_EQ(typed_expr->qtype(), GetQType<float>());
}
TEST_F(AnnotationOperatorTest, StripAnnotations) {
const auto id_anno = std::make_shared<IdentityAnnotation>();
{
ASSERT_OK_AND_ASSIGN(
ExprNodePtr expr,
CallOp(id_anno, {CallOp("math.add",
{CallOp(id_anno, {Leaf("x")}), Leaf("y")})}));
ASSERT_OK_AND_ASSIGN(ExprNodePtr actual, StripAnnotations(expr));
ASSERT_OK_AND_ASSIGN(ExprNodePtr expected,
CallOp("math.add", {Leaf("x"), Leaf("y")}));
EXPECT_THAT(actual, EqualsExpr(expected));
}
{
ASSERT_OK_AND_ASSIGN(ExprNodePtr expr,
CallOp(id_anno, {CallOp(id_anno, {Leaf("x")})}));
ASSERT_OK_AND_ASSIGN(ExprNodePtr actual, StripAnnotations(expr));
ExprNodePtr expected = Leaf("x");
EXPECT_THAT(actual, EqualsExpr(expected));
}
}
TEST_F(AnnotationOperatorTest, StripTopmostAnnotations) {
const auto id_anno = std::make_shared<IdentityAnnotation>();
{
ASSERT_OK_AND_ASSIGN(
ExprNodePtr expr,
CallOp(id_anno, {CallOp("math.add",
{CallOp(id_anno, {Leaf("x")}), Leaf("y")})}));
EXPECT_THAT(StripTopmostAnnotations(expr),
IsOkAndHolds(EqualsExpr(CallOp(
"math.add", {CallOp(id_anno, {Leaf("x")}), Leaf("y")}))));
}
{
ASSERT_OK_AND_ASSIGN(ExprNodePtr expr,
CallOp(id_anno, {CallOp(id_anno, {Leaf("x")})}));
EXPECT_THAT(StripTopmostAnnotations(expr),
IsOkAndHolds(EqualsExpr(Leaf("x"))));
}
}
class IdentityAnnotation2 : public AnnotationExprOperatorTag,
public BasicExprOperator {
public:
IdentityAnnotation2()
: BasicExprOperator(
"id2", ExprOperatorSignature::MakeArgsN(1), "",
FingerprintHasher("arolla::expr::IdentityAnnotation2").Finish()) {}
absl::StatusOr<QTypePtr> GetOutputQType(
absl::Span<const QTypePtr> input_qtypes) const override {
return input_qtypes[0];
}
};
TEST_F(AnnotationOperatorTest, AttachAnnotations) {
ExprNodePtr expr = Leaf("x");
EXPECT_THAT(AttachAnnotation(expr, expr),
StatusIs(absl::StatusCode::kInvalidArgument,
HasSubstr("not a detached annotation")));
const auto id_anno = std::make_shared<IdentityAnnotation>();
const auto id_anno2 = std::make_shared<IdentityAnnotation2>();
ASSERT_OK_AND_ASSIGN(auto anno1, CallOp(id_anno, {Placeholder("_")}));
ASSERT_OK_AND_ASSIGN(auto anno2, CallOp(id_anno2, {Placeholder("_")}));
std::vector<ExprNodePtr> annotations = {anno1, anno2};
ASSERT_OK_AND_ASSIGN(auto anno_expr, AttachAnnotations(expr, annotations));
ASSERT_OK_AND_ASSIGN(ExprNodePtr expected_anno_expr,
CallOp(id_anno2, {CallOp(id_anno, {Leaf("x")})}));
EXPECT_THAT(anno_expr, EqualsExpr(expected_anno_expr));
ASSERT_OK_AND_ASSIGN(auto detached, StripAnnotations(anno_expr));
EXPECT_THAT(detached, EqualsExpr(expr));
}
TEST_F(AnnotationOperatorTest, AnnotationExport) {
ASSERT_OK_AND_ASSIGN(
ExprNodePtr expr,
CallOp(ExportAnnotation::Make(), {Leaf("a"), Literal(Text{"b"})}));
ASSERT_TRUE(IsExportAnnotation(expr));
auto expected_value = Leaf("a");
EXPECT_THAT(ReadExportAnnotationTag(expr), Eq("b"));
EXPECT_THAT(ReadExportAnnotationValue(expr), EqualsExpr(expected_value));
}
TEST_F(AnnotationOperatorTest, AnnotationExportValue) {
ASSERT_OK_AND_ASSIGN(ExprNodePtr expr,
CallOp(ExportValueAnnotation::Make(),
{Leaf("a"), Literal(Text{"b"}), Leaf("c")}));
ASSERT_TRUE(IsExportAnnotation(expr));
auto expected_value = Leaf("c");
EXPECT_THAT(ReadExportAnnotationTag(expr), Eq("b"));
EXPECT_THAT(ReadExportAnnotationValue(expr), EqualsExpr(expected_value));
}
TEST_F(AnnotationOperatorTest, AnnotationExportArbitraryNode) {
ExprNodePtr expr = Leaf("a");
ASSERT_FALSE(IsExportAnnotation(expr));
EXPECT_EQ(ReadExportAnnotationTag(expr), "");
EXPECT_EQ(ReadExportAnnotationValue(expr), nullptr);
}
}
} |
394 | #ifndef TENSORFLOW_CORE_DATA_SERVICE_WORKER_CLIENT_H_
#define TENSORFLOW_CORE_DATA_SERVICE_WORKER_CLIENT_H_
#include <memory>
#include <string>
#include "tensorflow/core/data/service/common.h"
#include "tensorflow/core/data/service/common.pb.h"
#include "tensorflow/core/data/service/data_transfer.h"
#include "tensorflow/core/data/service/worker.pb.h"
#include "tensorflow/core/framework/types.h"
#include "tensorflow/core/platform/mutex.h"
#include "tensorflow/core/platform/status.h"
#include "tensorflow/core/platform/statusor.h"
#include "tensorflow/core/platform/types.h"
namespace tensorflow {
namespace data {
constexpr const char kLocalTransferProtocol[] = "local";
constexpr const char kGrpcTransferProtocol[] = "grpc";
class DataServiceWorkerClient : public DataServiceClientBase {
public:
DataServiceWorkerClient(
const std::string& address, const std::string& protocol,
const std::string& transfer_protocol,
const DeviceBase::AcceleratorDeviceInfo* accelerator_device_info,
Allocator* allocator)
: DataServiceClientBase(address, protocol),
transfer_protocol_(transfer_protocol),
accelerator_device_info_(accelerator_device_info),
allocator_(allocator) {}
Status GetElement(const GetElementRequest& req, GetElementResult& result);
void TryCancel();
Status CheckCompatibility(
const std::string& server_compatibility_info) const {
return client_->CheckCompatibility(server_compatibility_info);
}
std::string GetDataTransferProtocol() const;
protected:
Status EnsureInitialized() override;
private:
std::string transfer_protocol_;
const DeviceBase::AcceleratorDeviceInfo* accelerator_device_info_;
Allocator* allocator_;
mutex mu_;
std::unique_ptr<DataTransferClient> client_;
};
absl::StatusOr<std::unique_ptr<DataServiceWorkerClient>>
CreateDataServiceWorkerClient(
const std::string& dispatcher_protocol, const DataTransferServerInfo& info,
const DeviceBase::AcceleratorDeviceInfo* accelerator_device_info,
Allocator* allocator);
}
}
#endif
#include "tensorflow/core/data/service/worker_client.h"
#include <cstdint>
#include <functional>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "grpcpp/client_context.h"
#include "grpcpp/create_channel.h"
#include "grpcpp/security/credentials.h"
#include "grpcpp/support/channel_arguments.h"
#include "grpcpp/support/status.h"
#include "absl/container/flat_hash_set.h"
#include "absl/memory/memory.h"
#include "absl/strings/string_view.h"
#include "absl/strings/substitute.h"
#include "tensorflow/core/data/service/credentials_factory.h"
#include "tensorflow/core/data/service/data_transfer.h"
#include "tensorflow/core/data/service/grpc_util.h"
#include "tensorflow/core/data/service/worker.grpc.pb.h"
#include "tensorflow/core/data/service/worker.pb.h"
#include "tensorflow/core/data/service/worker_impl.h"
#include "tensorflow/core/framework/allocator.h"
#include "tensorflow/core/framework/dataset.pb.h"
#include "tensorflow/core/framework/device_base.h"
#include "tensorflow/core/framework/metrics.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/framework/tensor_types.h"
#include "tensorflow/core/framework/types.pb.h"
#include "tensorflow/core/framework/variant.h"
#include "tensorflow/core/platform/errors.h"
#include "tensorflow/core/platform/mutex.h"
#include "tensorflow/core/platform/status.h"
#include "tensorflow/core/platform/statusor.h"
#include "tensorflow/core/platform/thread_annotations.h"
#include "tensorflow/core/platform/types.h"
#include "tsl/platform/errors.h"
namespace tensorflow {
namespace data {
absl::StatusOr<std::unique_ptr<DataServiceWorkerClient>>
CreateDataServiceWorkerClient(
const std::string& dispatcher_protocol, const DataTransferServerInfo& info,
const DeviceBase::AcceleratorDeviceInfo* accelerator_device_info,
Allocator* allocator) {
auto client = std::make_unique<DataServiceWorkerClient>(
info.address(), dispatcher_protocol, info.protocol(),
accelerator_device_info, allocator);
TF_RETURN_IF_ERROR(client->Initialize());
TF_RETURN_WITH_CONTEXT_IF_ERROR(
client->CheckCompatibility(info.compatibility_info()),
"for data transfer protocol '", client->GetDataTransferProtocol(),
"', the compatibility check between the trainer worker and the ",
"tf.data service worker at ", info.address(), "failed");
return client;
}
Status DataServiceWorkerClient::GetElement(const GetElementRequest& req,
GetElementResult& result) {
TF_RETURN_IF_ERROR(EnsureInitialized());
return client_->GetElement(req, result);
}
Status DataServiceWorkerClient::EnsureInitialized() {
mutex_lock l(mu_);
if (client_) {
return absl::OkStatus();
}
TF_RETURN_IF_ERROR(DataTransferClient::Build(
GetDataTransferProtocol(),
{protocol_, address_, accelerator_device_info_, allocator_}, &client_));
return absl::OkStatus();
}
std::string DataServiceWorkerClient::GetDataTransferProtocol() const {
if (LocalWorkers::Get(address_) != nullptr) {
return kLocalTransferProtocol;
}
return transfer_protocol_;
}
void DataServiceWorkerClient::TryCancel() { client_->TryCancel(); }
class GrpcDataTransferClient : public DataTransferClient {
public:
GrpcDataTransferClient(std::shared_ptr<grpc::ChannelCredentials> credentials,
std::string address) {
VLOG(2) << "Create GrpcDataTransferClient for worker " << address << ".";
grpc::ChannelArguments args;
args.SetMaxReceiveMessageSize(-1);
auto channel = grpc::CreateCustomChannel(address, credentials, args);
stub_ = WorkerService::NewStub(channel);
}
Status GetElement(const GetElementRequest& req,
GetElementResult& result) override {
VLOG(3) << "GetElement for task " << req.task_id() << " from gRPC worker "
<< "server.";
{
mutex_lock l(mu_);
if (cancelled_) {
return errors::Cancelled("Client was cancelled.");
}
}
grpc::ClientContext ctx;
gtl::Cleanup<std::function<void()>> cleanup;
{
mutex_lock l(mu_);
active_contexts_.insert(&ctx);
cleanup = gtl::MakeCleanup([this, &ctx] {
mutex_lock l(mu_);
active_contexts_.erase(&ctx);
});
}
GetElementResponse resp;
int64_t start_time_us = env_->NowMicros();
grpc::Status s = stub_->GetElement(&ctx, req, &resp);
int64_t end_time_us = env_->NowMicros();
if (!s.ok()) {
return grpc_util::WrapError("Failed to get element", s);
}
metrics::RecordTFDataServiceGetElementDuration(kGrpcTransferProtocol,
end_time_us - start_time_us);
result.end_of_sequence = resp.end_of_sequence();
result.skip = resp.skip_task();
switch (resp.element_case()) {
case GetElementResponse::kCompressed: {
Tensor tensor(DT_VARIANT, TensorShape{});
tensor.scalar<Variant>()() = std::move(resp.compressed());
result.components.push_back(tensor);
break;
}
case GetElementResponse::kUncompressed:
for (const auto& component : resp.uncompressed().components()) {
result.components.emplace_back();
if (!result.components.back().FromProto(component)) {
return errors::Internal("Failed to parse tensor.");
}
}
break;
case GetElementResponse::ELEMENT_NOT_SET:
break;
}
return absl::OkStatus();
}
void TryCancel() override {
VLOG(2) << "Cancel GrpcDataTransferClient.";
mutex_lock l(mu_);
cancelled_ = true;
for (const auto& ctx : active_contexts_) {
ctx->TryCancel();
}
}
private:
mutex mu_;
std::unique_ptr<WorkerService::Stub> stub_;
absl::flat_hash_set<::grpc::ClientContext*> active_contexts_
TF_GUARDED_BY(mu_);
bool cancelled_ TF_GUARDED_BY(mu_) = false;
};
class GrpcTransferClientRegistrar {
public:
GrpcTransferClientRegistrar() {
DataTransferClient::Register(
kGrpcTransferProtocol, [](DataTransferClient::Config config,
std::unique_ptr<DataTransferClient>* out) {
std::shared_ptr<grpc::ChannelCredentials> credentials;
TF_RETURN_IF_ERROR(CredentialsFactory::CreateClientCredentials(
config.protocol, &credentials));
*out = std::make_unique<GrpcDataTransferClient>(credentials,
config.address);
return absl::OkStatus();
});
}
};
static GrpcTransferClientRegistrar gprc_client_registrar;
class LocalDataTransferClient : public DataTransferClient {
public:
explicit LocalDataTransferClient(absl::string_view worker_address)
: worker_address_(worker_address) {
VLOG(2) << "Create LocalDataTransferClient for worker " << worker_address_
<< ".";
}
Status GetElement(const GetElementRequest& req,
GetElementResult& result) override {
VLOG(3) << "GetElement for task " << req.task_id() << " from local worker.";
TF_RETURN_IF_ERROR(VerifyClientIsNotCancelled());
TF_ASSIGN_OR_RETURN(std::shared_ptr<DataServiceWorkerImpl> worker,
GetWorker(req));
int64_t start_time_us = env_->NowMicros();
Status s = worker->GetElementResult(&req, &result);
int64_t end_time_us = env_->NowMicros();
TF_RETURN_IF_ERROR(s);
metrics::RecordTFDataServiceGetElementDuration(kLocalTransferProtocol,
end_time_us - start_time_us);
return s;
}
void TryCancel() override {
VLOG(2) << "Cancel LocalDataTransferClient for worker " << worker_address_
<< ".";
mutex_lock l(mu_);
cancelled_ = true;
}
private:
Status VerifyClientIsNotCancelled() TF_LOCKS_EXCLUDED(mu_) {
mutex_lock l(mu_);
if (cancelled_) {
return errors::Cancelled(absl::Substitute(
"Client for worker $0 has been cancelled.", worker_address_));
}
return absl::OkStatus();
}
absl::StatusOr<std::shared_ptr<DataServiceWorkerImpl>> GetWorker(
const GetElementRequest& req) const {
std::shared_ptr<DataServiceWorkerImpl> worker =
LocalWorkers::Get(worker_address_);
if (!worker) {
return errors::Cancelled(absl::Substitute(
"Local worker at address $0 is no longer available; cancel request "
"for task $1.",
worker_address_, req.task_id()));
}
return worker;
}
const std::string worker_address_;
mutex mu_;
bool cancelled_ TF_GUARDED_BY(mu_) = false;
};
class LocalTransferClientRegistrar {
public:
LocalTransferClientRegistrar() {
DataTransferClient::Register(
kLocalTransferProtocol, [](DataTransferClient::Config config,
std::unique_ptr<DataTransferClient>* out) {
*out = std::make_unique<LocalDataTransferClient>(config.address);
return absl::OkStatus();
});
}
};
static LocalTransferClientRegistrar local_client_registrar;
}
} | #include "tensorflow/core/data/service/worker_client.h"
#include <memory>
#include <optional>
#include <string>
#include <utility>
#include "absl/memory/memory.h"
#include "absl/status/status.h"
#include "absl/strings/substitute.h"
#include "absl/types/optional.h"
#include "tensorflow/core/data/service/common.h"
#include "tensorflow/core/data/service/common.pb.h"
#include "tensorflow/core/data/service/data_transfer.h"
#include "tensorflow/core/data/service/dispatcher.pb.h"
#include "tensorflow/core/data/service/dispatcher_client.h"
#include "tensorflow/core/data/service/test_cluster.h"
#include "tensorflow/core/data/service/test_util.h"
#include "tensorflow/core/data/service/worker.pb.h"
#include "tensorflow/core/data/service/worker_impl.h"
#include "tensorflow/core/framework/graph.pb.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor_testutil.h"
#include "tensorflow/core/lib/core/status_test_util.h"
#include "tensorflow/core/platform/errors.h"
#include "tensorflow/core/platform/status.h"
#include "tensorflow/core/platform/status_matchers.h"
#include "tensorflow/core/platform/statusor.h"
#include "tensorflow/core/platform/test.h"
#include "tensorflow/core/platform/types.h"
#include "tensorflow/core/protobuf/data_service.pb.h"
#include "tensorflow/core/protobuf/error_codes.pb.h"
namespace tensorflow {
namespace data {
namespace {
using ::tensorflow::data::testing::RangeSquareDataset;
using ::tensorflow::testing::StatusIs;
using ::testing::MatchesRegex;
constexpr const char kProtocol[] = "grpc";
constexpr const char kAltTransferProtocol[] = "alt";
class WorkerClientTest : public ::testing::TestWithParam<std::string> {
protected:
void SetUp() override { InitializeTestCluster(); }
void InitializeTestCluster(
std::optional<std::string> data_transfer_protocol = std::nullopt) {
test_cluster_ = std::make_unique<TestCluster>(1,
data_transfer_protocol);
TF_ASSERT_OK(test_cluster_->Initialize());
dispatcher_client_ = std::make_unique<DataServiceDispatcherClient>(
test_cluster_->DispatcherAddress(), kProtocol);
}
absl::StatusOr<std::string> RegisterDataset(const int64_t range) {
const auto dataset_def = RangeSquareDataset(range);
std::string dataset_id;
TF_RETURN_IF_ERROR(dispatcher_client_->RegisterDataset(
dataset_def, DataServiceMetadata(),
std::nullopt, dataset_id));
return dataset_id;
}
absl::StatusOr<int64_t> CreateIteration(const std::string& dataset_id) {
ProcessingModeDef processing_mode;
processing_mode.set_sharding_policy(ProcessingModeDef::OFF);
int64_t job_id = 0;
TF_RETURN_IF_ERROR(dispatcher_client_->GetOrCreateJob(
dataset_id, processing_mode, std::nullopt,
std::nullopt, false,
TARGET_WORKERS_AUTO, job_id));
int64_t iteration_client_id = 0;
TF_RETURN_IF_ERROR(dispatcher_client_->GetOrCreateIteration(
job_id, 0, iteration_client_id));
return iteration_client_id;
}
absl::StatusOr<int64_t> GetTaskToRead(const int64_t iteration_client_id) {
ClientHeartbeatRequest request;
ClientHeartbeatResponse response;
request.set_iteration_client_id(iteration_client_id);
TF_RETURN_IF_ERROR(dispatcher_client_->ClientHeartbeat(request, response));
if (response.task_info().empty()) {
return errors::NotFound(absl::Substitute(
"No task found for iteration $0.", iteration_client_id));
}
return response.task_info(0).task_id();
}
absl::StatusOr<std::unique_ptr<DataServiceWorkerClient>> GetWorkerClient(
const std::string& data_transfer_protocol) {
DataTransferServerInfo info;
info.set_address(GetWorkerAddress());
info.set_protocol(data_transfer_protocol);
return CreateDataServiceWorkerClient(kProtocol, info,
nullptr,
nullptr);
}
absl::StatusOr<GetElementResult> GetElement(DataServiceWorkerClient& client,
const int64_t task_id) {
GetElementRequest request;
GetElementResult result;
request.set_task_id(task_id);
TF_RETURN_IF_ERROR(client.GetElement(request, result));
return result;
}
std::string GetDispatcherAddress() const {
return test_cluster_->DispatcherAddress();
}
std::string GetWorkerAddress() const {
return test_cluster_->WorkerAddress(0);
}
std::unique_ptr<TestCluster> test_cluster_;
std::unique_ptr<DataServiceDispatcherClient> dispatcher_client_;
};
class AltDataTransferServer : public DataTransferServer {
public:
explicit AltDataTransferServer(DataTransferServer::GetElementT get_element)
: get_element_(get_element) {}
absl::Status GetElement(const GetElementRequest& req,
GetElementResult& result) {
return get_element_(&req, &result);
}
absl::Status Start(const experimental::WorkerConfig& config) override {
return absl::OkStatus();
}
int Port() const override { return -1; }
private:
DataTransferServer::GetElementT get_element_;
};
class AltDataTransferClient : public DataTransferClient {
public:
explicit AltDataTransferClient(std::shared_ptr<AltDataTransferServer> server)
: server_(server) {}
absl::Status GetElement(const GetElementRequest& req,
GetElementResult& result) override {
return server_->GetElement(req, result);
}
void TryCancel() override {}
private:
std::shared_ptr<AltDataTransferServer> server_;
};
class AltDataTransferRegistrar {
public:
AltDataTransferRegistrar() {
DataTransferServer::Register(
kAltTransferProtocol,
[this](DataTransferServer::GetElementT get_element,
std::shared_ptr<DataTransferServer>* server) {
server_ = std::make_shared<AltDataTransferServer>(get_element);
*server = server_;
return absl::OkStatus();
});
DataTransferClient::Register(
kAltTransferProtocol,
[this](DataTransferClient::Config config,
std::unique_ptr<DataTransferClient>* client) {
*client = std::make_unique<AltDataTransferClient>(server_);
return absl::OkStatus();
});
}
private:
std::shared_ptr<AltDataTransferServer> server_ = nullptr;
};
static AltDataTransferRegistrar alt_data_transfer_registrar;
class DataTransferProtocolWorkerClientTest : public WorkerClientTest {
protected:
void SetUp() override {
std::string data_transfer_protocol = GetParam();
InitializeTestCluster(data_transfer_protocol);
}
};
TEST_F(WorkerClientTest, LocalRead) {
const int64_t range = 5;
TF_ASSERT_OK_AND_ASSIGN(const std::string dataset_id, RegisterDataset(range));
TF_ASSERT_OK_AND_ASSIGN(const int64_t iteration_client_id,
CreateIteration(dataset_id));
TF_ASSERT_OK_AND_ASSIGN(const int64_t task_id,
GetTaskToRead(iteration_client_id));
TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<DataServiceWorkerClient> client,
GetWorkerClient(kLocalTransferProtocol));
for (int64_t i = 0; i < range; ++i) {
TF_ASSERT_OK_AND_ASSIGN(GetElementResult result,
GetElement(*client, task_id));
test::ExpectEqual(result.components[0], Tensor(int64_t{i * i}));
EXPECT_FALSE(result.end_of_sequence);
}
LocalWorkers::Remove(GetWorkerAddress());
EXPECT_THAT(GetElement(*client, task_id),
StatusIs(error::CANCELLED,
MatchesRegex("Local worker.*is no longer available.*")));
}
TEST_F(WorkerClientTest, LocalReadEmptyDataset) {
TF_ASSERT_OK_AND_ASSIGN(const std::string dataset_id,
RegisterDataset(0));
TF_ASSERT_OK_AND_ASSIGN(const int64_t iteration_client_id,
CreateIteration(dataset_id));
TF_ASSERT_OK_AND_ASSIGN(const int64_t task_id,
GetTaskToRead(iteration_client_id));
TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<DataServiceWorkerClient> client,
GetWorkerClient(kLocalTransferProtocol));
TF_ASSERT_OK_AND_ASSIGN(GetElementResult result,
GetElement(*client, task_id));
EXPECT_TRUE(result.end_of_sequence);
LocalWorkers::Remove(GetWorkerAddress());
EXPECT_THAT(GetElement(*client, task_id),
StatusIs(error::CANCELLED,
MatchesRegex("Local worker.*is no longer available.*")));
}
TEST_P(DataTransferProtocolWorkerClientTest, NetworkRead) {
std::string data_transfer_protocol = GetParam();
LocalWorkers::Remove(GetWorkerAddress());
const int64_t range = 5;
TF_ASSERT_OK_AND_ASSIGN(const std::string dataset_id, RegisterDataset(range));
TF_ASSERT_OK_AND_ASSIGN(const int64_t iteration_client_id,
CreateIteration(dataset_id));
TF_ASSERT_OK_AND_ASSIGN(const int64_t task_id,
GetTaskToRead(iteration_client_id));
TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<DataServiceWorkerClient> client,
GetWorkerClient(data_transfer_protocol));
for (int64_t i = 0; i < range; ++i) {
TF_ASSERT_OK_AND_ASSIGN(GetElementResult result,
GetElement(*client, task_id));
test::ExpectEqual(result.components[0], Tensor(int64_t{i * i}));
EXPECT_FALSE(result.end_of_sequence);
}
}
INSTANTIATE_TEST_SUITE_P(
NetworkProtocols, DataTransferProtocolWorkerClientTest,
::testing::Values(kGrpcTransferProtocol, kAltTransferProtocol),
[](const ::testing::TestParamInfo<
DataTransferProtocolWorkerClientTest::ParamType>& info) {
return info.param;
});
TEST_F(WorkerClientTest, LocalServerShutsDown) {
TF_ASSERT_OK_AND_ASSIGN(const std::string dataset_id,
RegisterDataset(5));
TF_ASSERT_OK_AND_ASSIGN(const int64_t iteration_client_id,
CreateIteration(dataset_id));
TF_ASSERT_OK_AND_ASSIGN(const int64_t task_id,
GetTaskToRead(iteration_client_id));
TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<DataServiceWorkerClient> client,
GetWorkerClient(kLocalTransferProtocol));
test_cluster_->StopWorkers();
EXPECT_THAT(GetElement(*client, task_id),
StatusIs(error::CANCELLED,
MatchesRegex("Local worker.*is no longer available.*")));
}
TEST_F(WorkerClientTest, CancelClient) {
TF_ASSERT_OK_AND_ASSIGN(const std::string dataset_id,
RegisterDataset(5));
TF_ASSERT_OK_AND_ASSIGN(const int64_t iteration_client_id,
CreateIteration(dataset_id));
TF_ASSERT_OK_AND_ASSIGN(const int64_t task_id,
GetTaskToRead(iteration_client_id));
TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<DataServiceWorkerClient> client,
GetWorkerClient(kLocalTransferProtocol));
client->TryCancel();
EXPECT_THAT(GetElement(*client, task_id),
StatusIs(error::CANCELLED,
MatchesRegex("Client for worker.*has been cancelled.")));
}
}
}
} |
395 | #ifndef TENSORFLOW_CORE_COMMON_RUNTIME_DEVICE_MGR_H_
#define TENSORFLOW_CORE_COMMON_RUNTIME_DEVICE_MGR_H_
#include <map>
#include <memory>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include "absl/container/flat_hash_set.h"
#include "tensorflow/core/common_runtime/device.h"
#include "tensorflow/core/lib/core/arena.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/lib/core/stringpiece.h"
#include "tensorflow/core/lib/gtl/inlined_vector.h"
#include "tensorflow/core/platform/macros.h"
namespace tensorflow {
class DeviceAttributes;
class DeviceMgr {
public:
DeviceMgr() = default;
virtual ~DeviceMgr();
virtual void ListDeviceAttributes(
std::vector<DeviceAttributes>* devices) const = 0;
virtual std::vector<Device*> ListDevices() const = 0;
virtual string DebugString() const = 0;
virtual string DeviceMappingString() const = 0;
virtual Status LookupDevice(StringPiece name, Device** device) const = 0;
virtual bool ContainsDevice(int64_t device_incarnation) const = 0;
virtual void ClearContainers(absl::Span<const string> containers) const = 0;
virtual int NumDeviceType(const string& type) const = 0;
virtual int NumDevices() const = 0;
virtual Device* HostCPU() const = 0;
DeviceMgr(const DeviceMgr&) = delete;
void operator=(const DeviceMgr&) = delete;
};
static const size_t kStaleDeviceBufferSize = 8192;
class DynamicDeviceMgr : public DeviceMgr {
public:
DynamicDeviceMgr();
explicit DynamicDeviceMgr(std::vector<std::unique_ptr<Device>>&& devices);
explicit DynamicDeviceMgr(std::unique_ptr<Device>&& device);
~DynamicDeviceMgr() override;
void ListDeviceAttributes(
std::vector<DeviceAttributes>* devices) const override;
std::vector<Device*> ListDevices() const override;
string DebugString() const override;
string DeviceMappingString() const override;
Status LookupDevice(StringPiece name, Device** device) const override;
bool ContainsDevice(int64_t device_incarnation) const override;
void ClearContainers(absl::Span<const string> containers) const override;
int NumDeviceType(const string& type) const override;
int NumDevices() const override;
Device* HostCPU() const override;
Status AddDevices(std::vector<std::unique_ptr<Device>> devices);
Status RemoveDevices(const std::vector<Device*>& devices);
Status RemoveDevicesByName(const std::vector<string>& device_names);
private:
mutable mutex devices_mu_;
struct DereferenceDevicePtrLess {
bool operator()(const Device* a, const Device* b) const {
return Device::LessByParsedName(*a, *b);
}
};
std::map<Device*, std::unique_ptr<Device>, DereferenceDevicePtrLess>
dynamic_devices_ TF_GUARDED_BY(devices_mu_);
absl::flat_hash_set<int64_t> device_incarnation_set_
TF_GUARDED_BY(devices_mu_);
std::unordered_map<string, Device*> device_map_ TF_GUARDED_BY(devices_mu_);
std::unordered_map<string, int> device_type_counts_
TF_GUARDED_BY(devices_mu_);
mutable std::atomic<Device*> cpu_device_;
class DeviceCircularBuffer {
public:
DeviceCircularBuffer() : index_(0) {
devices_.resize(kStaleDeviceBufferSize);
}
void add(std::unique_ptr<Device> device) {
devices_[index_] = std::move(device);
index_ = (index_ + 1) % kStaleDeviceBufferSize;
}
private:
int index_;
std::vector<std::unique_ptr<Device>> devices_;
};
DeviceCircularBuffer stale_devices_ TF_GUARDED_BY(devices_mu_);
DynamicDeviceMgr(const DynamicDeviceMgr&) = delete;
void operator=(const DynamicDeviceMgr&) = delete;
};
using StaticDeviceMgr = DynamicDeviceMgr;
}
#endif
#include "tensorflow/core/common_runtime/device_mgr.h"
#include <memory>
#include <vector>
#include "tensorflow/core/common_runtime/local_device.h"
#include "tensorflow/core/framework/device_attributes.pb.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/util/device_name_utils.h"
namespace tensorflow {
DeviceMgr::~DeviceMgr() {}
} | #include "tensorflow/core/common_runtime/device_mgr.h"
#include <memory>
#include <vector>
#include "absl/memory/memory.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/platform/test.h"
namespace tensorflow {
namespace {
static Device* CreateDevice(const char* type, const char* name) {
class FakeDevice : public Device {
public:
explicit FakeDevice(const DeviceAttributes& attr) : Device(nullptr, attr) {}
Status Sync() override { return absl::OkStatus(); }
Allocator* GetAllocator(AllocatorAttributes) override { return nullptr; }
};
DeviceAttributes attr;
attr.set_name(name);
attr.set_device_type(type);
return new FakeDevice(attr);
}
TEST(StaticDeviceMgr, NoCPUDevice) {
std::unique_ptr<Device> d0(CreateDevice("GPU", "/device:GPU:0"));
std::unique_ptr<Device> d1(CreateDevice("GPU", "/device:GPU:1"));
std::vector<std::unique_ptr<Device>> devices;
devices.emplace_back(std::move(d0));
devices.emplace_back(std::move(d1));
StaticDeviceMgr lm(std::move(devices));
EXPECT_EQ(lm.HostCPU(), nullptr);
}
TEST(StaticDeviceMgr, SomeCPUDevice) {
std::unique_ptr<Device> d0(CreateDevice("GPU", "/device:GPU:0"));
std::unique_ptr<Device> d1(CreateDevice("GPU", "/device:GPU:1"));
std::unique_ptr<Device> d2(CreateDevice("CPU", "/device:CPU:0"));
Device* d2_ptr = d2.get();
std::vector<std::unique_ptr<Device>> devices;
devices.emplace_back(std::move(d0));
devices.emplace_back(std::move(d1));
devices.emplace_back(std::move(d2));
StaticDeviceMgr lm(std::move(devices));
EXPECT_EQ(lm.HostCPU(), d2_ptr);
}
}
} |
396 | #ifndef XLA_SERVICE_GPU_ALL_REDUCE_BLUECONNECT_H_
#define XLA_SERVICE_GPU_ALL_REDUCE_BLUECONNECT_H_
#include <cstddef>
#include "absl/container/flat_hash_set.h"
#include "absl/status/statusor.h"
#include "absl/strings/string_view.h"
#include "xla/hlo/ir/hlo_module.h"
#include "xla/service/hlo_pass_interface.h"
namespace xla {
class AllReduceBlueConnect : public HloModulePass {
public:
explicit AllReduceBlueConnect(size_t num_devices_per_host)
: num_devices_per_host_(num_devices_per_host) {}
absl::string_view name() const override { return "all-reduce-blueconnect"; }
using HloPassInterface::Run;
absl::StatusOr<bool> Run(
HloModule* module,
const absl::flat_hash_set<absl::string_view>& execution_threads) override;
private:
size_t num_devices_per_host_;
};
}
#endif
#include "xla/service/gpu/all_reduce_blueconnect.h"
#include <algorithm>
#include <cstddef>
#include <cstdint>
#include <iterator>
#include <optional>
#include <utility>
#include <vector>
#include "absl/algorithm/container.h"
#include "absl/container/btree_map.h"
#include "absl/container/flat_hash_set.h"
#include "absl/strings/string_view.h"
#include "absl/types/span.h"
#include "xla/hlo/ir/hlo_casting_utils.h"
#include "xla/hlo/ir/hlo_instruction.h"
#include "xla/hlo/ir/hlo_instructions.h"
#include "xla/hlo/ir/hlo_opcode.h"
#include "xla/hlo/utils/hlo_query.h"
#include "xla/service/computation_placer.h"
#include "xla/service/hlo_creation_utils.h"
#include "xla/shape.h"
#include "xla/shape_util.h"
#include "xla/status_macros.h"
#include "tsl/platform/errors.h"
#include "tsl/platform/logging.h"
#include "tsl/platform/statusor.h"
namespace xla {
namespace {
std::vector<HloInstruction*> GetOutputs(HloInstruction& instruction) {
if (!instruction.shape().IsTuple()) {
return {&instruction};
}
std::vector<HloInstruction*> outputs;
outputs.reserve(instruction.shape().tuple_shapes_size());
HloComputation& computation = *instruction.parent();
for (int i = 0; i < instruction.shape().tuple_shapes_size(); ++i) {
outputs.push_back(computation.AddInstruction(
HloInstruction::CreateGetTupleElement(&instruction, i)));
}
return outputs;
}
struct DecomposedReplicaGroups {
std::vector<ReplicaGroup> scatter_gather_groups;
std::vector<ReplicaGroup> new_all_reduce_groups;
};
absl::StatusOr<std::optional<DecomposedReplicaGroups>> TryDecomposeReplicaGroup(
const ReplicaGroup& replica_group,
const DeviceAssignment& device_assignment, size_t num_devices_per_host) {
int group_size = replica_group.replica_ids_size();
TF_RET_CHECK(group_size > 0);
absl::btree_map<int, std::vector<int64_t>> replica_ids_by_host;
for (int64_t replica_id : replica_group.replica_ids()) {
int device_id = device_assignment(replica_id, 0);
TF_RET_CHECK(device_id >= 0);
int host_id = device_id / num_devices_per_host;
replica_ids_by_host[host_id].push_back(replica_id);
}
size_t num_local_devices = replica_ids_by_host.begin()->second.size();
bool same_num_devices_on_each_host =
absl::c_all_of(replica_ids_by_host, [&](const auto& entry) {
return entry.second.size() == num_local_devices;
});
if (!same_num_devices_on_each_host) {
return {std::nullopt};
}
std::vector<int64_t> sorted_replica_group;
sorted_replica_group.reserve(group_size);
for (const auto& entry : replica_ids_by_host) {
absl::c_copy(entry.second, std::back_inserter(sorted_replica_group));
}
size_t scatter_group_size = std::max(num_local_devices, size_t(2));
size_t num_scatter_groups = group_size / scatter_group_size;
if ((group_size % scatter_group_size != 0) || (num_scatter_groups < 2)) {
return {std::nullopt};
}
std::vector<ReplicaGroup> scatter_gather_groups(num_scatter_groups);
std::vector<ReplicaGroup> new_all_reduce_groups(scatter_group_size);
for (size_t i = 0; i < group_size; ++i) {
int64_t replica_id = sorted_replica_group[i];
scatter_gather_groups[i / scatter_group_size].add_replica_ids(replica_id);
new_all_reduce_groups[i % scatter_group_size].add_replica_ids(replica_id);
}
return {DecomposedReplicaGroups{std::move(scatter_gather_groups),
std::move(new_all_reduce_groups)}};
}
absl::StatusOr<std::optional<DecomposedReplicaGroups>>
TryDecomposeReplicaGroups(const HloAllReduceInstruction& all_reduce,
size_t num_devices_per_host) {
const DeviceAssignment& device_assignment =
all_reduce.GetModule()->config().static_device_assignment();
absl::Span<const ReplicaGroup> replica_groups = all_reduce.replica_groups();
ReplicaGroup all_replicas;
if (replica_groups.empty()) {
for (int i = 0; i < device_assignment.replica_count(); ++i) {
all_replicas.add_replica_ids(i);
}
replica_groups = absl::MakeSpan(&all_replicas, 1);
}
std::vector<ReplicaGroup> scatter_gather_groups;
std::vector<ReplicaGroup> new_all_reduce_groups;
for (const ReplicaGroup& replica_group : replica_groups) {
TF_ASSIGN_OR_RETURN(
std::optional<DecomposedReplicaGroups> decomposed_groups,
TryDecomposeReplicaGroup(replica_group, device_assignment,
num_devices_per_host));
if (!decomposed_groups) return {std::nullopt};
int scatter_group_size =
decomposed_groups->scatter_gather_groups[0].replica_ids_size();
if (scatter_gather_groups.empty()) {
for (const HloInstruction* operand : all_reduce.operands()) {
TF_RET_CHECK(operand->shape().IsArray());
int64_t num_elements = ShapeUtil::ElementsIn(operand->shape());
if (num_elements % scatter_group_size != 0) {
return {std::nullopt};
}
}
scatter_gather_groups.reserve(
replica_groups.size() *
decomposed_groups->scatter_gather_groups.size());
new_all_reduce_groups.reserve(
replica_groups.size() *
decomposed_groups->new_all_reduce_groups.size());
} else if (scatter_group_size !=
scatter_gather_groups[0].replica_ids_size()) {
return {std::nullopt};
}
absl::c_move(decomposed_groups->scatter_gather_groups,
std::back_inserter(scatter_gather_groups));
absl::c_move(decomposed_groups->new_all_reduce_groups,
std::back_inserter(new_all_reduce_groups));
}
return {DecomposedReplicaGroups{std::move(scatter_gather_groups),
std::move(new_all_reduce_groups)}};
}
absl::StatusOr<bool> TryDecomposeAllReduce(HloAllReduceInstruction* all_reduce,
size_t num_devices_per_host) {
TF_RET_CHECK(all_reduce);
TF_RET_CHECK(!all_reduce->has_sharding());
HloComputation& computation = *all_reduce->parent();
PrimitiveType element_type = all_reduce->operand(0)->shape().element_type();
TF_ASSIGN_OR_RETURN(
std::optional<DecomposedReplicaGroups> decomposed_groups,
TryDecomposeReplicaGroups(*all_reduce, num_devices_per_host));
if (!decomposed_groups) return false;
std::vector<HloInstruction*> flat_operands;
flat_operands.reserve(all_reduce->operand_count());
std::vector<Shape> flat_shapes;
flat_shapes.reserve(all_reduce->operand_count());
std::vector<Shape> scattered_shapes;
scattered_shapes.reserve(all_reduce->operand_count());
int scatter_group_size =
decomposed_groups->scatter_gather_groups[0].replica_ids_size();
for (HloInstruction* operand : all_reduce->operands()) {
TF_RET_CHECK(operand->shape().IsArray());
int64_t num_elements = ShapeUtil::ElementsIn(operand->shape());
Shape flat_shape = ShapeUtil::MakeShape(element_type, {num_elements});
flat_operands.push_back(computation.AddInstruction(
HloInstruction::CreateBitcast(flat_shape, operand)));
flat_shapes.push_back(std::move(flat_shape));
scattered_shapes.push_back(ShapeUtil::MakeShape(
element_type, {num_elements / scatter_group_size}));
}
Shape reduce_scatter_shape = ShapeUtil::MakeMaybeTupleShape(scattered_shapes);
HloInstruction* reduce_scatter =
computation.AddInstruction(HloInstruction::CreateReduceScatter(
reduce_scatter_shape, flat_operands, all_reduce->to_apply(),
CollectiveDeviceList(decomposed_groups->scatter_gather_groups),
false, all_reduce->channel_id(),
all_reduce->use_global_device_ids(),
0));
HloInstruction* new_all_reduce =
computation.AddInstruction(HloInstruction::CreateAllReduce(
reduce_scatter_shape, GetOutputs(*reduce_scatter),
all_reduce->to_apply(),
CollectiveDeviceList(decomposed_groups->new_all_reduce_groups),
false, all_reduce->channel_id(),
all_reduce->use_global_device_ids()));
HloInstruction* all_gather =
computation.AddInstruction(HloInstruction::CreateAllGather(
ShapeUtil::MakeMaybeTupleShape(flat_shapes),
GetOutputs(*new_all_reduce),
0,
CollectiveDeviceList(decomposed_groups->scatter_gather_groups),
false, all_reduce->channel_id(),
all_reduce->use_global_device_ids()));
std::vector<HloInstruction*> outputs = GetOutputs(*all_gather);
for (int64_t i = 0; i < outputs.size(); ++i) {
outputs[i] = computation.AddInstruction(HloInstruction::CreateBitcast(
all_reduce->operand(i)->shape(), outputs[i]));
}
HloInstruction* replacement = MaybeMakeTuple(outputs);
TF_RETURN_IF_ERROR(
all_reduce->CopyAllControlDepsTo(reduce_scatter, replacement));
TF_RETURN_IF_ERROR(all_reduce->DropAllControlDeps());
TF_RETURN_IF_ERROR(computation.ReplaceInstruction(all_reduce, replacement));
TF_RETURN_IF_ERROR(
TryDecomposeAllReduce(Cast<HloAllReduceInstruction>(new_all_reduce),
num_devices_per_host)
.status());
return true;
}
}
absl::StatusOr<bool> AllReduceBlueConnect::Run(
HloModule* module,
const absl::flat_hash_set<absl::string_view>& execution_threads) {
VLOG(1) << "Running AllReduceBlueConnect";
if (hlo_query::ContainsLayoutConstrainedAllReduce(*module)) {
VLOG(1)
<< "Skip AllReduceBlueConnect because the module contains all-reduce "
"with constrained layouts";
return false;
}
if (!module->config().has_static_device_assignment()) {
VLOG(1)
<< "Skip AllReduceBlueConnect because the module doesn't have static "
"device assignment";
return false;
}
std::vector<HloAllReduceInstruction*> all_reduces;
for (HloComputation* computation :
module->MakeNonfusionComputations(execution_threads)) {
for (HloInstruction* instruction : computation->instructions()) {
if (instruction->opcode() == HloOpcode::kAllReduce) {
all_reduces.push_back(Cast<HloAllReduceInstruction>(instruction));
}
}
}
bool changed = false;
for (HloAllReduceInstruction* all_reduce : all_reduces) {
TF_ASSIGN_OR_RETURN(
bool all_reduce_changed,
TryDecomposeAllReduce(all_reduce, num_devices_per_host_));
changed |= all_reduce_changed;
}
return changed;
}
} | #include "xla/service/gpu/all_reduce_blueconnect.h"
#include <cstddef>
#include <cstdint>
#include <memory>
#include <vector>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "absl/strings/string_view.h"
#include "absl/types/span.h"
#include "xla/hlo/ir/hlo_computation.h"
#include "xla/hlo/ir/hlo_instruction.h"
#include "xla/hlo/ir/hlo_module.h"
#include "xla/service/computation_placer.h"
#include "xla/service/pattern_matcher.h"
#include "xla/service/pattern_matcher_gmock.h"
#include "xla/shape.h"
#include "xla/shape_util.h"
#include "xla/tests/hlo_test_base.h"
#include "tsl/platform/status_matchers.h"
#include "tsl/platform/statusor.h"
namespace xla {
namespace {
using ::tsl::testing::IsOkAndHolds;
namespace m = ::xla::match;
using AllReduceBlueConnectTest = HloTestBase;
void SetModuleConfig(HloModule& module, size_t replica_count) {
DeviceAssignment device_assignment(replica_count, 1);
device_assignment.FillIota(0);
auto& module_config = module.mutable_config();
module_config.set_replica_count(replica_count);
module_config.set_static_device_assignment(device_assignment);
}
TEST_F(AllReduceBlueConnectTest, OneStage) {
constexpr absl::string_view hlo_string = R"(
HloModule module
%add {
lhs = f32[] parameter(0)
rhs = f32[] parameter(1)
ROOT add = f32[] add(lhs, rhs)
}
ENTRY %comp {
p0 = f32[4,4] parameter(0)
ROOT crs = f32[4,4] all-reduce(p0), to_apply=add
})";
TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> module,
ParseAndReturnVerifiedModule(hlo_string));
SetModuleConfig(*module, 8);
AllReduceBlueConnect pass(4);
EXPECT_THAT(pass.Run(module.get()), IsOkAndHolds(true));
std::vector<std::vector<int64_t>> scatter_gather_groups = {
{0, 1, 2, 3}, {4, 5, 6, 7}};
std::vector<std::vector<int64_t>> new_all_reduce_groups = {
{0, 4}, {1, 5}, {2, 6}, {3, 7}};
auto bitcast = m::Bitcast(m::Parameter(0)).WithShape(F32, {16});
auto reduce_scatter =
m::ReduceScatter(bitcast).WithShape(F32, {4}).WithReplicaGroups(
scatter_gather_groups);
auto all_reduce = m::AllReduce(reduce_scatter)
.WithShape(F32, {4})
.WithReplicaGroups(new_all_reduce_groups);
auto all_gather = m::AllGather(all_reduce)
.WithShape(F32, {16})
.WithReplicaGroups(scatter_gather_groups);
EXPECT_THAT(module->entry_computation()->root_instruction(),
GmockMatch(m::Bitcast(all_gather).WithShape(F32, {4, 4})));
}
TEST_F(AllReduceBlueConnectTest, TwoStage) {
constexpr absl::string_view hlo_string = R"(
HloModule module
%add {
lhs = f32[] parameter(0)
rhs = f32[] parameter(1)
ROOT add = f32[] add(lhs, rhs)
}
ENTRY %comp {
p0 = f32[4,4] parameter(0)
ROOT crs = f32[4,4] all-reduce(p0), to_apply=add
})";
TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> module,
ParseAndReturnVerifiedModule(hlo_string));
SetModuleConfig(*module, 16);
AllReduceBlueConnect pass(4);
EXPECT_THAT(pass.Run(module.get()), IsOkAndHolds(true));
std::vector<std::vector<int64_t>> outer_scatter_gather_groups = {
{0, 1, 2, 3}, {4, 5, 6, 7}, {8, 9, 10, 11}, {12, 13, 14, 15}};
std::vector<std::vector<int64_t>> inner_scatter_gather_groups = {
{0, 4}, {8, 12}, {1, 5}, {9, 13}, {2, 6}, {10, 14}, {3, 7}, {11, 15}};
std::vector<std::vector<int64_t>> new_all_reduce_groups = {
{0, 8}, {4, 12}, {1, 9}, {5, 13}, {2, 10}, {6, 14}, {3, 11}, {7, 15}};
auto bitcast0 = m::Bitcast(m::Parameter(0)).WithShape(F32, {16});
auto reduce_scatter0 =
m::ReduceScatter(bitcast0).WithShape(F32, {4}).WithReplicaGroups(
outer_scatter_gather_groups);
auto bitcast1 = m::Bitcast(reduce_scatter0).WithShape(F32, {4});
auto reduce_scatter1 =
m::ReduceScatter(bitcast1).WithShape(F32, {2}).WithReplicaGroups(
inner_scatter_gather_groups);
auto all_reduce = m::AllReduce(reduce_scatter1)
.WithShape(F32, {2})
.WithReplicaGroups(new_all_reduce_groups);
auto all_gather0 = m::AllGather(all_reduce)
.WithShape(F32, {4})
.WithReplicaGroups(inner_scatter_gather_groups);
auto bitcast2 = m::Bitcast(all_gather0).WithShape(F32, {4});
auto all_gather1 =
m::AllGather(bitcast2).WithShape(F32, {16}).WithReplicaGroups(
outer_scatter_gather_groups);
EXPECT_THAT(module->entry_computation()->root_instruction(),
GmockMatch(m::Bitcast(all_gather1).WithShape(F32, {4, 4})));
}
TEST_F(AllReduceBlueConnectTest, TwoOperands) {
constexpr absl::string_view hlo_string = R"(
HloModule module
%add {
lhs = f32[] parameter(0)
rhs = f32[] parameter(1)
ROOT add = f32[] add(lhs, rhs)
}
ENTRY %comp {
p0 = f32[4,4] parameter(0)
p1 = f32[4,4,2] parameter(1)
ROOT crs = (f32[4,4], f32[4,4,2]) all-reduce(p0, p1), to_apply=add
})";
TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> module,
ParseAndReturnVerifiedModule(hlo_string));
SetModuleConfig(*module, 8);
AllReduceBlueConnect pass(4);
EXPECT_THAT(pass.Run(module.get()), IsOkAndHolds(true));
std::vector<std::vector<int64_t>> scatter_gather_groups = {
{0, 1, 2, 3}, {4, 5, 6, 7}};
std::vector<std::vector<int64_t>> new_all_reduce_groups = {
{0, 4}, {1, 5}, {2, 6}, {3, 7}};
auto bitcast0 = m::Bitcast(m::Parameter(0)).WithShape(F32, {16});
auto bitcast1 = m::Bitcast(m::Parameter(1)).WithShape(F32, {32});
Shape expected0 = ShapeUtil::MakeTupleShape(
{ShapeUtil::MakeShape(F32, {4}), ShapeUtil::MakeShape(F32, {8})});
Shape expected1 = ShapeUtil::MakeTupleShape(
{ShapeUtil::MakeShape(F32, {16}), ShapeUtil::MakeShape(F32, {32})});
auto reduce_scatter = m::ReduceScatter(bitcast0, bitcast1)
.WithShapeEqualTo(&expected0)
.WithReplicaGroups(scatter_gather_groups);
auto all_reduce = m::AllReduce(m::GetTupleElement(reduce_scatter, 0),
m::GetTupleElement(reduce_scatter, 1))
.WithShapeEqualTo(&expected0)
.WithReplicaGroups(new_all_reduce_groups);
auto all_gather = m::AllGather(m::GetTupleElement(all_reduce, 0),
m::GetTupleElement(all_reduce, 1))
.WithShapeEqualTo(&expected1)
.WithReplicaGroups(scatter_gather_groups);
auto bitcast2 =
m::Bitcast(m::GetTupleElement(all_gather, 0)).WithShape(F32, {4, 4});
auto bitcast3 =
m::Bitcast(m::GetTupleElement(all_gather, 1)).WithShape(F32, {4, 4, 2});
EXPECT_THAT(module->entry_computation()->root_instruction(),
GmockMatch(m::Tuple(bitcast2, bitcast3)));
}
TEST_F(AllReduceBlueConnectTest, DifferentNumLocalDevicesWithinReplicaGroup) {
constexpr absl::string_view hlo_string = R"(
HloModule module
%add {
lhs = f32[] parameter(0)
rhs = f32[] parameter(1)
ROOT add = f32[] add(lhs, rhs)
}
ENTRY %comp {
p0 = f32[4,4] parameter(0)
ROOT crs = f32[4,4] all-reduce(p0),
replica_groups={{0,1,2,7},{3,4,5,6}}, to_apply=add
})";
TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> module,
ParseAndReturnVerifiedModule(hlo_string));
SetModuleConfig(*module, 8);
AllReduceBlueConnect pass(4);
EXPECT_THAT(pass.Run(module.get()), IsOkAndHolds(false));
}
TEST_F(AllReduceBlueConnectTest, DifferentNumLocalDevicesAcrossReplicaGroups) {
constexpr absl::string_view hlo_string = R"(
HloModule module
%add {
lhs = f32[] parameter(0)
rhs = f32[] parameter(1)
ROOT add = f32[] add(lhs, rhs)
}
ENTRY %comp {
p0 = f32[4,4] parameter(0)
ROOT crs = f32[4,4] all-reduce(p0),
replica_groups={{0,1,4,5},{2,3,6,7},{8,9,10,11},{12,13,14,15}}, to_apply=add
})";
TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> module,
ParseAndReturnVerifiedModule(hlo_string));
SetModuleConfig(*module, 16);
AllReduceBlueConnect pass(4);
EXPECT_THAT(pass.Run(module.get()), IsOkAndHolds(false));
}
TEST_F(AllReduceBlueConnectTest, OperandIndivisible) {
constexpr absl::string_view hlo_string = R"(
HloModule module
%add {
lhs = f32[] parameter(0)
rhs = f32[] parameter(1)
ROOT add = f32[] add(lhs, rhs)
}
ENTRY %comp {
p0 = f32[4,4] parameter(0)
p1 = f32[9] parameter(1)
ROOT crs = (f32[4,4], f32[9]) all-reduce(p0, p1), to_apply=add
})";
TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> module,
ParseAndReturnVerifiedModule(hlo_string));
SetModuleConfig(*module, 8);
AllReduceBlueConnect pass(4);
EXPECT_THAT(pass.Run(module.get()), IsOkAndHolds(false));
}
TEST_F(AllReduceBlueConnectTest, ControlDeps) {
constexpr absl::string_view hlo_string = R"(
HloModule module
%add {
lhs = f32[] parameter(0)
rhs = f32[] parameter(1)
ROOT add = f32[] add(lhs, rhs)
}
ENTRY %comp {
p0 = f32[4,4] parameter(0)
p1 = f32[4,4] parameter(1)
add = f32[4,4] add(p0, p1)
crs = f32[4,4] all-reduce(p0), to_apply=add, control-predecessors={add}
ROOT add1 = f32[4,4] add(crs, add), control-predecessors={crs}
})";
TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> module,
ParseAndReturnVerifiedModule(hlo_string));
SetModuleConfig(*module, 8);
const HloInstruction* ar =
module->entry_computation()->root_instruction()->operand(0);
auto expected_preds = ar->control_predecessors();
auto expected_succs = ar->control_successors();
AllReduceBlueConnect pass(4);
EXPECT_THAT(pass.Run(module.get()), IsOkAndHolds(true));
std::vector<std::vector<int64_t>> scatter_gather_groups = {
{0, 1, 2, 3}, {4, 5, 6, 7}};
std::vector<std::vector<int64_t>> new_all_reduce_groups = {
{0, 4}, {1, 5}, {2, 6}, {3, 7}};
const HloInstruction *matched_rs, *matched_bitcast;
auto bitcast = m::Bitcast(m::Parameter(0)).WithShape(F32, {16});
auto reduce_scatter = m::ReduceScatter(&matched_rs, bitcast)
.WithShape(F32, {4})
.WithReplicaGroups(scatter_gather_groups);
auto all_reduce = m::AllReduce(reduce_scatter)
.WithShape(F32, {4})
.WithReplicaGroups(new_all_reduce_groups);
auto all_gather = m::AllGather(all_reduce)
.WithShape(F32, {16})
.WithReplicaGroups(scatter_gather_groups);
HloInstruction* root = module->entry_computation()->root_instruction();
ASSERT_THAT(root, GmockMatch(m::Add()));
EXPECT_THAT(
root->operand(0),
GmockMatch(
m::Bitcast(&matched_bitcast, all_gather).WithShape(F32, {4, 4})));
EXPECT_THAT(matched_rs, GmockMatch(m::Op().WithControlDeps(
absl::MakeSpan(expected_preds), {})));
EXPECT_THAT(matched_bitcast, GmockMatch(m::Op().WithControlDeps(
{}, absl::MakeSpan(expected_succs))));
}
}
} |
397 | #ifndef TENSORFLOW_COMPILER_MLIR_QUANTIZATION_STABLEHLO_CC_CALIBRATION_REPRESENTATIVE_DATASET_H_
#define TENSORFLOW_COMPILER_MLIR_QUANTIZATION_STABLEHLO_CC_CALIBRATION_REPRESENTATIVE_DATASET_H_
#include <string>
#include "absl/container/flat_hash_map.h"
#include "absl/status/statusor.h"
#include "absl/types/span.h"
#include "tensorflow/compiler/mlir/quantization/stablehlo/quantization_config.pb.h"
#include "tensorflow/compiler/mlir/quantization/tensorflow/quantization_options.pb.h"
namespace stablehlo::quantization {
absl::StatusOr<absl::flat_hash_map<
std::string, tensorflow::quantization::RepresentativeDatasetFile>>
CreateRepresentativeDatasetFileMap(absl::Span<const RepresentativeDatasetConfig>
representative_dataset_configs);
}
#endif
#include "tensorflow/compiler/mlir/quantization/stablehlo/cc/calibration/representative_dataset.h"
#include <string>
#include <utility>
#include "absl/container/flat_hash_map.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/str_cat.h"
#include "absl/types/span.h"
#include "tensorflow/compiler/mlir/quantization/stablehlo/quantization_config.pb.h"
#include "tensorflow/compiler/mlir/quantization/tensorflow/quantization_options.pb.h"
namespace stablehlo::quantization {
using ::tensorflow::quantization::RepresentativeDatasetFile;
absl::StatusOr<absl::flat_hash_map<std::string, RepresentativeDatasetFile>>
CreateRepresentativeDatasetFileMap(absl::Span<const RepresentativeDatasetConfig>
representative_dataset_configs) {
absl::flat_hash_map<std::string, RepresentativeDatasetFile>
repr_dataset_file_map{};
for (const RepresentativeDatasetConfig& dataset_config :
representative_dataset_configs) {
RepresentativeDatasetFile repr_dataset_file;
repr_dataset_file.set_tfrecord_file_path(dataset_config.tf_record().path());
const std::string signature_key = dataset_config.has_signature_key()
? dataset_config.signature_key()
: "serving_default";
if (repr_dataset_file_map.contains(signature_key)) {
return absl::InvalidArgumentError(
absl::StrCat("RepresentativeDatasetConfig should not contain "
"duplicate signature key: ",
signature_key));
}
repr_dataset_file_map[signature_key] = std::move(repr_dataset_file);
}
return repr_dataset_file_map;
}
} | #include "tensorflow/compiler/mlir/quantization/stablehlo/cc/calibration/representative_dataset.h"
#include <string>
#include <vector>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "absl/container/flat_hash_map.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "tensorflow/compiler/mlir/quantization/stablehlo/quantization_config.pb.h"
#include "tsl/platform/status_matchers.h"
namespace mlir::quant::stablehlo {
namespace {
using ::stablehlo::quantization::RepresentativeDatasetConfig;
using ::tensorflow::quantization::RepresentativeDatasetFile;
using ::testing::Contains;
using ::testing::HasSubstr;
using ::testing::Key;
using ::testing::SizeIs;
using ::testing::StrEq;
using ::tsl::testing::IsOk;
using ::tsl::testing::StatusIs;
TEST(CreateRepresentativeDatasetFileMapTest,
ConfigWithoutExplicitSignatureKeyMappedToServingDefault) {
std::vector<RepresentativeDatasetConfig> representative_dataset_configs;
RepresentativeDatasetConfig config{};
*(config.mutable_tf_record()->mutable_path()) = "test_path";
representative_dataset_configs.push_back(config);
const absl::StatusOr<
absl::flat_hash_map<std::string, RepresentativeDatasetFile>>
representative_dataset_file_map =
CreateRepresentativeDatasetFileMap(representative_dataset_configs);
ASSERT_THAT(representative_dataset_file_map, IsOk());
ASSERT_THAT(*representative_dataset_file_map, SizeIs(1));
EXPECT_THAT(*representative_dataset_file_map,
Contains(Key("serving_default")));
EXPECT_THAT(representative_dataset_file_map->at("serving_default")
.tfrecord_file_path(),
StrEq("test_path"));
}
TEST(CreateRepresentativeDatasetFileMapTest, ConfigWithExplicitSignatureKey) {
std::vector<RepresentativeDatasetConfig> representative_dataset_configs;
RepresentativeDatasetConfig config{};
config.set_signature_key("test_signature_key");
*(config.mutable_tf_record()->mutable_path()) = "test_path";
representative_dataset_configs.push_back(config);
const absl::StatusOr<
absl::flat_hash_map<std::string, RepresentativeDatasetFile>>
representative_dataset_file_map =
CreateRepresentativeDatasetFileMap(representative_dataset_configs);
ASSERT_THAT(representative_dataset_file_map, IsOk());
ASSERT_THAT(*representative_dataset_file_map, SizeIs(1));
EXPECT_THAT(*representative_dataset_file_map,
Contains(Key(StrEq("test_signature_key"))));
EXPECT_THAT(representative_dataset_file_map->at("test_signature_key")
.tfrecord_file_path(),
StrEq("test_path"));
}
TEST(CreateRepresentativeDatasetFileMapTest,
ConfigWithDuplicateSignatureKeyReturnsInvalidArgumentError) {
std::vector<RepresentativeDatasetConfig> representative_dataset_configs;
RepresentativeDatasetConfig config_1{};
config_1.set_signature_key("serving_default");
*(config_1.mutable_tf_record()->mutable_path()) = "test_path_1";
representative_dataset_configs.push_back(config_1);
RepresentativeDatasetConfig config_2{};
*(config_2.mutable_tf_record()->mutable_path()) = "test_path_2";
representative_dataset_configs.push_back(config_2);
const absl::StatusOr<
absl::flat_hash_map<std::string, RepresentativeDatasetFile>>
representative_dataset_file_map =
CreateRepresentativeDatasetFileMap(representative_dataset_configs);
EXPECT_THAT(representative_dataset_file_map,
StatusIs(absl::StatusCode::kInvalidArgument,
HasSubstr("duplicate signature key: serving_default")));
}
}
} |
398 | #ifndef XLA_SERVICE_GPU_RUNTIME_COPY_THUNK_H_
#define XLA_SERVICE_GPU_RUNTIME_COPY_THUNK_H_
#include <cstdint>
#include <memory>
#include <utility>
#include "absl/base/thread_annotations.h"
#include "absl/container/flat_hash_map.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/synchronization/mutex.h"
#include "xla/hlo/ir/hlo_instruction.h"
#include "xla/service/buffer_assignment.h"
#include "xla/service/gpu/runtime/thunk.h"
#include "xla/stream_executor/event.h"
#include "xla/stream_executor/stream_executor.h"
namespace xla {
namespace gpu {
class DeviceToDeviceCopyThunk : public Thunk {
public:
DeviceToDeviceCopyThunk(ThunkInfo thunk_info,
const BufferAllocation::Slice& source_buffer,
const BufferAllocation::Slice& destination_buffer,
uint64_t mem_size);
DeviceToDeviceCopyThunk(const DeviceToDeviceCopyThunk&) = delete;
DeviceToDeviceCopyThunk& operator=(const DeviceToDeviceCopyThunk&) = delete;
absl::Status ExecuteOnStream(const ExecuteParams& params) override;
const BufferAllocation::Slice& source() const { return source_buffer_; }
const BufferAllocation::Slice& destination() const {
return destination_buffer_;
}
uint64_t size_bytes() const { return mem_size_; }
private:
const BufferAllocation::Slice source_buffer_;
const BufferAllocation::Slice destination_buffer_;
const uint64_t mem_size_;
};
class CopyThunk : public Thunk {
public:
class AsyncEvents {
public:
absl::Status Emplace(se::StreamExecutor* executor,
const HloInstruction* instr,
std::unique_ptr<se::Event> event);
absl::StatusOr<std::unique_ptr<se::Event>> Extract(
se::StreamExecutor* executor, const HloInstruction* instr);
private:
using Key = std::pair<se::StreamExecutor*, const HloInstruction*>;
absl::Mutex mutex_;
absl::flat_hash_map<Key, std::unique_ptr<se::Event>> events_
ABSL_GUARDED_BY(mutex_);
};
CopyThunk(ThunkInfo thunk_info, const BufferAllocation::Slice& source_buffer,
const BufferAllocation::Slice& destination_buffer,
uint64_t mem_size);
absl::Status ExecuteOnStream(const ExecuteParams& params) override;
const BufferAllocation::Slice& source() const { return source_buffer_; }
const BufferAllocation::Slice& destination() const {
return destination_buffer_;
}
uint64_t size_bytes() const { return mem_size_; }
private:
const BufferAllocation::Slice source_buffer_;
const BufferAllocation::Slice destination_buffer_;
const uint64_t mem_size_;
};
class DeviceToHostCopyThunk : public CopyThunk {
public:
DeviceToHostCopyThunk(ThunkInfo thunk_info,
const BufferAllocation::Slice& source_buffer,
const BufferAllocation::Slice& destination_buffer,
uint64_t mem_size,
std::shared_ptr<CopyThunk::AsyncEvents> events,
const HloInstruction* instr);
absl::Status ExecuteOnStream(const ExecuteParams& params) override;
private:
std::shared_ptr<CopyThunk::AsyncEvents> async_events_;
const HloInstruction* instr_;
};
class HostToDeviceCopyThunk : public CopyThunk {
public:
HostToDeviceCopyThunk(ThunkInfo thunk_info,
const BufferAllocation::Slice& source_buffer,
const BufferAllocation::Slice& destination_buffer,
uint64_t mem_size,
std::shared_ptr<CopyThunk::AsyncEvents> events,
const HloInstruction* instr);
absl::Status ExecuteOnStream(const ExecuteParams& params) override;
private:
std::shared_ptr<CopyThunk::AsyncEvents> async_events_;
const HloInstruction* instr_;
};
class CopyDoneThunk : public Thunk {
public:
CopyDoneThunk(Thunk::Kind kind, ThunkInfo thunk_info,
std::shared_ptr<CopyThunk::AsyncEvents> events,
const HloInstruction* copy_start_instr);
absl::Status ExecuteOnStream(const ExecuteParams& params) override;
private:
std::shared_ptr<CopyThunk::AsyncEvents> async_events_;
const HloInstruction* copy_start_instr_;
};
}
}
#endif
#include "xla/service/gpu/runtime/copy_thunk.h"
#include <cstdint>
#include <memory>
#include <utility>
#include "absl/log/log.h"
#include "absl/status/status.h"
#include "absl/synchronization/mutex.h"
#include "xla/hlo/ir/hlo_instruction.h"
#include "xla/service/buffer_assignment.h"
#include "xla/service/gpu/runtime/thunk.h"
#include "xla/stream_executor/device_memory.h"
#include "xla/stream_executor/event.h"
#include "xla/stream_executor/stream_executor.h"
#include "tsl/platform/errors.h"
#include "tsl/platform/statusor.h"
namespace xla {
namespace gpu {
DeviceToDeviceCopyThunk::DeviceToDeviceCopyThunk(
ThunkInfo thunk_info, const BufferAllocation::Slice& source_buffer,
const BufferAllocation::Slice& destination_buffer, uint64_t mem_size)
: Thunk(Kind::kCopy, std::move(thunk_info)),
source_buffer_(source_buffer),
destination_buffer_(destination_buffer),
mem_size_(mem_size) {}
absl::Status DeviceToDeviceCopyThunk::ExecuteOnStream(
const ExecuteParams& params) {
se::DeviceMemoryBase destination_data =
params.buffer_allocations->GetDeviceAddress(destination_buffer_);
se::DeviceMemoryBase source_data =
params.buffer_allocations->GetDeviceAddress(source_buffer_);
VLOG(3) << "Memcpy D2D of size " << mem_size_ << " from "
<< source_data.opaque() << " to " << destination_data.opaque();
return params.stream->Memcpy(&destination_data, source_data, mem_size_);
}
CopyThunk::CopyThunk(ThunkInfo thunk_info,
const BufferAllocation::Slice& source_buffer,
const BufferAllocation::Slice& destination_buffer,
uint64_t mem_size)
: Thunk(Kind::kCopy, std::move(thunk_info)),
source_buffer_(source_buffer),
destination_buffer_(destination_buffer),
mem_size_(mem_size) {}
absl::Status CopyThunk::ExecuteOnStream(const ExecuteParams& params) {
return absl::OkStatus();
}
absl::Status CopyThunk::AsyncEvents::Emplace(se::StreamExecutor* executor,
const HloInstruction* instr,
std::unique_ptr<se::Event> event) {
Key key = {executor, instr};
absl::MutexLock lock(&mutex_);
VLOG(3) << "Emplace event " << event.get();
if (auto [it, inserted] = events_.try_emplace(key, std::move(event));
inserted) {
return absl::OkStatus();
}
return absl::InternalError("Async copy event already exists!");
}
absl::StatusOr<std::unique_ptr<se::Event>> CopyThunk::AsyncEvents::Extract(
se::StreamExecutor* executor, const HloInstruction* instr) {
Key key = {executor, instr};
absl::MutexLock lock(&mutex_);
if (auto event = events_.extract(key)) {
VLOG(3) << "Extract event " << event.mapped().get();
return std::move(event.mapped());
}
return absl::InternalError("Async copy event was not found!");
}
DeviceToHostCopyThunk::DeviceToHostCopyThunk(
ThunkInfo thunk_info, const BufferAllocation::Slice& source_buffer,
const BufferAllocation::Slice& destination_buffer, uint64_t mem_size,
std::shared_ptr<CopyThunk::AsyncEvents> async_events,
const HloInstruction* instr)
: CopyThunk(std::move(thunk_info), source_buffer, destination_buffer,
mem_size),
async_events_(std::move(async_events)),
instr_(instr) {}
absl::Status DeviceToHostCopyThunk::ExecuteOnStream(
const ExecuteParams& params) {
se::DeviceMemoryBase destination_data =
params.buffer_allocations->GetDeviceAddress(destination());
se::DeviceMemoryBase source_data =
params.buffer_allocations->GetDeviceAddress(source());
void* cpu_dst = destination_data.opaque();
TF_ASSIGN_OR_RETURN(
se::Stream * stream,
GetStreamForExecution(Thunk::execution_stream_id(), params));
TF_RETURN_IF_ERROR(stream->Memcpy(cpu_dst, source_data, size_bytes()));
if (stream == params.stream) {
VLOG(2) << "Memcpy D2H from the main stream";
return absl::OkStatus();
}
VLOG(2) << "Memcpy D2H from the other stream";
se::StreamExecutor* executor = params.stream->parent();
TF_ASSIGN_OR_RETURN(auto event, executor->CreateEvent());
TF_RETURN_IF_ERROR(stream->RecordEvent(event.get()));
VLOG(3) << "Emplace events: " << event.get()
<< " for instr: " << instr_->ToString();
return async_events_->Emplace(executor, instr_, std::move(event));
}
HostToDeviceCopyThunk::HostToDeviceCopyThunk(
ThunkInfo thunk_info, const BufferAllocation::Slice& source_buffer,
const BufferAllocation::Slice& destination_buffer, uint64_t mem_size,
std::shared_ptr<CopyThunk::AsyncEvents> async_events,
const HloInstruction* instr)
: CopyThunk(std::move(thunk_info), source_buffer, destination_buffer,
mem_size),
async_events_(std::move(async_events)),
instr_(instr) {}
absl::Status HostToDeviceCopyThunk::ExecuteOnStream(
const ExecuteParams& params) {
se::DeviceMemoryBase destination_data =
params.buffer_allocations->GetDeviceAddress(destination());
se::DeviceMemoryBase source_data =
params.buffer_allocations->GetDeviceAddress(source());
void* cpu_src = source_data.opaque();
TF_ASSIGN_OR_RETURN(
se::Stream * stream,
GetStreamForExecution(Thunk::execution_stream_id(), params));
TF_RETURN_IF_ERROR(stream->Memcpy(&destination_data, cpu_src, size_bytes()));
if (stream == params.stream) {
VLOG(2) << "Memcpy H2D from the main stream";
return absl::OkStatus();
}
VLOG(2) << "Memcpy H2D from the other stream";
se::StreamExecutor* executor = params.stream->parent();
TF_ASSIGN_OR_RETURN(auto event, executor->CreateEvent());
TF_RETURN_IF_ERROR(stream->RecordEvent(event.get()));
VLOG(3) << "Emplace events: " << event.get()
<< " for instr: " << instr_->ToString();
return async_events_->Emplace(executor, instr_, std::move(event));
}
CopyDoneThunk::CopyDoneThunk(
Thunk::Kind kind, ThunkInfo thunk_info,
std::shared_ptr<CopyThunk::AsyncEvents> async_events,
const HloInstruction* copy_start_instr)
: Thunk(kind, std::move(thunk_info)),
async_events_(std::move(async_events)),
copy_start_instr_(copy_start_instr) {}
absl::Status CopyDoneThunk::ExecuteOnStream(const ExecuteParams& params) {
VLOG(3) << "CopyDone thunk between a host and a device for: "
<< copy_start_instr_->ToString();
se::StreamExecutor* executor = params.stream->parent();
TF_ASSIGN_OR_RETURN(std::unique_ptr<se::Event> event,
async_events_->Extract(executor, copy_start_instr_));
return params.stream->WaitFor(event.get());
}
}
} | #include "xla/service/cpu/runtime/copy_thunk.h"
#include <cstddef>
#include <vector>
#include "xla/layout_util.h"
#include "xla/service/buffer_assignment.h"
#include "xla/service/cpu/runtime/buffer_allocations.h"
#include "xla/service/cpu/runtime/thunk.h"
#include "xla/service/maybe_owning_device_memory.h"
#include "xla/shape.h"
#include "xla/shape_util.h"
#include "xla/stream_executor/device_memory.h"
#include "xla/tsl/concurrency/async_value_ref.h"
#include "tsl/lib/core/status_test_util.h"
#include "tsl/platform/statusor.h"
#include "tsl/platform/test.h"
namespace xla::cpu {
namespace {
TEST(CopyThunkTest, CopySameShape) {
std::vector<MaybeOwningDeviceMemory> buffers;
std::vector<float> src = {1.0, 2.0, 3.0, 4.0};
std::vector<float> dst(4, 0.0);
size_t size_in_bytes = src.size() * sizeof(float);
buffers.emplace_back(se::DeviceMemoryBase(src.data(), size_in_bytes));
buffers.emplace_back(se::DeviceMemoryBase(dst.data(), size_in_bytes));
BufferAllocations allocations(buffers);
BufferAllocation src_alloc(0, size_in_bytes, 0);
BufferAllocation dst_alloc(1, size_in_bytes, 0);
BufferAllocation::Slice src_slice(&src_alloc, 0, size_in_bytes);
BufferAllocation::Slice dst_slice(&dst_alloc, 0, size_in_bytes);
Shape shape = ShapeUtil::MakeShape(F32, {2, 2});
TF_ASSERT_OK_AND_ASSIGN(
auto thunk,
CopyThunk::Create({"copy"}, src_slice, shape, dst_slice, shape));
Thunk::ExecuteParams params = {nullptr, &allocations};
auto execute_event = thunk->Execute(params);
tsl::BlockUntilReady(execute_event);
ASSERT_FALSE(execute_event.IsError());
EXPECT_EQ(src, dst);
}
TEST(CopyThunkTest, CopyTransposed) {
std::vector<MaybeOwningDeviceMemory> buffers;
std::vector<float> src = {1.0, 2.0, 3.0, 4.0};
std::vector<float> dst(4, 0.0);
size_t size_in_bytes = src.size() * sizeof(float);
buffers.emplace_back(se::DeviceMemoryBase(src.data(), size_in_bytes));
buffers.emplace_back(se::DeviceMemoryBase(dst.data(), size_in_bytes));
BufferAllocations allocations(buffers);
BufferAllocation src_alloc(0, size_in_bytes, 0);
BufferAllocation dst_alloc(1, size_in_bytes, 0);
BufferAllocation::Slice src_slice(&src_alloc, 0, size_in_bytes);
BufferAllocation::Slice dst_slice(&dst_alloc, 0, size_in_bytes);
Shape src_shape = ShapeUtil::MakeShape(F32, {2, 2});
*src_shape.mutable_layout() = LayoutUtil::MakeLayout({0, 1});
Shape dst_shape = ShapeUtil::MakeShape(F32, {2, 2});
TF_ASSERT_OK_AND_ASSIGN(
auto thunk,
CopyThunk::Create({"copy"}, src_slice, src_shape, dst_slice, dst_shape));
Thunk::ExecuteParams params = {nullptr, &allocations};
auto execute_event = thunk->Execute(params);
tsl::BlockUntilReady(execute_event);
ASSERT_FALSE(execute_event.IsError());
std::vector<float> expected = {1.0, 3.0, 2.0, 4.0};
EXPECT_EQ(expected, dst);
}
}
} |
399 | #include "gmock/internal/gmock-internal-utils.h"
#include <ctype.h>
#include <array>
#include <cctype>
#include <cstdint>
#include <cstring>
#include <iostream>
#include <ostream>
#include <string>
#include <utility>
#include <vector>
#include "gmock/gmock.h"
#include "gmock/internal/gmock-port.h"
#include "gtest/gtest.h"
namespace testing {
namespace internal {
GTEST_API_ std::string JoinAsKeyValueTuple(
const std::vector<const char*>& names, const Strings& values) {
GTEST_CHECK_(names.size() == values.size());
if (values.empty()) {
return "";
}
const auto build_one = [&](const size_t i) {
return std::string(names[i]) + ": " + values[i];
};
std::string result = "(" + build_one(0);
for (size_t i = 1; i < values.size(); i++) {
result += ", ";
result += build_one(i);
}
result += ")";
return result;
}
GTEST_API_ std::string ConvertIdentifierNameToWords(const char* id_name) {
std::string result;
char prev_char = '\0';
for (const char* p = id_name; *p != '\0'; prev_char = *(p++)) {
const bool starts_new_word = IsUpper(*p) ||
(!IsAlpha(prev_char) && IsLower(*p)) ||
(!IsDigit(prev_char) && IsDigit(*p));
if (IsAlNum(*p)) {
if (starts_new_word && !result.empty()) result += ' ';
result += ToLower(*p);
}
}
return result;
}
class GoogleTestFailureReporter : public FailureReporterInterface {
public:
void ReportFailure(FailureType type, const char* file, int line,
const std::string& message) override {
AssertHelper(type == kFatal ? TestPartResult::kFatalFailure
: TestPartResult::kNonFatalFailure,
file, line, message.c_str()) = Message();
if (type == kFatal) {
posix::Abort();
}
}
};
GTEST_API_ FailureReporterInterface* GetFailureReporter() {
static FailureReporterInterface* const failure_reporter =
new GoogleTestFailureReporter();
return failure_reporter;
}
static GTEST_DEFINE_STATIC_MUTEX_(g_log_mutex);
GTEST_API_ bool LogIsVisible(LogSeverity severity) {
if (GMOCK_FLAG_GET(verbose) == kInfoVerbosity) {
return true;
} else if (GMOCK_FLAG_GET(verbose) == kErrorVerbosity) {
return false;
} else {
return severity == kWarning;
}
}
GTEST_API_ void Log(LogSeverity severity, const std::string& message,
int stack_frames_to_skip) {
if (!LogIsVisible(severity)) return;
MutexLock l(&g_log_mutex);
if (severity == kWarning) {
std::cout << "\nGMOCK WARNING:";
}
if (message.empty() || message[0] != '\n') {
std::cout << "\n";
}
std::cout << message;
if (stack_frames_to_skip >= 0) {
#ifdef NDEBUG
const int actual_to_skip = 0;
#else
const int actual_to_skip = stack_frames_to_skip + 1;
#endif
if (!message.empty() && *message.rbegin() != '\n') {
std::cout << "\n";
}
std::cout << "Stack trace:\n"
<< ::testing::internal::GetCurrentOsStackTraceExceptTop(
actual_to_skip);
}
std::cout << ::std::flush;
}
GTEST_API_ WithoutMatchers GetWithoutMatchers() { return WithoutMatchers(); }
GTEST_API_ void IllegalDoDefault(const char* file, int line) {
internal::Assert(
false, file, line,
"You are using DoDefault() inside a composite action like "
"DoAll() or WithArgs(). This is not supported for technical "
"reasons. Please instead spell out the default action, or "
"assign the default action to an Action variable and use "
"the variable in various places.");
}
constexpr char UndoWebSafeEncoding(char c) {
return c == '-' ? '+' : c == '_' ? '/' : c;
}
constexpr char UnBase64Impl(char c, const char* const base64, char carry) {
return *base64 == 0 ? static_cast<char>(65)
: *base64 == c
? carry
: UnBase64Impl(c, base64 + 1, static_cast<char>(carry + 1));
}
template <size_t... I>
constexpr std::array<char, 256> UnBase64Impl(std::index_sequence<I...>,
const char* const base64) {
return {
{UnBase64Impl(UndoWebSafeEncoding(static_cast<char>(I)), base64, 0)...}};
}
constexpr std::array<char, 256> UnBase64(const char* const base64) {
return UnBase64Impl(std::make_index_sequence<256>{}, base64);
}
static constexpr char kBase64[] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
static constexpr std::array<char, 256> kUnBase64 = UnBase64(kBase64);
bool Base64Unescape(const std::string& encoded, std::string* decoded) {
decoded->clear();
size_t encoded_len = encoded.size();
decoded->reserve(3 * (encoded_len / 4) + (encoded_len % 4));
int bit_pos = 0;
char dst = 0;
for (int src : encoded) {
if (std::isspace(src) || src == '=') {
continue;
}
char src_bin = kUnBase64[static_cast<size_t>(src)];
if (src_bin >= 64) {
decoded->clear();
return false;
}
if (bit_pos == 0) {
dst |= static_cast<char>(src_bin << 2);
bit_pos = 6;
} else {
dst |= static_cast<char>(src_bin >> (bit_pos - 2));
decoded->push_back(dst);
dst = static_cast<char>(src_bin << (10 - bit_pos));
bit_pos = (bit_pos + 6) % 8;
}
}
return true;
}
}
} | #include "gmock/internal/gmock-internal-utils.h"
#include <stdlib.h>
#include <cstdint>
#include <map>
#include <memory>
#include <sstream>
#include <string>
#include <tuple>
#include <vector>
#include "gmock/gmock.h"
#include "gmock/internal/gmock-port.h"
#include "gtest/gtest-spi.h"
#include "gtest/gtest.h"
#define GTEST_IMPLEMENTATION_ 1
#include "src/gtest-internal-inl.h"
#undef GTEST_IMPLEMENTATION_
#ifdef GTEST_OS_CYGWIN
#include <sys/types.h>
#endif
namespace proto2 {
class Message;
}
namespace testing {
namespace internal {
namespace {
TEST(JoinAsKeyValueTupleTest, JoinsEmptyTuple) {
EXPECT_EQ("", JoinAsKeyValueTuple({}, Strings()));
}
TEST(JoinAsKeyValueTupleTest, JoinsOneTuple) {
EXPECT_EQ("(a: 1)", JoinAsKeyValueTuple({"a"}, {"1"}));
}
TEST(JoinAsKeyValueTupleTest, JoinsTwoTuple) {
EXPECT_EQ("(a: 1, b: 2)", JoinAsKeyValueTuple({"a", "b"}, {"1", "2"}));
}
TEST(JoinAsKeyValueTupleTest, JoinsTenTuple) {
EXPECT_EQ(
"(a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: 8, i: 9, j: 10)",
JoinAsKeyValueTuple({"a", "b", "c", "d", "e", "f", "g", "h", "i", "j"},
{"1", "2", "3", "4", "5", "6", "7", "8", "9", "10"}));
}
TEST(ConvertIdentifierNameToWordsTest, WorksWhenNameContainsNoWord) {
EXPECT_EQ("", ConvertIdentifierNameToWords(""));
EXPECT_EQ("", ConvertIdentifierNameToWords("_"));
EXPECT_EQ("", ConvertIdentifierNameToWords("__"));
}
TEST(ConvertIdentifierNameToWordsTest, WorksWhenNameContainsDigits) {
EXPECT_EQ("1", ConvertIdentifierNameToWords("_1"));
EXPECT_EQ("2", ConvertIdentifierNameToWords("2_"));
EXPECT_EQ("34", ConvertIdentifierNameToWords("_34_"));
EXPECT_EQ("34 56", ConvertIdentifierNameToWords("_34_56"));
}
TEST(ConvertIdentifierNameToWordsTest, WorksWhenNameContainsCamelCaseWords) {
EXPECT_EQ("a big word", ConvertIdentifierNameToWords("ABigWord"));
EXPECT_EQ("foo bar", ConvertIdentifierNameToWords("FooBar"));
EXPECT_EQ("foo", ConvertIdentifierNameToWords("Foo_"));
EXPECT_EQ("foo bar", ConvertIdentifierNameToWords("_Foo_Bar_"));
EXPECT_EQ("foo and bar", ConvertIdentifierNameToWords("_Foo__And_Bar"));
}
TEST(ConvertIdentifierNameToWordsTest, WorksWhenNameContains_SeparatedWords) {
EXPECT_EQ("foo bar", ConvertIdentifierNameToWords("foo_bar"));
EXPECT_EQ("foo", ConvertIdentifierNameToWords("_foo_"));
EXPECT_EQ("foo bar", ConvertIdentifierNameToWords("_foo_bar_"));
EXPECT_EQ("foo and bar", ConvertIdentifierNameToWords("_foo__and_bar"));
}
TEST(ConvertIdentifierNameToWordsTest, WorksWhenNameIsMixture) {
EXPECT_EQ("foo bar 123", ConvertIdentifierNameToWords("Foo_bar123"));
EXPECT_EQ("chapter 11 section 1",
ConvertIdentifierNameToWords("_Chapter11Section_1_"));
}
TEST(GetRawPointerTest, WorksForSmartPointers) {
const char* const raw_p1 = new const char('a');
const std::unique_ptr<const char> p1(raw_p1);
EXPECT_EQ(raw_p1, GetRawPointer(p1));
double* const raw_p2 = new double(2.5);
const std::shared_ptr<double> p2(raw_p2);
EXPECT_EQ(raw_p2, GetRawPointer(p2));
}
TEST(GetRawPointerTest, WorksForRawPointers) {
int* p = nullptr;
EXPECT_TRUE(nullptr == GetRawPointer(p));
int n = 1;
EXPECT_EQ(&n, GetRawPointer(&n));
}
TEST(GetRawPointerTest, WorksForStdReferenceWrapper) {
int n = 1;
EXPECT_EQ(&n, GetRawPointer(std::ref(n)));
EXPECT_EQ(&n, GetRawPointer(std::cref(n)));
}
class Base {};
class Derived : public Base {};
TEST(KindOfTest, Bool) {
EXPECT_EQ(kBool, GMOCK_KIND_OF_(bool));
}
TEST(KindOfTest, Integer) {
EXPECT_EQ(kInteger, GMOCK_KIND_OF_(char));
EXPECT_EQ(kInteger, GMOCK_KIND_OF_(signed char));
EXPECT_EQ(kInteger, GMOCK_KIND_OF_(unsigned char));
EXPECT_EQ(kInteger, GMOCK_KIND_OF_(short));
EXPECT_EQ(kInteger, GMOCK_KIND_OF_(unsigned short));
EXPECT_EQ(kInteger, GMOCK_KIND_OF_(int));
EXPECT_EQ(kInteger, GMOCK_KIND_OF_(unsigned int));
EXPECT_EQ(kInteger, GMOCK_KIND_OF_(long));
EXPECT_EQ(kInteger, GMOCK_KIND_OF_(unsigned long));
EXPECT_EQ(kInteger, GMOCK_KIND_OF_(long long));
EXPECT_EQ(kInteger, GMOCK_KIND_OF_(unsigned long long));
EXPECT_EQ(kInteger, GMOCK_KIND_OF_(wchar_t));
EXPECT_EQ(kInteger, GMOCK_KIND_OF_(size_t));
#if defined(GTEST_OS_LINUX) || defined(GTEST_OS_MAC) || defined(GTEST_OS_CYGWIN)
EXPECT_EQ(kInteger, GMOCK_KIND_OF_(ssize_t));
#endif
}
TEST(KindOfTest, FloatingPoint) {
EXPECT_EQ(kFloatingPoint, GMOCK_KIND_OF_(float));
EXPECT_EQ(kFloatingPoint, GMOCK_KIND_OF_(double));
EXPECT_EQ(kFloatingPoint, GMOCK_KIND_OF_(long double));
}
TEST(KindOfTest, Other) {
EXPECT_EQ(kOther, GMOCK_KIND_OF_(void*));
EXPECT_EQ(kOther, GMOCK_KIND_OF_(char**));
EXPECT_EQ(kOther, GMOCK_KIND_OF_(Base));
}
TEST(LosslessArithmeticConvertibleTest, BoolToBool) {
EXPECT_TRUE((LosslessArithmeticConvertible<bool, bool>::value));
}
TEST(LosslessArithmeticConvertibleTest, BoolToInteger) {
EXPECT_TRUE((LosslessArithmeticConvertible<bool, char>::value));
EXPECT_TRUE((LosslessArithmeticConvertible<bool, int>::value));
EXPECT_TRUE(
(LosslessArithmeticConvertible<bool, unsigned long>::value));
}
TEST(LosslessArithmeticConvertibleTest, BoolToFloatingPoint) {
EXPECT_TRUE((LosslessArithmeticConvertible<bool, float>::value));
EXPECT_TRUE((LosslessArithmeticConvertible<bool, double>::value));
}
TEST(LosslessArithmeticConvertibleTest, IntegerToBool) {
EXPECT_FALSE((LosslessArithmeticConvertible<unsigned char, bool>::value));
EXPECT_FALSE((LosslessArithmeticConvertible<int, bool>::value));
}
TEST(LosslessArithmeticConvertibleTest, IntegerToInteger) {
EXPECT_TRUE((LosslessArithmeticConvertible<unsigned char, int>::value));
EXPECT_TRUE((LosslessArithmeticConvertible<unsigned short,
uint64_t>::value));
EXPECT_FALSE(
(LosslessArithmeticConvertible<short, uint64_t>::value));
EXPECT_FALSE((LosslessArithmeticConvertible<signed char,
unsigned int>::value));
EXPECT_TRUE(
(LosslessArithmeticConvertible<unsigned char, unsigned char>::value));
EXPECT_TRUE((LosslessArithmeticConvertible<int, int>::value));
EXPECT_TRUE((LosslessArithmeticConvertible<wchar_t, wchar_t>::value));
EXPECT_TRUE((LosslessArithmeticConvertible<unsigned long,
unsigned long>::value));
EXPECT_FALSE(
(LosslessArithmeticConvertible<unsigned char, signed char>::value));
EXPECT_FALSE((LosslessArithmeticConvertible<int, unsigned int>::value));
EXPECT_FALSE((LosslessArithmeticConvertible<uint64_t, int64_t>::value));
EXPECT_FALSE((LosslessArithmeticConvertible<long, char>::value));
EXPECT_FALSE((LosslessArithmeticConvertible<int, signed char>::value));
EXPECT_FALSE((LosslessArithmeticConvertible<int64_t, unsigned int>::value));
}
TEST(LosslessArithmeticConvertibleTest, IntegerToFloatingPoint) {
EXPECT_FALSE((LosslessArithmeticConvertible<char, float>::value));
EXPECT_FALSE((LosslessArithmeticConvertible<int, double>::value));
EXPECT_FALSE(
(LosslessArithmeticConvertible<short, long double>::value));
}
TEST(LosslessArithmeticConvertibleTest, FloatingPointToBool) {
EXPECT_FALSE((LosslessArithmeticConvertible<float, bool>::value));
EXPECT_FALSE((LosslessArithmeticConvertible<double, bool>::value));
}
TEST(LosslessArithmeticConvertibleTest, FloatingPointToInteger) {
EXPECT_FALSE((LosslessArithmeticConvertible<float, long>::value));
EXPECT_FALSE((LosslessArithmeticConvertible<double, int64_t>::value));
EXPECT_FALSE((LosslessArithmeticConvertible<long double, int>::value));
}
TEST(LosslessArithmeticConvertibleTest, FloatingPointToFloatingPoint) {
EXPECT_TRUE((LosslessArithmeticConvertible<float, double>::value));
EXPECT_TRUE((LosslessArithmeticConvertible<float, long double>::value));
EXPECT_TRUE((LosslessArithmeticConvertible<double, long double>::value));
EXPECT_TRUE((LosslessArithmeticConvertible<float, float>::value));
EXPECT_TRUE((LosslessArithmeticConvertible<double, double>::value));
EXPECT_FALSE((LosslessArithmeticConvertible<double, float>::value));
GTEST_INTENTIONAL_CONST_COND_PUSH_()
if (sizeof(double) == sizeof(long double)) {
GTEST_INTENTIONAL_CONST_COND_POP_()
EXPECT_TRUE((LosslessArithmeticConvertible<long double, double>::value));
} else {
EXPECT_FALSE((LosslessArithmeticConvertible<long double, double>::value));
}
}
TEST(TupleMatchesTest, WorksForSize0) {
std::tuple<> matchers;
std::tuple<> values;
EXPECT_TRUE(TupleMatches(matchers, values));
}
TEST(TupleMatchesTest, WorksForSize1) {
std::tuple<Matcher<int>> matchers(Eq(1));
std::tuple<int> values1(1), values2(2);
EXPECT_TRUE(TupleMatches(matchers, values1));
EXPECT_FALSE(TupleMatches(matchers, values2));
}
TEST(TupleMatchesTest, WorksForSize2) {
std::tuple<Matcher<int>, Matcher<char>> matchers(Eq(1), Eq('a'));
std::tuple<int, char> values1(1, 'a'), values2(1, 'b'), values3(2, 'a'),
values4(2, 'b');
EXPECT_TRUE(TupleMatches(matchers, values1));
EXPECT_FALSE(TupleMatches(matchers, values2));
EXPECT_FALSE(TupleMatches(matchers, values3));
EXPECT_FALSE(TupleMatches(matchers, values4));
}
TEST(TupleMatchesTest, WorksForSize5) {
std::tuple<Matcher<int>, Matcher<char>, Matcher<bool>,
Matcher<long>,
Matcher<std::string>>
matchers(Eq(1), Eq('a'), Eq(true), Eq(2L), Eq("hi"));
std::tuple<int, char, bool, long, std::string>
values1(1, 'a', true, 2L, "hi"), values2(1, 'a', true, 2L, "hello"),
values3(2, 'a', true, 2L, "hi");
EXPECT_TRUE(TupleMatches(matchers, values1));
EXPECT_FALSE(TupleMatches(matchers, values2));
EXPECT_FALSE(TupleMatches(matchers, values3));
}
TEST(AssertTest, SucceedsOnTrue) {
Assert(true, __FILE__, __LINE__, "This should succeed.");
Assert(true, __FILE__, __LINE__);
}
TEST(AssertTest, FailsFatallyOnFalse) {
EXPECT_DEATH_IF_SUPPORTED(
{ Assert(false, __FILE__, __LINE__, "This should fail."); }, "");
EXPECT_DEATH_IF_SUPPORTED({ Assert(false, __FILE__, __LINE__); }, "");
}
TEST(ExpectTest, SucceedsOnTrue) {
Expect(true, __FILE__, __LINE__, "This should succeed.");
Expect(true, __FILE__, __LINE__);
}
TEST(ExpectTest, FailsNonfatallyOnFalse) {
EXPECT_NONFATAL_FAILURE(
{
Expect(false, __FILE__, __LINE__, "This should fail.");
},
"This should fail");
EXPECT_NONFATAL_FAILURE(
{
Expect(false, __FILE__, __LINE__);
},
"Expectation failed");
}
class LogIsVisibleTest : public ::testing::Test {
protected:
void SetUp() override { original_verbose_ = GMOCK_FLAG_GET(verbose); }
void TearDown() override { GMOCK_FLAG_SET(verbose, original_verbose_); }
std::string original_verbose_;
};
TEST_F(LogIsVisibleTest, AlwaysReturnsTrueIfVerbosityIsInfo) {
GMOCK_FLAG_SET(verbose, kInfoVerbosity);
EXPECT_TRUE(LogIsVisible(kInfo));
EXPECT_TRUE(LogIsVisible(kWarning));
}
TEST_F(LogIsVisibleTest, AlwaysReturnsFalseIfVerbosityIsError) {
GMOCK_FLAG_SET(verbose, kErrorVerbosity);
EXPECT_FALSE(LogIsVisible(kInfo));
EXPECT_FALSE(LogIsVisible(kWarning));
}
TEST_F(LogIsVisibleTest, WorksWhenVerbosityIsWarning) {
GMOCK_FLAG_SET(verbose, kWarningVerbosity);
EXPECT_FALSE(LogIsVisible(kInfo));
EXPECT_TRUE(LogIsVisible(kWarning));
}
#if GTEST_HAS_STREAM_REDIRECTION
void TestLogWithSeverity(const std::string& verbosity, LogSeverity severity,
bool should_print) {
const std::string old_flag = GMOCK_FLAG_GET(verbose);
GMOCK_FLAG_SET(verbose, verbosity);
CaptureStdout();
Log(severity, "Test log.\n", 0);
if (should_print) {
EXPECT_THAT(
GetCapturedStdout().c_str(),
ContainsRegex(severity == kWarning
? "^\nGMOCK WARNING:\nTest log\\.\nStack trace:\n"
: "^\nTest log\\.\nStack trace:\n"));
} else {
EXPECT_STREQ("", GetCapturedStdout().c_str());
}
GMOCK_FLAG_SET(verbose, old_flag);
}
TEST(LogTest, NoStackTraceWhenStackFramesToSkipIsNegative) {
const std::string saved_flag = GMOCK_FLAG_GET(verbose);
GMOCK_FLAG_SET(verbose, kInfoVerbosity);
CaptureStdout();
Log(kInfo, "Test log.\n", -1);
EXPECT_STREQ("\nTest log.\n", GetCapturedStdout().c_str());
GMOCK_FLAG_SET(verbose, saved_flag);
}
struct MockStackTraceGetter : testing::internal::OsStackTraceGetterInterface {
std::string CurrentStackTrace(int max_depth, int skip_count) override {
return (testing::Message() << max_depth << "::" << skip_count << "\n")
.GetString();
}
void UponLeavingGTest() override {}
};
TEST(LogTest, NoSkippingStackFrameInOptMode) {
MockStackTraceGetter* mock_os_stack_trace_getter = new MockStackTraceGetter;
GetUnitTestImpl()->set_os_stack_trace_getter(mock_os_stack_trace_getter);
CaptureStdout();
Log(kWarning, "Test log.\n", 100);
const std::string log = GetCapturedStdout();
std::string expected_trace =
(testing::Message() << GTEST_FLAG_GET(stack_trace_depth) << "::")
.GetString();
std::string expected_message =
"\nGMOCK WARNING:\n"
"Test log.\n"
"Stack trace:\n" +
expected_trace;
EXPECT_THAT(log, HasSubstr(expected_message));
int skip_count = atoi(log.substr(expected_message.size()).c_str());
#if defined(NDEBUG)
const int expected_skip_count = 0;
#else
const int expected_skip_count = 100;
#endif
EXPECT_THAT(skip_count,
AllOf(Ge(expected_skip_count), Le(expected_skip_count + 10)));
GetUnitTestImpl()->set_os_stack_trace_getter(nullptr);
}
TEST(LogTest, AllLogsArePrintedWhenVerbosityIsInfo) {
TestLogWithSeverity(kInfoVerbosity, kInfo, true);
TestLogWithSeverity(kInfoVerbosity, kWarning, true);
}
TEST(LogTest, OnlyWarningsArePrintedWhenVerbosityIsWarning) {
TestLogWithSeverity(kWarningVerbosity, kInfo, false);
TestLogWithSeverity(kWarningVerbosity, kWarning, true);
}
TEST(LogTest, NoLogsArePrintedWhenVerbosityIsError) {
TestLogWithSeverity(kErrorVerbosity, kInfo, false);
TestLogWithSeverity(kErrorVerbosity, kWarning, false);
}
TEST(LogTest, OnlyWarningsArePrintedWhenVerbosityIsInvalid) {
TestLogWithSeverity("invalid", kInfo, false);
TestLogWithSeverity("invalid", kWarning, true);
}
std::string GrabOutput(void (*logger)(), const char* verbosity) {
const std::string saved_flag = GMOCK_FLAG_GET(verbose);
GMOCK_FLAG_SET(verbose, verbosity);
CaptureStdout();
logger();
GMOCK_FLAG_SET(verbose, saved_flag);
return GetCapturedStdout();
}
class DummyMock {
public:
MOCK_METHOD0(TestMethod, void());
MOCK_METHOD1(TestMethodArg, void(int dummy));
};
void ExpectCallLogger() {
DummyMock mock;
EXPECT_CALL(mock, TestMethod());
mock.TestMethod();
}
TEST(ExpectCallTest, LogsWhenVerbosityIsInfo) {
EXPECT_THAT(std::string(GrabOutput(ExpectCallLogger, kInfoVerbosity)),
HasSubstr("EXPECT_CALL(mock, TestMethod())"));
}
TEST(ExpectCallTest, DoesNotLogWhenVerbosityIsWarning) {
EXPECT_STREQ("", GrabOutput(ExpectCallLogger, kWarningVerbosity).c_str());
}
TEST(ExpectCallTest, DoesNotLogWhenVerbosityIsError) {
EXPECT_STREQ("", GrabOutput(ExpectCallLogger, kErrorVerbosity).c_str());
}
void OnCallLogger() {
DummyMock mock;
ON_CALL(mock, TestMethod());
}
TEST(OnCallTest, LogsWhenVerbosityIsInfo) {
EXPECT_THAT(std::string(GrabOutput(OnCallLogger, kInfoVerbosity)),
HasSubstr("ON_CALL(mock, TestMethod())"));
}
TEST(OnCallTest, DoesNotLogWhenVerbosityIsWarning) {
EXPECT_STREQ("", GrabOutput(OnCallLogger, kWarningVerbosity).c_str());
}
TEST(OnCallTest, DoesNotLogWhenVerbosityIsError) {
EXPECT_STREQ("", GrabOutput(OnCallLogger, kErrorVerbosity).c_str());
}
void OnCallAnyArgumentLogger() {
DummyMock mock;
ON_CALL(mock, TestMethodArg(_));
}
TEST(OnCallTest, LogsAnythingArgument) {
EXPECT_THAT(std::string(GrabOutput(OnCallAnyArgumentLogger, kInfoVerbosity)),
HasSubstr("ON_CALL(mock, TestMethodArg(_)"));
}
#endif
TEST(StlContainerViewTest, WorksForStlContainer) {
StaticAssertTypeEq<std::vector<int>,
StlContainerView<std::vector<int>>::type>();
StaticAssertTypeEq<const std::vector<double>&,
StlContainerView<std::vector<double>>::const_reference>();
typedef std::vector<char> Chars;
Chars v1;
const Chars& v2(StlContainerView<Chars>::ConstReference(v1));
EXPECT_EQ(&v1, &v2);
v1.push_back('a');
Chars v3 = StlContainerView<Chars>::Copy(v1);
EXPECT_THAT(v3, Eq(v3));
}
TEST(StlContainerViewTest, WorksForStaticNativeArray) {
StaticAssertTypeEq<NativeArray<int>, StlContainerView<int[3]>::type>();
StaticAssertTypeEq<NativeArray<double>,
StlContainerView<const double[4]>::type>();
StaticAssertTypeEq<NativeArray<char[3]>,
StlContainerView<const char[2][3]>::type>();
StaticAssertTypeEq<const NativeArray<int>,
StlContainerView<int[2]>::const_reference>();
int a1[3] = {0, 1, 2};
NativeArray<int> a2 = StlContainerView<int[3]>::ConstReference(a1);
EXPECT_EQ(3U, a2.size());
EXPECT_EQ(a1, a2.begin());
const NativeArray<int> a3 = StlContainerView<int[3]>::Copy(a1);
ASSERT_EQ(3U, a3.size());
EXPECT_EQ(0, a3.begin()[0]);
EXPECT_EQ(1, a3.begin()[1]);
EXPECT_EQ(2, a3.begin()[2]);
a1[0] = 3;
EXPECT_EQ(0, a3.begin()[0]);
}
TEST(StlContainerViewTest, WorksForDynamicNativeArray) {
StaticAssertTypeEq<NativeArray<int>,
StlContainerView<std::tuple<const int*, size_t>>::type>();
StaticAssertTypeEq<
NativeArray<double>,
StlContainerView<std::tuple<std::shared_ptr<double>, int>>::type>();
StaticAssertTypeEq<
const NativeArray<int>,
StlContainerView<std::tuple<const int*, int>>::const_reference>();
int a1[3] = {0, 1, 2};
const int* const p1 = a1;
NativeArray<int> a2 =
StlContainerView<std::tuple<const int*, int>>::ConstReference(
std::make_tuple(p1, 3));
EXPECT_EQ(3U, a2.size());
EXPECT_EQ(a1, a2.begin());
const NativeArray<int> a3 = StlContainerView<std::tuple<int*, size_t>>::Copy(
std::make_tuple(static_cast<int*>(a1), 3));
ASSERT_EQ(3U, a3.size());
EXPECT_EQ(0, a3.begin()[0]);
EXPECT_EQ(1, a3.begin()[1]);
EXPECT_EQ(2, a3.begin()[2]);
a1[0] = 3;
EXPECT_EQ(0, a3.begin()[0]);
}
TEST(FunctionTest, Nullary) {
typedef Function<int()> F;
EXPECT_EQ(0u, F::ArgumentCount);
EXPECT_TRUE((std::is_same<int, F::Result>::value));
EXPECT_TRUE((std::is_same<std::tuple<>, F::ArgumentTuple>::value));
EXPECT_TRUE((std::is_same<std::tuple<>, F::ArgumentMatcherTuple>::value));
EXPECT_TRUE((std::is_same<void(), F::MakeResultVoid>::value));
EXPECT_TRUE((std::is_same<IgnoredValue(), F::MakeResultIgnoredValue>::value));
}
TEST(FunctionTest, Unary) {
typedef Function<int(bool)> F;
EXPECT_EQ(1u, F::ArgumentCount);
EXPECT_TRUE((std::is_same<int, F::Result>::value));
EXPECT_TRUE((std::is_same<bool, F::Arg<0>::type>::value));
EXPECT_TRUE((std::is_same<std::tuple<bool>, F::ArgumentTuple>::value));
EXPECT_TRUE((
std::is_same<std::tuple<Matcher<bool>>, F::ArgumentMatcherTuple>::value));
EXPECT_TRUE((std::is_same<void(bool), F::MakeResultVoid>::value));
EXPECT_TRUE((std::is_same<IgnoredValue(bool),
F::MakeResultIgnoredValue>::value));
}
TEST(FunctionTest, Binary) {
typedef Function<int(bool, const long&)> F;
EXPECT_EQ(2u, F::ArgumentCount);
EXPECT_TRUE((std::is_same<int, F::Result>::value));
EXPECT_TRUE((std::is_same<bool, F::Arg<0>::type>::value));
EXPECT_TRUE((std::is_same<const long&, F::Arg<1>::type>::value));
EXPECT_TRUE((std::is_same<std::tuple<bool, const long&>,
F::ArgumentTuple>::value));
EXPECT_TRUE(
(std::is_same<std::tuple<Matcher<bool>, Matcher<const long&>>,
F::ArgumentMatcherTuple>::value));
EXPECT_TRUE((std::is_same<void(bool, const long&),
F::MakeResultVoid>::value));
EXPECT_TRUE((std::is_same<IgnoredValue(bool, const long&),
F::MakeResultIgnoredValue>::value));
}
TEST(FunctionTest, LongArgumentList) {
typedef Function<char(bool, int, char*, int&, const long&)> F;
EXPECT_EQ(5u, F::ArgumentCount);
EXPECT_TRUE((std::is_same<char, F::Result>::value));
EXPECT_TRUE((std::is_same<bool, F::Arg<0>::type>::value));
EXPECT_TRUE((std::is_same<int, F::Arg<1>::type>::value));
EXPECT_TRUE((std::is_same<char*, F::Arg<2>::type>::value));
EXPECT_TRUE((std::is_same<int&, F::Arg<3>::type>::value));
EXPECT_TRUE((std::is_same<const long&, F::Arg<4>::type>::value));
EXPECT_TRUE(
(std::is_same<std::tuple<bool, int, char*, int&, const long&>,
F::ArgumentTuple>::value));
EXPECT_TRUE(
(std::is_same<
std::tuple<Matcher<bool>, Matcher<int>, Matcher<char*>, Matcher<int&>,
Matcher<const long&>>,
F::ArgumentMatcherTuple>::value));
EXPECT_TRUE(
(std::is_same<void(bool, int, char*, int&, const long&),
F::MakeResultVoid>::value));
EXPECT_TRUE((
std::is_same<IgnoredValue(bool, int, char*, int&, const long&),
F::MakeResultIgnoredValue>::value));
}
TEST(Base64Unescape, InvalidString) {
std::string unescaped;
EXPECT_FALSE(Base64Unescape("(invalid)", &unescaped));
}
TEST(Base64Unescape, ShortString) {
std::string unescaped;
EXPECT_TRUE(Base64Unescape("SGVsbG8gd29ybGQh", &unescaped));
EXPECT_EQ("Hello world!", unescaped);
}
TEST(Base64Unescape, ShortStringWithPadding) {
std::string unescaped;
EXPECT_TRUE(Base64Unescape("SGVsbG8gd29ybGQ=", &unescaped));
EXPECT_EQ("Hello world", unescaped);
}
TEST(Base64Unescape, ShortStringWithoutPadding) {
std::string unescaped;
EXPECT_TRUE(Base64Unescape("SGVsbG8gd29ybGQ", &unescaped));
EXPECT_EQ("Hello world", unescaped);
}
TEST(Base64Unescape, LongStringWithWhiteSpaces) {
std::string escaped =
R"(TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieSB0aGlz
IHNpbmd1bGFyIHBhc3Npb24gZnJvbSBvdGhlciBhbmltYWxzLCB3aGljaCBpcyBhIGx1c3Qgb2Yg
dGhlIG1pbmQsIHRoYXQgYnkgYSBwZXJzZXZlcmFuY2Ugb2YgZGVsaWdodCBpbiB0aGUgY29udGlu
dWVkIGFuZCBpbmRlZmF0aWdhYmxlIGdlbmVyYXRpb24gb2Yga25vd2xlZGdlLCBleGNlZWRzIHRo
ZSBzaG9ydCB2ZWhlbWVuY2Ugb2YgYW55IGNhcm5hbCBwbGVhc3VyZS4=)";
std::string expected =
"Man is distinguished, not only by his reason, but by this singular "
"passion from other animals, which is a lust of the mind, that by a "
"perseverance of delight in the continued and indefatigable generation "
"of knowledge, exceeds the short vehemence of any carnal pleasure.";
std::string unescaped;
EXPECT_TRUE(Base64Unescape(escaped, &unescaped));
EXPECT_EQ(expected, unescaped);
}
}
}
} |