Code
stringlengths 131
28.2k
| Unit Test
stringlengths 40
32.1k
| __index_level_0__
int64 0
2.63k
|
---|---|---|
#ifndef XLA_TOOLS_HLO_CONTROL_FLOW_FLATTENING_H_
#define XLA_TOOLS_HLO_CONTROL_FLOW_FLATTENING_H_
#include <limits>
#include <string>
#include <utility>
#include "absl/container/flat_hash_set.h"
#include "absl/status/status.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/service/call_graph.h"
#include "xla/service/hlo_pass_interface.h"
namespace xla {
class HloControlFlowFlattening : public HloModulePass {
public:
struct Options {
int while_execution_count = 1;
int max_outer_loop_count = std::numeric_limits<int>::max();
int max_loop_count = std::numeric_limits<int>::max();
bool remove_infeed_outfeed = true;
bool flatten_while_loop = true;
bool remove_comm = true;
bool remove_host_transfer = false;
};
explicit HloControlFlowFlattening(const Options& options)
: while_execution_count_(options.while_execution_count),
max_outer_loop_count_(options.max_outer_loop_count),
max_loop_count_(options.max_loop_count),
remove_infeed_outfeed_(options.remove_infeed_outfeed),
flatten_while_loop_(options.flatten_while_loop),
remove_host_transfer_(options.remove_host_transfer),
remove_comm_(options.remove_comm) {}
~HloControlFlowFlattening() override = default;
absl::string_view name() const override { return "control-flow-flattening"; }
using HloPassInterface::Run;
absl::StatusOr<bool> Run(
HloModule* module,
const absl::flat_hash_set<absl::string_view>& execution_threads) override;
private:
absl::Status RemoveInfeed(HloInstruction* infeed_hlo) const;
absl::Status RemoveOutfeed(HloInstruction* outfeed_hlo) const;
absl::Status FlattenWhileLoop(HloInstruction* while_hlo,
const CallGraph& call_graph) const;
absl::Status RemoveId(HloInstruction* hlo) const;
int while_execution_count_;
int max_outer_loop_count_;
int max_loop_count_;
bool remove_infeed_outfeed_;
bool flatten_while_loop_;
bool remove_host_transfer_;
protected:
virtual absl::StatusOr<HloInstruction*> RemoveCollective(
HloInstruction* hlo) const;
virtual absl::StatusOr<std::pair<HloInstruction*, HloInstruction*>>
RemoveSendAndSendDone(
HloInstruction* send_done,
absl::flat_hash_set<HloInstruction*>* additional_removed) const;
virtual absl::StatusOr<std::pair<HloInstruction*, HloInstruction*>>
RemoveRecvAndRecvDone(
HloInstruction* recv_done,
absl::flat_hash_set<HloInstruction*>* additional_removed) const;
bool remove_comm_;
};
int GetLoopBound(const HloInstruction& while_hlo, const int default_loop_count,
const int max_loop_count);
int GetLoopBoundWithOuterLoopMax(const HloInstruction& while_hlo,
const CallGraph& call_graph,
const int default_loop_count,
const int max_outer_loop_count,
const int max_loop_count);
}
#endif
#include "xla/tools/hlo_control_flow_flattening.h"
#include <algorithm>
#include <cstdint>
#include <string>
#include <utility>
#include <vector>
#include "absl/container/flat_hash_set.h"
#include "absl/log/check.h"
#include "absl/log/log.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/string_view.h"
#include "xla/comparison_util.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_opcode.h"
#include "xla/hlo/ir/hlo_sharding.h"
#include "xla/literal.h"
#include "xla/literal_util.h"
#include "xla/service/call_graph.h"
#include "xla/service/collective_ops_utils.h"
#include "xla/service/hlo_dce.h"
#include "xla/service/tuple_util.h"
#include "xla/shape.h"
#include "xla/shape_util.h"
#include "xla/util.h"
#include "tsl/platform/errors.h"
#include "tsl/platform/statusor.h"
namespace xla {
namespace {
HloInstruction* CreateConstant(const Shape& shape,
HloComputation* computation) {
if (shape.IsTuple()) {
std::vector<HloInstruction*> tuple_arguments(shape.tuple_shapes_size());
for (int index = 0; index < shape.tuple_shapes_size(); ++index) {
tuple_arguments[index] =
CreateConstant(shape.tuple_shapes(index), computation);
}
return computation->AddInstruction(
HloInstruction::CreateTuple(tuple_arguments));
} else {
return computation->AddInstruction(
HloInstruction::CreateConstant(Literal::CreateFromShape(shape)));
}
}
void PrintSubexpression(HloInstruction* inst, int depth) {
if (depth == 0) {
return;
}
for (auto* operand : inst->operands()) {
PrintSubexpression(operand, depth - 1);
}
VLOG(2) << inst->ToString();
}
bool IsConstantScalarInt(const HloInstruction* inst) {
return inst->opcode() == HloOpcode::kConstant &&
ShapeUtil::IsEffectiveScalar(inst->shape()) &&
inst->shape().IsInteger();
}
bool IsNotContainedInLoop(const HloInstruction& while_hlo,
const CallGraph& call_graph) {
const HloComputation* computation = while_hlo.parent();
while (!computation->IsEntryComputation()) {
auto& node = call_graph.GetNode(computation);
CHECK_EQ(node.caller_callsites().size(), 1)
<< "The module is not flattened!";
auto& callsite = node.caller_callsites()[0];
if (callsite.instruction()->opcode() == HloOpcode::kWhile) {
return false;
}
computation = callsite.instruction()->parent();
}
return true;
}
}
int GetLoopBound(const HloInstruction& while_hlo, const int default_loop_count,
const int max_loop_count) {
HloInstruction* condition = while_hlo.while_condition()->root_instruction();
if (condition->opcode() == HloOpcode::kCompare) {
int64_t value = 0;
Comparison::Direction cmp = condition->comparison_direction();
if ((cmp == Comparison::Direction::kLt ||
cmp == Comparison::Direction::kLe ||
cmp == Comparison::Direction::kNe) &&
IsConstantScalarInt(condition->operand(1))) {
value = *condition->operand(1)->literal().GetFirstInteger();
} else if ((cmp == Comparison::Direction::kGt ||
cmp == Comparison::Direction::kGe ||
cmp == Comparison::Direction::kNe) &&
IsConstantScalarInt(condition->operand(0))) {
value = *condition->operand(0)->literal().GetFirstInteger();
}
if (value > 0) {
return std::min(value, static_cast<int64_t>(max_loop_count));
}
}
return default_loop_count;
}
int GetLoopBoundWithOuterLoopMax(const HloInstruction& while_hlo,
const CallGraph& call_graph,
const int default_loop_count,
const int max_outer_loop_count,
const int max_loop_count) {
int loop_bound = GetLoopBound(while_hlo, default_loop_count, max_loop_count);
if (loop_bound > max_outer_loop_count) {
if (IsNotContainedInLoop(while_hlo, call_graph)) {
return max_outer_loop_count;
}
}
return loop_bound;
}
absl::Status HloControlFlowFlattening::FlattenWhileLoop(
HloInstruction* while_hlo, const CallGraph& call_graph) const {
CHECK_EQ(while_hlo->opcode(), HloOpcode::kWhile);
HloComputation* computation = while_hlo->parent();
HloInstruction* initialization = computation->AddInstruction(
HloInstruction::CreateConstant(LiteralUtil::CreateR0<int>(0)));
HloInstruction* old_tuple = while_hlo->mutable_operand(0);
HloInstruction* new_tuple =
TupleUtil::AppendSuffix(old_tuple, {initialization});
int new_tuple_size = new_tuple->shape().tuple_shapes().size();
TF_RETURN_IF_ERROR(while_hlo->ReplaceOperandWithDifferentShape(0, new_tuple));
auto change_op_shape = [&](HloInstruction* instruction) {
Shape* shape = instruction->mutable_shape();
CHECK(shape->IsTuple());
CHECK_EQ(shape->tuple_shapes().size(), new_tuple_size - 1);
Shape* subshape = shape->add_tuple_shapes();
return ShapeUtil::PopulateShape(S32, {}, subshape);
};
auto replace_non_gte_users =
[](HloInstruction* new_tuple) -> absl::StatusOr<HloInstruction*> {
CHECK(new_tuple->shape().IsTuple());
HloInstruction* prefix = nullptr;
std::vector<HloInstruction*> users(new_tuple->users());
for (HloInstruction* user : users) {
if (user->opcode() == HloOpcode::kGetTupleElement) {
continue;
}
if (prefix == nullptr) {
prefix = TupleUtil::ExtractPrefix(
new_tuple, new_tuple->shape().tuple_shapes_size() - 1);
}
TF_RETURN_IF_ERROR(new_tuple->ReplaceUseWithDifferentShape(user, prefix));
}
return prefix;
};
{
HloComputation* condition = while_hlo->while_condition();
TF_RETURN_IF_ERROR(change_op_shape(condition->parameter_instruction(0)));
TF_RETURN_IF_ERROR(
replace_non_gte_users(condition->parameter_instruction(0)).status());
if (VLOG_IS_ON(2)) {
VLOG(2) << "Loop condition in " << while_hlo->parent()->name();
PrintSubexpression(condition->root_instruction(), 3);
}
const int loop_bound = GetLoopBoundWithOuterLoopMax(
*while_hlo, call_graph, while_execution_count_, max_outer_loop_count_,
max_loop_count_);
VLOG(1) << "loop_bound = " << loop_bound;
HloInstruction* limit = condition->AddInstruction(
HloInstruction::CreateConstant(LiteralUtil::CreateR0<int>(loop_bound)));
Shape shape = initialization->shape();
HloInstruction* induction_variable =
condition->AddInstruction(HloInstruction::CreateGetTupleElement(
shape, condition->parameter_instruction(0), new_tuple_size - 1));
HloInstruction* compare =
condition->AddInstruction(HloInstruction::CreateCompare(
ShapeUtil::MakeShape(PRED, {}), induction_variable, limit,
ComparisonDirection::kLt));
TF_RETURN_IF_ERROR(
condition->ReplaceInstruction(condition->root_instruction(), compare));
}
{
HloComputation* body = while_hlo->while_body();
TF_RETURN_IF_ERROR(change_op_shape(body->parameter_instruction(0)));
TF_RETURN_IF_ERROR(
replace_non_gte_users(body->parameter_instruction(0)).status());
HloInstruction* old_root = body->root_instruction();
Shape shape = initialization->shape();
HloInstruction* induction_variable =
body->AddInstruction(HloInstruction::CreateGetTupleElement(
shape, body->parameter_instruction(0), new_tuple_size - 1));
HloInstruction* increment = body->AddInstruction(
HloInstruction::CreateConstant(LiteralUtil::CreateR0<int>(1)));
induction_variable = body->AddInstruction(HloInstruction::CreateBinary(
shape, HloOpcode::kAdd, induction_variable, increment));
HloInstruction* new_root =
TupleUtil::AppendSuffix(old_root, {induction_variable});
body->set_root_instruction(new_root, true);
}
std::vector<HloInstruction*> while_users(while_hlo->users().begin(),
while_hlo->users().end());
TF_RETURN_IF_ERROR(change_op_shape(while_hlo));
TF_ASSIGN_OR_RETURN(HloInstruction * prefix,
replace_non_gte_users(while_hlo));
if (while_hlo->parent()->root_instruction() == while_hlo) {
if (prefix == nullptr) {
prefix = TupleUtil::ExtractPrefix(while_hlo, new_tuple_size - 1);
}
while_hlo->parent()->set_root_instruction(prefix,
true);
}
return absl::OkStatus();
}
absl::Status HloControlFlowFlattening::RemoveInfeed(
HloInstruction* infeed_hlo) const {
CHECK_EQ(infeed_hlo->opcode(), HloOpcode::kInfeed);
HloComputation* computation = infeed_hlo->parent();
CHECK_EQ(infeed_hlo->shape().tuple_shapes_size(), 2);
const Shape& infeed_shape = ShapeUtil::GetSubshape(infeed_hlo->shape(), {0});
HloInstruction* custom_call = computation->AddInstruction(
HloInstruction::CreateCustomCall(infeed_shape, {}, kNopCustomCallTarget));
auto new_tuple = HloInstruction::CreateTuple(
{custom_call, infeed_hlo->mutable_operand(0)});
TF_RETURN_IF_ERROR(
computation->ReplaceWithNewInstruction(infeed_hlo, std::move(new_tuple)));
custom_call->SetAndSanitizeName(infeed_hlo->name());
return absl::OkStatus();
}
absl::StatusOr<std::pair<HloInstruction*, HloInstruction*>>
HloControlFlowFlattening::RemoveRecvAndRecvDone(
HloInstruction* recv_done,
absl::flat_hash_set<HloInstruction*>* additional_removed) const {
CHECK_EQ(recv_done->opcode(), HloOpcode::kRecvDone);
CHECK_EQ(recv_done->operand_count(), 1);
HloInstruction* recv = recv_done->mutable_operand(0);
CHECK_EQ(recv->opcode(), HloOpcode::kRecv);
HloComputation* computation = recv_done->parent();
CHECK_EQ(recv_done->shape().tuple_shapes_size(), 2);
HloModule* module = computation->parent();
HloInstruction* custom_call_recv =
computation->AddInstruction(HloInstruction::CreateCustomCall(
recv->shape(), recv->operands(), kNopCustomCallTarget));
std::string original_recv_name(recv->name());
if (module->has_schedule() &&
module->schedule().is_computation_scheduled(computation)) {
module->schedule().replace_instruction(computation, recv, custom_call_recv);
}
TF_RETURN_IF_ERROR(computation->ReplaceInstruction(recv, custom_call_recv));
custom_call_recv->SetAndSanitizeName(original_recv_name);
std::string original_recv_done_name(recv_done->name());
HloInstruction* custom_call_recv_done = computation->AddInstruction(
HloInstruction::CreateCustomCall(
recv_done->shape(), recv_done->operands(), kNopCustomCallTarget),
recv_done->name());
if (module->has_schedule() &&
module->schedule().is_computation_scheduled(computation)) {
module->schedule().replace_instruction(computation, recv_done,
custom_call_recv_done);
}
TF_RETURN_IF_ERROR(
computation->ReplaceInstruction(recv_done, custom_call_recv_done));
custom_call_recv_done->SetAndSanitizeName(original_recv_done_name);
return std::make_pair(custom_call_recv, custom_call_recv_done);
}
absl::Status HloControlFlowFlattening::RemoveOutfeed(
HloInstruction* outfeed_hlo) const {
CHECK_EQ(outfeed_hlo->opcode(), HloOpcode::kOutfeed);
HloComputation* computation = outfeed_hlo->parent();
HloInstruction* custom_call =
computation->AddInstruction(HloInstruction::CreateCustomCall(
outfeed_hlo->shape(), outfeed_hlo->operands(),
kNopReturnTokenCustomCallTarget));
Cast<HloCustomCallInstruction>(custom_call)
->set_custom_call_has_side_effect(true);
custom_call->set_sharding(HloSharding::Manual());
TF_RETURN_IF_ERROR(computation->ReplaceInstruction(outfeed_hlo, custom_call));
custom_call->SetAndSanitizeName(outfeed_hlo->name());
return absl::OkStatus();
}
absl::StatusOr<std::pair<HloInstruction*, HloInstruction*>>
HloControlFlowFlattening::RemoveSendAndSendDone(
HloInstruction* send_done,
absl::flat_hash_set<HloInstruction*>* additional_removed) const {
CHECK_EQ(send_done->opcode(), HloOpcode::kSendDone);
CHECK_EQ(send_done->operand_count(), 1);
HloInstruction* send = send_done->mutable_operand(0);
CHECK_EQ(send->opcode(), HloOpcode::kSend);
HloComputation* computation = send_done->parent();
HloModule* module = computation->parent();
HloInstruction* custom_call_send =
computation->AddInstruction(HloInstruction::CreateCustomCall(
send->shape(), send->operands(), kNopCustomCallTarget));
std::string original_send_name(send->name());
if (module->has_schedule() &&
module->schedule().is_computation_scheduled(computation)) {
module->schedule().replace_instruction(computation, send, custom_call_send);
}
TF_RETURN_IF_ERROR(computation->ReplaceInstruction(send, custom_call_send));
custom_call_send->SetAndSanitizeName(original_send_name);
HloInstruction* custom_call_send_done =
computation->AddInstruction(HloInstruction::CreateCustomCall(
send_done->shape(), send_done->operands(),
kNopReturnTokenCustomCallTarget));
std::string original_send_done_name(send_done->name());
Cast<HloCustomCallInstruction>(custom_call_send_done)
->set_custom_call_has_side_effect(true);
if (module->has_schedule() &&
module->schedule().is_computation_scheduled(computation)) {
module->schedule().replace_instruction(computation, send_done,
custom_call_send_done);
}
TF_RETURN_IF_ERROR(
computation->ReplaceInstruction(send_done, custom_call_send_done));
custom_call_send_done->SetAndSanitizeName(original_send_done_name);
return std::make_pair(custom_call_send, custom_call_send_done);
}
absl::StatusOr<HloInstruction*> HloControlFlowFlattening::RemoveCollective(
HloInstruction* hlo) const {
HloComputation* computation = hlo->parent();
HloInstruction* custom_call =
computation->AddInstruction(HloInstruction::CreateCustomCall(
hlo->shape(), hlo->operands(), kNopCustomCallTarget));
custom_call->CopyBackendConfigFrom(hlo);
HloModule* module = computation->parent();
if (module->has_schedule() &&
module->schedule().is_computation_scheduled(computation)) {
module->schedule().replace_instruction(computation, hlo, custom_call);
}
std::string original_op_name(hlo->name());
TF_RETURN_IF_ERROR(computation->ReplaceInstruction(hlo, custom_call));
custom_call->SetAndSanitizeName(original_op_name);
return custom_call;
}
absl::Status HloControlFlowFlattening::RemoveId(HloInstruction* hlo) const {
HloComputation* computation = hlo->parent();
HloInstruction* zero = CreateConstant(hlo->shape(), computation);
std::string original_op_name(hlo->name());
TF_RETURN_IF_ERROR(computation->ReplaceInstruction(hlo, zero));
zero->SetAndSanitizeName(original_op_name);
return absl::OkStatus();
}
absl::StatusOr<bool> HloControlFlowFlattening::Run(
HloModule* module,
const absl::flat_hash_set<absl::string_view>& execution_threads) {
auto call_graph = CallGraph::Build(module);
bool changed = false;
absl::flat_hash_set<HloInstruction*> removed;
for (HloComputation* computation : module->computations(execution_threads)) {
if (computation->IsAsyncComputation()) {
continue;
}
for (HloInstruction* instruction :
computation->MakeInstructionPostOrder()) {
if (removed.contains(instruction)) {
continue;
}
if (flatten_while_loop_ && instruction->opcode() == HloOpcode::kWhile) {
VLOG(1) << "Remove " << instruction->name();
TF_RETURN_IF_ERROR(FlattenWhileLoop(instruction, *call_graph));
changed = true;
} else if (remove_infeed_outfeed_ &&
instruction->opcode() == HloOpcode::kInfeed) {
VLOG(1) << "Remove " << instruction->name();
TF_RETURN_IF_ERROR(RemoveInfeed(instruction));
changed = true;
} else if (remove_infeed_outfeed_ &&
instruction->opcode() == HloOpcode::kOutfeed) {
VLOG(1) << "Remove " << instruction->name();
TF_RETURN_IF_ERROR(RemoveOutfeed(instruction));
changed = true;
} else if (instruction->opcode() == HloOpcode::kSendDone) {
auto send_done_instruction =
DynCast<HloSendDoneInstruction>(instruction);
CHECK(send_done_instruction);
if (remove_comm_ || (remove_host_transfer_ &&
send_done_instruction->is_host_transfer())) {
VLOG(1) << "Remove " << instruction->name();
TF_RETURN_IF_ERROR(
RemoveSendAndSendDone(instruction, &removed).status());
changed = true;
}
} else if (instruction->opcode() == HloOpcode::kRecvDone) {
auto recv_done_instruction =
DynCast<HloRecvDoneInstruction>(instruction);
CHECK(recv_done_instruction);
if (remove_comm_ || (remove_host_transfer_ &&
recv_done_instruction->is_host_transfer())) {
VLOG(1) << "Remove " << instruction->name();
TF_RETURN_IF_ERROR(
RemoveRecvAndRecvDone(instruction, &removed).status());
changed = true;
}
} else if (remove_comm_ && IsCollective(instruction) &&
!instruction->parent()->IsFusionComputation() &&
(instruction->opcode() != HloOpcode::kAsyncStart &&
instruction->opcode() != HloOpcode::kAsyncUpdate)) {
if (instruction->opcode() == HloOpcode::kAsyncDone) {
while (instruction->opcode() == HloOpcode::kAsyncDone ||
instruction->opcode() == HloOpcode::kAsyncUpdate ||
instruction->opcode() == HloOpcode::kAsyncStart) {
HloInstruction* operand = instruction->mutable_operand(0);
VLOG(1) << "Remove " << instruction->name();
TF_RETURN_IF_ERROR(RemoveCollective(instruction).status());
instruction = operand;
}
} else {
VLOG(1) << "Remove " << instruction->name();
TF_RETURN_IF_ERROR(RemoveCollective(instruction).status());
}
changed = true;
} else if (remove_comm_ &&
(instruction->opcode() == HloOpcode::kPartitionId ||
instruction->opcode() == HloOpcode::kReplicaId ||
(instruction->opcode() == HloOpcode::kCustomCall &&
instruction->custom_call_target() == "SliceId"))) {
VLOG(1) << "Remove " << instruction->name();
TF_RETURN_IF_ERROR(RemoveId(instruction));
changed = true;
}
}
}
HloDCE hlo_dce;
TF_ASSIGN_OR_RETURN(bool dce_changed, hlo_dce.Run(module, execution_threads));
changed |= dce_changed;
if (changed && module->has_schedule()) {
TF_RETURN_IF_ERROR(module->schedule().Update());
}
XLA_VLOG_LINES(3, module->ToString());
return changed;
}
} | #include "xla/tools/hlo_control_flow_flattening.h"
#include <memory>
#include <utility>
#include "absl/strings/str_replace.h"
#include "xla/hlo/utils/hlo_matchers.h"
#include "xla/service/collective_ops_utils.h"
#include "xla/service/despecializer.h"
#include "xla/service/hlo_verifier.h"
#include "xla/service/spmd/spmd_partitioner.h"
#include "xla/tests/hlo_test_base.h"
#include "tsl/lib/core/status_test_util.h"
namespace xla {
namespace {
namespace op = xla::testing::opcode_matchers;
class HloControlFlowFlatteningTest : public HloTestBase {
public:
absl::StatusOr<std::unique_ptr<HloModule>> PartitionComputation(
std::unique_ptr<VerifiedHloModule> hlo_module, int64_t num_devices = 2) {
spmd::SpmdPartitionerOptions options;
auto collective_ops_creator =
spmd::GetDefaultCollectiveOpsCreator(num_devices, 1);
collective_ops_creator.create_cross_partition_all_gather = nullptr;
HloModuleConfig config = GetModuleConfigForTest();
config.set_use_spmd_partitioning(true);
config.set_num_partitions(num_devices);
HloPassPipeline pass("spmd-partitioning");
pass.AddPass<HloVerifier>(false,
false);
pass.AddPass<spmd::SpmdPartitioner>(num_devices, 1,
options, collective_ops_creator);
pass.AddPass<HloVerifier>(false,
false);
TF_RETURN_IF_ERROR(pass.Run(hlo_module.get()).status());
return absl::StatusOr<std::unique_ptr<HloModule>>(std::move(hlo_module));
}
};
constexpr int kDefaultMaxLoopCount = 1000;
TEST_F(HloControlFlowFlatteningTest, WhileRoot) {
absl::string_view hlo_string = R"(
HloModule While
While.body {
loop_var.1 = (s32[], s32[3]{0}) parameter(0)
get-tuple-element.1 = s32[] get-tuple-element(loop_var.1), index=0
constant.1 = s32[] constant(1)
add = s32[] add(get-tuple-element.1, constant.1)
get-tuple-element.2 = s32[3]{0} get-tuple-element(loop_var.1), index=1
multiply = s32[3]{0} multiply(get-tuple-element.2, get-tuple-element.2)
ROOT tuple = (s32[], s32[3]{0}) tuple(add, multiply)
}
While.condition {
loop_var.2 = (s32[], s32[3]{0}) parameter(0)
get-tuple-element.3 = s32[] get-tuple-element(loop_var.2), index=0
constant.2 = s32[] constant(100)
ROOT less-than = pred[] compare(get-tuple-element.3, constant.2), direction=LT
}
ENTRY While {
constant.3 = s32[] constant(42)
constant.4 = s32[3]{0} constant({0, 1, 2})
tuple.1 = (s32[], s32[3]{0}) tuple(constant.3, constant.4)
ROOT while = (s32[], s32[3]{0}) while(tuple.1), condition=While.condition, body=While.body
}
)";
TF_ASSERT_OK_AND_ASSIGN(auto module,
ParseAndReturnVerifiedModule(hlo_string));
HloControlFlowFlattening flattening(
HloControlFlowFlattening::Options{3});
EXPECT_TRUE(flattening.Run(module.get()).value());
TF_ASSERT_OK(HloVerifier(true,
true)
.Run(module.get())
.status());
auto root = module->entry_computation()->root_instruction();
auto while_op = module->entry_computation()->GetInstructionWithName("while");
EXPECT_THAT(root, op::Tuple(op::GetTupleElement(while_op, 0),
op::GetTupleElement(while_op, 1)));
EXPECT_THAT(while_op,
op::While(op::Tuple(op::GetTupleElement(), op::GetTupleElement(),
op::Constant())));
auto condition = while_op->while_condition();
EXPECT_THAT(
condition->root_instruction(),
op::Compare(op::GetTupleElement(op::Parameter(0), 2), op::Constant()));
auto body = while_op->while_body();
EXPECT_THAT(body->root_instruction(),
op::Tuple(op::GetTupleElement(), op::GetTupleElement(),
op::Add(op::GetTupleElement(op::Parameter(0), 2),
op::Constant())));
}
TEST_F(HloControlFlowFlatteningTest, WhileConditionCallComputation) {
absl::string_view hlo_string = R"(
HloModule While
While.body {
loop_var.1 = (s32[], s32[3]{0}) parameter(0)
get-tuple-element.1 = s32[] get-tuple-element(loop_var.1), index=0
constant.1 = s32[] constant(1)
add = s32[] add(get-tuple-element.1, constant.1)
get-tuple-element.2 = s32[3]{0} get-tuple-element(loop_var.1), index=1
multiply = s32[3]{0} multiply(get-tuple-element.2, get-tuple-element.2)
ROOT tuple = (s32[], s32[3]{0}) tuple(add, multiply)
}
While.condition.called {
loop_var.2 = (s32[], s32[3]{0}) parameter(0)
get-tuple-element.3 = s32[] get-tuple-element(loop_var.2), index=0
constant.2 = s32[] custom-call(), custom_call_target="AllocateBuffer", custom_call_has_side_effect=true
less-than = pred[] compare(get-tuple-element.3, constant.2), direction=LT
ROOT tuple.2 = (pred[]) tuple(less-than)
}
While.condition {
loop_var.3 = (s32[], s32[3]{0}) parameter(0)
call = (pred[]) call(loop_var.3), to_apply=While.condition.called
ROOT get-tuple-element.4 = pred[] get-tuple-element(call), index=0
}
ENTRY While {
constant.3 = s32[] constant(42)
constant.4 = s32[3]{0} constant({0, 1, 2})
tuple.1 = (s32[], s32[3]{0}) tuple(constant.3, constant.4)
ROOT while = (s32[], s32[3]{0}) while(tuple.1), condition=While.condition, body=While.body
}
)";
TF_ASSERT_OK_AND_ASSIGN(auto module,
ParseAndReturnVerifiedModule(hlo_string));
HloControlFlowFlattening flattening(
HloControlFlowFlattening::Options{3});
EXPECT_TRUE(flattening.Run(module.get()).value());
XLA_VLOG_LINES(3, "Loaded HLO module: " + module->ToString());
TF_ASSERT_OK(HloVerifier(true,
true)
.Run(module.get())
.status());
auto root = module->entry_computation()->root_instruction();
auto while_op = module->entry_computation()->GetInstructionWithName("while");
EXPECT_THAT(root, op::Tuple(op::GetTupleElement(while_op, 0),
op::GetTupleElement(while_op, 1)));
EXPECT_THAT(while_op,
op::While(op::Tuple(op::GetTupleElement(), op::GetTupleElement(),
op::Constant())));
auto condition = while_op->while_condition();
EXPECT_THAT(
condition->root_instruction(),
op::Compare(op::GetTupleElement(op::Parameter(0), 2), op::Constant()));
auto body = while_op->while_body();
EXPECT_THAT(body->root_instruction(),
op::Tuple(op::GetTupleElement(), op::GetTupleElement(),
op::Add(op::GetTupleElement(op::Parameter(0), 2),
op::Constant())));
}
TEST_F(HloControlFlowFlatteningTest, WhileRootScheduled) {
absl::string_view hlo_string = R"(
HloModule While, is_scheduled=true
While.body {
loop_var.1 = (s32[], s32[3]{0}) parameter(0)
get-tuple-element.1 = s32[] get-tuple-element(loop_var.1), index=0
constant.1 = s32[] constant(1)
add = s32[] add(get-tuple-element.1, constant.1)
get-tuple-element.2 = s32[3]{0} get-tuple-element(loop_var.1), index=1
multiply = s32[3]{0} multiply(get-tuple-element.2, get-tuple-element.2)
ROOT tuple = (s32[], s32[3]{0}) tuple(add, multiply)
}
While.condition {
loop_var.2 = (s32[], s32[3]{0}) parameter(0)
get-tuple-element.3 = s32[] get-tuple-element(loop_var.2), index=0
constant.2 = s32[] constant(100)
ROOT less-than = pred[] compare(get-tuple-element.3, constant.2), direction=LT
}
ENTRY While {
constant.3 = s32[] constant(42)
constant.4 = s32[3]{0} constant({0, 1, 2})
tuple.1 = (s32[], s32[3]{0}) tuple(constant.3, constant.4)
ROOT while = (s32[], s32[3]{0}) while(tuple.1), condition=While.condition, body=While.body
}
)";
TF_ASSERT_OK_AND_ASSIGN(auto module,
ParseAndReturnVerifiedModule(hlo_string));
HloControlFlowFlattening flattening(
HloControlFlowFlattening::Options{3});
EXPECT_TRUE(flattening.Run(module.get()).value());
TF_ASSERT_OK(HloVerifier(true,
true)
.Run(module.get())
.status());
auto root = module->entry_computation()->root_instruction();
auto while_op = module->entry_computation()->GetInstructionWithName("while");
EXPECT_THAT(root, op::Tuple(op::GetTupleElement(while_op, 0),
op::GetTupleElement(while_op, 1)));
EXPECT_THAT(while_op,
op::While(op::Tuple(op::GetTupleElement(), op::GetTupleElement(),
op::Constant())));
auto condition = while_op->while_condition();
EXPECT_THAT(
condition->root_instruction(),
op::Compare(op::GetTupleElement(op::Parameter(0), 2), op::Constant()));
}
TEST_F(HloControlFlowFlatteningTest, WhileUser) {
absl::string_view hlo_string = R"(
HloModule While
While.body {
loop_var.1 = (s32[], s32[3]{0}) parameter(0)
get-tuple-element.1 = s32[] get-tuple-element(loop_var.1), index=0
constant.1 = s32[] constant(1)
add = s32[] add(get-tuple-element.1, constant.1)
get-tuple-element.2 = s32[3]{0} get-tuple-element(loop_var.1), index=1
multiply = s32[3]{0} multiply(get-tuple-element.2, get-tuple-element.2)
ROOT tuple = (s32[], s32[3]{0}) tuple(add, multiply)
}
While.condition {
loop_var.2 = (s32[], s32[3]{0}) parameter(0)
get-tuple-element.3 = s32[] get-tuple-element(loop_var.2), index=0
constant.2 = s32[] constant(100)
ROOT less-than = pred[] compare(get-tuple-element.3, constant.2), direction=LT
}
FusedComputation {
param = (s32[], s32[3]{0}) parameter(0)
get-tuple-element.4 = s32[] get-tuple-element(param), index=0
get-tuple-element.5 = s32[3]{0} get-tuple-element(param), index=1
broadcast = s32[3]{0} broadcast(get-tuple-element.4), dimensions={}
ROOT add = s32[3]{0} add(broadcast, get-tuple-element.5)
}
ENTRY While {
constant.3 = s32[] constant(42)
constant.4 = s32[3]{0} constant({0, 1, 2})
tuple.1 = (s32[], s32[3]{0}) tuple(constant.3, constant.4)
while = (s32[], s32[3]{0}) while(tuple.1), condition=While.condition, body=While.body
ROOT fusion = s32[3]{0} fusion(while), kind=kLoop, calls=FusedComputation
}
)";
TF_ASSERT_OK_AND_ASSIGN(auto module,
ParseAndReturnVerifiedModule(hlo_string));
HloControlFlowFlattening flattening(
HloControlFlowFlattening::Options{3});
EXPECT_TRUE(flattening.Run(module.get()).value());
TF_ASSERT_OK(HloVerifier(true,
true)
.Run(module.get())
.status());
auto fusion = module->entry_computation()->root_instruction();
auto while_op = module->entry_computation()->GetInstructionWithName("while");
EXPECT_THAT(fusion, op::Fusion(op::Tuple(op::GetTupleElement(while_op, 0),
op::GetTupleElement(while_op, 1))));
}
TEST_F(HloControlFlowFlatteningTest, Infeed) {
absl::string_view hlo_string = R"(
HloModule Infeed
ENTRY Infeed {
after-all = token[] after-all()
ROOT infeed.23 = ((bf16[3]{0}, s32[12,5]{0,1}), token[]) infeed(after-all)
}
)";
TF_ASSERT_OK_AND_ASSIGN(auto module,
ParseAndReturnVerifiedModule(hlo_string));
HloControlFlowFlattening flattening(
HloControlFlowFlattening::Options{3});
EXPECT_TRUE(flattening.Run(module.get()).value());
TF_ASSERT_OK(HloVerifier(true,
true)
.Run(module.get())
.status());
auto custom_call =
module->entry_computation()->GetInstructionWithName("infeed.23");
EXPECT_THAT(custom_call, op::CustomCall());
auto tuple = module->entry_computation()->root_instruction();
EXPECT_THAT(tuple, op::Tuple(custom_call, op::AfterAll()));
}
TEST_F(HloControlFlowFlatteningTest, InfeedPreserveLayout) {
absl::string_view hlo_string = R"(
HloModule Infeed
ENTRY Infeed {
after-all = token[] after-all()
ROOT infeed = ((bf16[3]{0}, s32[12,5]{0,1:T(8,128)}), token[]) infeed(after-all)
}
)";
TF_ASSERT_OK_AND_ASSIGN(auto module,
ParseAndReturnVerifiedModule(hlo_string));
Shape root_shape = module->entry_computation()->root_instruction()->shape();
HloControlFlowFlattening flattening(
HloControlFlowFlattening::Options{3});
EXPECT_TRUE(flattening.Run(module.get()).value());
TF_ASSERT_OK(HloVerifier(true,
true)
.Run(module.get())
.status());
auto tuple = module->entry_computation()->root_instruction();
EXPECT_THAT(tuple, op::Tuple(op::CustomCall(), op::AfterAll()));
EXPECT_EQ(tuple->shape(), root_shape);
}
TEST_F(HloControlFlowFlatteningTest, OutfeedCustomCallIsPartitionable) {
absl::string_view hlo_string = R"(
HloModule Outfeed
ENTRY Outfeed {
param = (bf16[3]{0}, s32[12,5]{0,1}) parameter(0)
after-all = token[] after-all()
ROOT outfeed.23 = token[] outfeed(param, after-all)
}
)";
TF_ASSERT_OK_AND_ASSIGN(auto module,
ParseAndReturnVerifiedModule(hlo_string));
HloControlFlowFlattening flattening(HloControlFlowFlattening::Options{
3, 3,
3, true});
EXPECT_TRUE(flattening.Run(module.get()).value());
auto custom_call = module->entry_computation()->root_instruction();
EXPECT_EQ(custom_call->name(), "outfeed.23");
EXPECT_TRUE(custom_call->has_sharding());
TF_ASSERT_OK_AND_ASSIGN(auto hlo_module,
PartitionComputation(std::move(module)));
}
TEST_F(HloControlFlowFlatteningTest, Outfeed) {
absl::string_view hlo_string = R"(
HloModule Outfeed
ENTRY Outfeed {
param = (bf16[3]{0}, s32[12,5]{0,1}) parameter(0)
after-all = token[] after-all()
ROOT outfeed.23 = token[] outfeed(param, after-all)
}
)";
TF_ASSERT_OK_AND_ASSIGN(auto module,
ParseAndReturnVerifiedModule(hlo_string));
HloControlFlowFlattening flattening(
HloControlFlowFlattening::Options{3});
EXPECT_TRUE(flattening.Run(module.get()).value());
TF_ASSERT_OK(HloVerifier(true,
true)
.Run(module.get())
.status());
auto custom_call = module->entry_computation()->root_instruction();
EXPECT_EQ(custom_call->name(), "outfeed.23");
EXPECT_THAT(custom_call, op::CustomCall(op::Parameter(0), op::AfterAll()));
}
TEST_F(HloControlFlowFlatteningTest, AllReduce) {
absl::string_view hlo_string = R"(
HloModule AllReduce
sum {
p0 = f32[] parameter(0)
p1 = f32[] parameter(1)
ROOT add = f32[] add(p0, p1)
}
ENTRY AllReduce {
param0 = f32[3]{0} parameter(0)
param1 = f32[12,5]{0,1} parameter(1)
ROOT all-reduce = (bf16[3]{0}, bf16[12,5]{0,1}) all-reduce(param0, param1), to_apply=sum, replica_groups={}
}
)";
TF_ASSERT_OK_AND_ASSIGN(auto module,
ParseAndReturnVerifiedModule(hlo_string));
HloControlFlowFlattening flattening(
HloControlFlowFlattening::Options{3});
EXPECT_TRUE(flattening.Run(module.get()).value());
TF_ASSERT_OK(HloVerifier(true,
true)
.Run(module.get())
.status());
EXPECT_THAT(module->entry_computation()->root_instruction(),
op::CustomCall(op::Parameter(0), op::Parameter(1)));
EXPECT_EQ(module->entry_computation()->root_instruction()->name(),
"all-reduce");
}
TEST_F(HloControlFlowFlatteningTest, AllReduceStartAndDone) {
absl::string_view hlo_string = R"(
HloModule CRS
add {
lhs = f32[] parameter(0)
rhs = f32[] parameter(1)
ROOT add = f32[] add(lhs, rhs)
}
ENTRY CRS {
input = f32[8]{0} parameter(0)
crs = f32[8]{0} all-reduce-start(input), replica_groups={}, to_apply=add
ROOT done = f32[8]{0} all-reduce-done(crs)
}
)";
TF_ASSERT_OK_AND_ASSIGN(auto module,
ParseAndReturnVerifiedModule(hlo_string));
HloControlFlowFlattening flattening(
HloControlFlowFlattening::Options{3});
EXPECT_TRUE(flattening.Run(module.get()).value());
TF_ASSERT_OK(HloVerifier(true,
true)
.Run(module.get())
.status());
EXPECT_THAT(module->entry_computation()->root_instruction(),
op::CustomCall(op::CustomCall(op::Parameter(0))));
EXPECT_EQ(module->entry_computation()->root_instruction()->name(), "done");
EXPECT_EQ(module->entry_computation()->root_instruction()->operand(0)->name(),
"crs");
}
TEST_F(HloControlFlowFlatteningTest, AllGather) {
absl::string_view hlo_string = R"(
HloModule AllGather
ENTRY AllGather {
input = f32[128,32]{0,1} parameter(0)
ROOT ag = f32[128,128]{0,1} all-gather(input), replica_groups={}, dimensions={1}
}
)";
TF_ASSERT_OK_AND_ASSIGN(auto module,
ParseAndReturnVerifiedModule(hlo_string));
HloControlFlowFlattening flattening(
HloControlFlowFlattening::Options{3});
EXPECT_TRUE(flattening.Run(module.get()).value());
TF_ASSERT_OK(HloVerifier(true,
true)
.Run(module.get())
.status());
EXPECT_THAT(module->entry_computation()->root_instruction(),
op::CustomCall(op::Parameter(0)));
EXPECT_EQ(module->entry_computation()->root_instruction()->name(), "ag");
}
TEST_F(HloControlFlowFlatteningTest, AllToAll) {
absl::string_view hlo_string = R"(
HloModule AllToAll
ENTRY AllToAll {
input = f32[128,32]{0,1} parameter(0)
ROOT a2a = (f32[128,32]{0,1}) all-to-all(input), replica_groups={}
}
)";
TF_ASSERT_OK_AND_ASSIGN(auto module,
ParseAndReturnVerifiedModule(hlo_string));
HloControlFlowFlattening flattening(
HloControlFlowFlattening::Options{3});
EXPECT_TRUE(flattening.Run(module.get()).value());
TF_ASSERT_OK(HloVerifier(true,
true)
.Run(module.get())
.status());
EXPECT_THAT(module->entry_computation()->root_instruction(),
op::CustomCall(op::Parameter(0)));
EXPECT_EQ(module->entry_computation()->root_instruction()->name(), "a2a");
}
TEST_F(HloControlFlowFlatteningTest, CollectivePermute) {
absl::string_view hlo_string = R"(
HloModule CollectivePermute
ENTRY CollectivePermute {
input = f32[128,32]{0,1} parameter(0)
ROOT collective-permute = f32[128,32]{0,1} collective-permute(input), source_target_pairs={{0,1},{1,2},{2,3}}
}
)";
TF_ASSERT_OK_AND_ASSIGN(auto module,
ParseAndReturnVerifiedModule(hlo_string));
HloControlFlowFlattening flattening(
HloControlFlowFlattening::Options{3});
EXPECT_TRUE(flattening.Run(module.get()).value());
TF_ASSERT_OK(HloVerifier(true,
true)
.Run(module.get())
.status());
EXPECT_THAT(module->entry_computation()->root_instruction(),
op::CustomCall(op::Parameter(0)));
EXPECT_EQ(module->entry_computation()->root_instruction()->name(),
"collective-permute");
}
TEST_F(HloControlFlowFlatteningTest, ReplicaIdSucceedsWithChange) {
absl::string_view hlo_string = R"(
HloModule ReplicaId
ENTRY ReplicaId {
ROOT replica-id.18600 = u32[]{:T(128)} replica-id()
}
)";
TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<VerifiedHloModule> module,
ParseAndReturnVerifiedModule(hlo_string));
HloControlFlowFlattening flattening(HloControlFlowFlattening::Options{});
EXPECT_TRUE(flattening.Run(module.get()).value());
TF_ASSERT_OK(HloVerifier(true,
true)
.Run(module.get())
.status());
EXPECT_THAT(module->entry_computation()->root_instruction(), op::Constant());
EXPECT_EQ(module->entry_computation()->root_instruction()->name(),
"replica-id.18600");
}
TEST_F(HloControlFlowFlatteningTest, CollectivePermuteInPlaceUpdate) {
absl::string_view hlo_string = R"(
HloModule CollectivePermuteInPlaceUpdate
ENTRY CollectivePermuteInPlaceUpdate {
input = f32[128,32]{0,1} parameter(0)
constant = f32[] constant(1)
output = f32[128,128]{0,1} broadcast(constant), dimensions={}
constant.1 = s32[] constant(0)
tuple.1 = (s32[], s32[]) tuple(constant.1, constant.1)
constant.2 = s32[] constant(64)
tuple.2 = (s32[], s32[]) tuple(constant.1, constant.2)
ROOT collective-permute = f32[128,128]{0,1} collective-permute(input, output, tuple.1, tuple.2), source_target_pairs={{0,1},{1,2},{2,3}}, slice_sizes={{128,32}}
}
)";
TF_ASSERT_OK_AND_ASSIGN(auto module,
ParseAndReturnVerifiedModule(hlo_string));
HloControlFlowFlattening flattening(
HloControlFlowFlattening::Options{3});
EXPECT_TRUE(flattening.Run(module.get()).value());
TF_ASSERT_OK(HloVerifier(true,
true)
.Run(module.get())
.status());
EXPECT_THAT(module->entry_computation()->root_instruction(),
op::CustomCall(op::Parameter(0), op::Broadcast(op::Constant()),
op::Tuple(op::Constant(), op::Constant()),
op::Tuple(op::Constant(), op::Constant())));
EXPECT_EQ(module->entry_computation()->root_instruction()->name(),
"collective-permute");
}
TEST_F(HloControlFlowFlatteningTest, CollectivePermuteStartAndDone) {
absl::string_view hlo_string = R"(
HloModule CollectivePermuteStartAndDone
ENTRY CollectivePermuteStartAndDone {
input = f32[128,32]{0,1} parameter(0)
collective-permute-start.1 = (f32[128,32]{0,1}, f32[128,32]{0,1}, u32[], u32[]) collective-permute-start(input), source_target_pairs={{0,1},{1,2},{2,3}}
ROOT collective-permute-done.1 = f32[128,32]{0,1} collective-permute-done(collective-permute-start.1)
}
)";
TF_ASSERT_OK_AND_ASSIGN(auto module,
ParseAndReturnVerifiedModule(hlo_string));
HloControlFlowFlattening flattening(
HloControlFlowFlattening::Options{3});
EXPECT_TRUE(flattening.Run(module.get()).value());
TF_ASSERT_OK(HloVerifier(true,
true)
.Run(module.get())
.status());
EXPECT_THAT(module->entry_computation()->root_instruction(),
op::CustomCall(op::CustomCall(op::Parameter(0))));
EXPECT_EQ(module->entry_computation()->root_instruction()->name(),
"collective-permute-done.1");
EXPECT_EQ(module->entry_computation()->root_instruction()->operand(0)->name(),
"collective-permute-start.1");
}
TEST_F(HloControlFlowFlatteningTest, Recv) {
absl::string_view hlo_string = R"(
HloModule Recv
ENTRY %Recv () -> (f32[], token[]) {
%token0 = token[] after-all()
%recv = (f32[], u32[], token[]) recv(token[] %token0), channel_id=15
ROOT %recv-done = (f32[], token[]) recv-done((f32[], u32[], token[]) %recv), channel_id=15
%constant = f32[] constant(2.1)
%send = (f32[], u32[], token[]) send(f32[] %constant, token[] %token0), channel_id=16, control-predecessors={%recv}
%send-done = token[] send-done((f32[], u32[], token[]) %send), channel_id=16
}
)";
TF_ASSERT_OK_AND_ASSIGN(auto module,
ParseAndReturnVerifiedModule(hlo_string));
ControlDepRemover control_remover;
HloControlFlowFlattening flattening(
HloControlFlowFlattening::Options{3});
TF_ASSERT_OK(control_remover.Run(module.get()).status());
EXPECT_TRUE(flattening.Run(module.get()).value());
TF_ASSERT_OK(HloVerifier(true,
true)
.Run(module.get())
.status());
EXPECT_THAT(module->entry_computation()->root_instruction(),
op::CustomCall(op::CustomCall()));
EXPECT_EQ(module->entry_computation()->root_instruction()->name(),
"recv-done");
EXPECT_EQ(module->entry_computation()->root_instruction()->operand(0)->name(),
"recv");
}
TEST_F(HloControlFlowFlatteningTest, RecvHostTransfer) {
absl::string_view hlo_string = R"(
HloModule Recv
ENTRY %Recv () -> (f32[], token[]) {
%token0 = token[] after-all()
%recv = (f32[], u32[], token[]) recv(token[] %token0), channel_id=15, is_host_transfer=true
ROOT %recv-done = (f32[], token[]) recv-done((f32[], u32[], token[]) %recv), channel_id=15, is_host_transfer=true
%constant = f32[] constant(2.1)
%send = (f32[], u32[], token[]) send(f32[] %constant, token[] %token0), channel_id=16, control-predecessors={%recv}
%send-done = token[] send-done((f32[], u32[], token[]) %send), channel_id=16
}
)";
TF_ASSERT_OK_AND_ASSIGN(auto module,
ParseAndReturnVerifiedModule(hlo_string));
ControlDepRemover control_remover;
HloControlFlowFlattening flattening(HloControlFlowFlattening::Options{
3, 3,
3, true,
true, false,
true});
TF_ASSERT_OK(control_remover.Run(module.get()).status());
EXPECT_TRUE(flattening.Run(module.get()).value());
TF_ASSERT_OK(HloVerifier(true,
true)
.Run(module.get())
.status());
EXPECT_THAT(module->entry_computation()->root_instruction(),
op::CustomCall(op::CustomCall()));
EXPECT_EQ(module->entry_computation()->root_instruction()->name(),
"recv-done");
EXPECT_EQ(module->entry_computation()->root_instruction()->operand(0)->name(),
"recv");
}
TEST_F(HloControlFlowFlatteningTest, Send) {
absl::string_view hlo_string = R"(
HloModule Send
ENTRY %Send () -> token[] {
%token0 = token[] after-all()
%recv = (f32[], u32[], token[]) recv(token[] %token0), channel_id=15
%recv-done = (f32[], token[]) recv-done((f32[], u32[], token[]) %recv), channel_id=15
%constant = f32[] constant(2.1)
%send = (f32[], u32[], token[]) send(f32[] %constant, token[] %token0), channel_id=16, control-predecessors={%recv}
ROOT %send-done = token[] send-done((f32[], u32[], token[]) %send), channel_id=16
}
)";
TF_ASSERT_OK_AND_ASSIGN(auto module,
ParseAndReturnVerifiedModule(hlo_string));
ControlDepRemover control_remover;
HloControlFlowFlattening flattening(
HloControlFlowFlattening::Options{3});
TF_ASSERT_OK(control_remover.Run(module.get()).status());
EXPECT_TRUE(flattening.Run(module.get()).value());
TF_ASSERT_OK(HloVerifier(true,
true)
.Run(module.get())
.status());
EXPECT_THAT(module->entry_computation()->root_instruction(),
op::CustomCall(op::CustomCall()));
EXPECT_EQ(module->entry_computation()->root_instruction()->name(),
"send-done");
EXPECT_EQ(module->entry_computation()->root_instruction()->operand(0)->name(),
"send");
}
TEST_F(HloControlFlowFlatteningTest, SendHostTransfer) {
absl::string_view hlo_string = R"(
HloModule Send
ENTRY %Send () -> token[] {
%token0 = token[] after-all()
%recv = (f32[], u32[], token[]) recv(token[] %token0), channel_id=15
%recv-done = (f32[], token[]) recv-done((f32[], u32[], token[]) %recv), channel_id=15
%constant = f32[] constant(2.1)
%send = (f32[], u32[], token[]) send(f32[] %constant, token[] %token0), channel_id=16, is_host_transfer=true, control-predecessors={%recv}
ROOT %send-done = token[] send-done((f32[], u32[], token[]) %send), channel_id=16, is_host_transfer=true
}
)";
TF_ASSERT_OK_AND_ASSIGN(auto module,
ParseAndReturnVerifiedModule(hlo_string));
ControlDepRemover control_remover;
HloControlFlowFlattening flattening(HloControlFlowFlattening::Options{
3, 3,
3, true,
true, false,
true});
TF_ASSERT_OK(control_remover.Run(module.get()).status());
EXPECT_TRUE(flattening.Run(module.get()).value());
TF_ASSERT_OK(HloVerifier(true,
true)
.Run(module.get())
.status());
EXPECT_THAT(module->entry_computation()->root_instruction(),
op::CustomCall(op::CustomCall()));
EXPECT_EQ(module->entry_computation()->root_instruction()->name(),
"send-done");
EXPECT_EQ(module->entry_computation()->root_instruction()->operand(0)->name(),
"send");
}
TEST_F(HloControlFlowFlatteningTest, AllGatherStartAndDone) {
absl::string_view hlo_string = R"(
HloModule AllGatherStartAndDone
ENTRY AllGatherStartAndDone {
%input = f32[8,256,256] parameter(0)
%ag-start = (f32[8,256,256], f32[16,256,256]) all-gather-start(
f32[8,256,256] %input), replica_groups={{0,1}}, dimensions={0},
metadata={op_type="AllGather" op_name="ag0"}
ROOT %ag-done = f32[16,256,256] all-gather-done(
(f32[8,256,256], f32[16,256,256]) %ag-start),
metadata={op_type="AllGather" op_name="ag0"}
}
)";
TF_ASSERT_OK_AND_ASSIGN(auto module,
ParseAndReturnVerifiedModule(hlo_string));
HloControlFlowFlattening flattening(
HloControlFlowFlattening::Options{3});
EXPECT_TRUE(flattening.Run(module.get()).value());
TF_ASSERT_OK(HloVerifier(true,
true)
.Run(module.get())
.status());
EXPECT_THAT(module->entry_computation()->root_instruction(),
op::CustomCall(op::CustomCall(op::Parameter(0))));
EXPECT_EQ(module->entry_computation()->root_instruction()->name(), "ag-done");
EXPECT_EQ(module->entry_computation()->root_instruction()->operand(0)->name(),
"ag-start");
}
TEST_F(HloControlFlowFlatteningTest, CollectiveFusion) {
absl::string_view hlo_template = R"(
HloModule collective-fusion, is_scheduled=true
%sum (a: f32[], b: f32[]) -> f32[] {
%a = f32[] parameter(0)
%b = f32[] parameter(1)
ROOT %add = f32[] add(f32[] a, f32[] b)
}
%all-gather {
%constant.3 = f32[] constant(0)
%broadcast = f32[full_size,8,128]{2,1,0} broadcast(%constant.3), dimensions={}
%input.0 = f32[4,8,128]{2,1,0} parameter(0)
%input.1 = f32[4,8,128]{2,1,0} parameter(1)
%replica-id.1 = u32[] replica-id()
%constant.4 = u32[] constant(4) | 2,187 |
#ifndef XLA_TOOLS_XLA_COMPILE_LIB_H_
#define XLA_TOOLS_XLA_COMPILE_LIB_H_
#include <memory>
#include <optional>
#include <string>
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/string_view.h"
#include "xla/hlo/ir/hlo_module.h"
#include "xla/service/compiler.h"
#include "xla/service/symbol_repository.h"
#include "xla/service/xla_compile_result.pb.h"
#include "xla/util.h"
namespace xla {
absl::StatusOr<std::string> CompileExecutable(
std::unique_ptr<HloModule> hlo_module, BackendType backend,
std::optional<Compiler::TargetConfig> target_config,
CompilationResult& result);
absl::Status WriteResultFile(absl::string_view result_output_file,
TimerStats& stats,
CompilationResult& compilation_result);
absl::StatusOr<std::unique_ptr<HloModule>> LoadModule(
absl::string_view module_path);
struct XlaCompileOptions {
std::string module_path;
std::string output_path;
std::string platform;
std::string result_output_file;
struct SymbolRepoOptions {
std::string symbol_repo;
std::string symbol_id;
std::string optimized_symbol_id;
bool wait_for_uploads = false;
};
struct GpuOptions {
std::string gpu_target_config_path;
bool use_attached_device = false;
std::string autotune_results_path;
};
SymbolRepoOptions repo_options;
GpuOptions gpu_options;
};
absl::Status XlaCompileMain(const XlaCompileOptions& compile_options);
}
#endif
#include "xla/tools/xla_compile_lib.h"
#include <cmath>
#include <memory>
#include <optional>
#include <string>
#include <utility>
#include <vector>
#include "google/protobuf/duration.pb.h"
#include "absl/cleanup/cleanup.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/synchronization/mutex.h"
#include "mlir/Dialect/Arith/IR/Arith.h"
#include "mlir/Dialect/Func/IR/FuncOps.h"
#include "mlir/IR/BuiltinOps.h"
#include "mlir/IR/DialectRegistry.h"
#include "mlir/IR/MLIRContext.h"
#include "mlir/IR/OwningOpRef.h"
#include "mlir/Parser/Parser.h"
#include "stablehlo/dialect/Register.h"
#include "xla/client/xla_computation.h"
#include "xla/debug_options_flags.h"
#include "xla/hlo/ir/hlo_module.h"
#include "xla/hlo/ir/hlo_module_group.h"
#include "xla/mlir_hlo/mhlo/IR/hlo_ops.h"
#include "xla/pjrt/mlir_to_hlo.h"
#include "xla/service/compiler.h"
#include "xla/service/cpu/cpu_compiler.h"
#include "xla/service/cpu/cpu_executable.h"
#include "xla/service/executable.h"
#include "xla/service/export_hlo.h"
#include "xla/service/hlo.pb.h"
#include "xla/service/hlo_module_config.h"
#include "xla/service/symbol_repository.h"
#include "xla/service/xla_compile_result.pb.h"
#include "xla/shape.h"
#include "xla/stream_executor/device_memory_allocator.h"
#include "xla/stream_executor/stream_executor.h"
#include "xla/stream_executor/stream_executor_memory_allocator.h"
#include "xla/tools/hlo_module_loader.h"
#include "xla/util.h"
#include "tsl/platform/env.h"
#include "tsl/platform/env_time.h"
#include "tsl/platform/errors.h"
#include "tsl/platform/path.h"
#include "tsl/platform/protobuf.h"
#include "tsl/platform/status.h"
#include "tsl/platform/status_to_from_proto.h"
#include "tsl/platform/statusor.h"
#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM
#include "xla/service/gpu/autotuner_util.h"
#include "xla/service/gpu/executable.pb.h"
#include "xla/service/gpu/gpu_symbol_repository.h"
#include "xla/stream_executor/gpu/gpu_init.h"
#endif
#if GOOGLE_CUDA
#include "xla/service/gpu/nvptx_compiler.h"
#elif TENSORFLOW_USE_ROCM
#include "xla/service/gpu/amdgpu_compiler.h"
#endif
namespace xla {
static absl::StatusOr<std::string> AotCompileCpuExecutable(
std::unique_ptr<HloModule> hlo_module) {
cpu::CpuCompiler cpu_compiler;
auto module_group = std::make_unique<HloModuleGroup>(std::move(hlo_module));
TF_ASSIGN_OR_RETURN(
std::vector<std::unique_ptr<Executable>> executables,
cpu_compiler.Compile(std::move(module_group), {{nullptr}}, {nullptr}));
TF_ASSIGN_OR_RETURN(std::unique_ptr<AotCompilationResult> aot_result,
cpu_compiler.Export(executables[0].get()));
return aot_result->SerializeAsString();
}
static absl::StatusOr<std::string> CompileGpuExecutable(
std::unique_ptr<HloModule> hlo_module,
std::optional<Compiler::TargetConfig> target_config,
CompilationResult& result) {
#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM
const bool aot = target_config.has_value();
#if GOOGLE_CUDA
auto gpu_compiler = gpu::NVPTXCompiler();
#elif TENSORFLOW_USE_ROCM
auto gpu_compiler = gpu::AMDGPUCompiler();
#endif
auto module_group = std::make_unique<HloModuleGroup>(std::move(hlo_module));
if (aot) {
AotCompilationOptions aot_options(gpu_compiler.PlatformId());
aot_options.set_target_config(*target_config);
aot_options.set_run_backend_only(true);
TF_ASSIGN_OR_RETURN(
std::vector<std::unique_ptr<AotCompilationResult>> aot_results,
gpu_compiler.CompileAheadOfTime(std::move(module_group), aot_options));
TF_ASSIGN_OR_RETURN(std::string compile_result,
aot_results[0]->SerializeAsString());
*result.mutable_hlo_module() =
aot_results[0]->optimized_module()->ToProto();
return compile_result;
}
Compiler::CompileOptions compile_options;
TF_RETURN_IF_ERROR(stream_executor::ValidateGPUMachineManager());
TF_ASSIGN_OR_RETURN(
stream_executor::StreamExecutor * stream_executor,
stream_executor::GPUMachineManager()->ExecutorForDevice(0));
auto allocator =
std::make_unique<stream_executor::StreamExecutorMemoryAllocator>(
stream_executor);
compile_options.device_allocator = allocator.get();
TF_ASSIGN_OR_RETURN(
std::vector<std::unique_ptr<Executable>> executables,
gpu_compiler.Compile(std::move(module_group), {{stream_executor}},
compile_options));
*result.mutable_hlo_module() = executables[0]->module().ToProto();
return executables[0]->module().ToString();
#else
LOG(ERROR) << "Neither ROCm nor CUDA present; returning empty.";
return "";
#endif
}
absl::StatusOr<std::string> CompileExecutable(
std::unique_ptr<HloModule> hlo_module, BackendType backend,
std::optional<Compiler::TargetConfig> target_config,
CompilationResult& result) {
if (backend == BackendType::kCpu) {
return AotCompileCpuExecutable(std::move(hlo_module));
}
return CompileGpuExecutable(std::move(hlo_module), std::move(target_config),
result);
}
absl::Status WriteResultFile(const absl::string_view result_output_file,
TimerStats& stats,
CompilationResult& compilation_result) {
if (result_output_file.empty()) {
return absl::OkStatus();
}
absl::MutexLock ml(&stats.stats_mutex);
const double secs = std::floor(stats.cumulative_secs);
const double nanos =
(stats.cumulative_secs - secs) * tsl::EnvTime::kSecondsToNanos;
google::protobuf::Duration duration;
duration.set_seconds(secs);
duration.set_nanos(nanos);
*compilation_result.mutable_perf_stats()->mutable_compilation_duration() =
duration;
*compilation_result.mutable_perf_stats()->mutable_total_duration() = duration;
return tsl::WriteBinaryProto(
tsl::Env::Default(), std::string(result_output_file), compilation_result);
}
absl::StatusOr<std::unique_ptr<HloModule>> LoadModule(
const absl::string_view module_path) {
auto format = std::string(tsl::io::Extension(module_path));
if (format == "hlo" || format == "txt" || format == "pb") {
return LoadModuleFromFile(
std::string(module_path), format, hlo_module_loader_details::Config(),
[&](HloModuleConfig* c) {}, nullptr);
}
std::string module_string;
TF_RETURN_IF_ERROR(tsl::ReadFileToString(
tsl::Env::Default(), std::string(module_path), &module_string));
mlir::DialectRegistry dialects;
dialects.insert<mlir::arith::ArithDialect>();
dialects.insert<mlir::mhlo::MhloDialect>();
dialects.insert<mlir::func::FuncDialect>();
mlir::stablehlo::registerAllDialects(dialects);
auto threading = mlir::MLIRContext::Threading::DISABLED;
auto ctx = std::make_unique<mlir::MLIRContext>(dialects, threading);
mlir::OwningOpRef<mlir::ModuleOp> module =
mlir::parseSourceString<mlir::ModuleOp>(module_string, ctx.get());
XlaComputation xla_computation;
TF_RETURN_IF_ERROR(
MlirToXlaComputation(*module, xla_computation, false, false));
HloModuleProto hlo_module_proto = xla_computation.proto();
TF_ASSIGN_OR_RETURN(ProgramShape shape, xla_computation.GetProgramShape());
DebugOptions debug_options = GetDebugOptionsFromFlags();
HloModuleConfig config(shape);
config.set_debug_options(debug_options);
return HloModule::CreateFromProto(hlo_module_proto, config);
}
static absl::StatusOr<std::unique_ptr<HloModuleAndMetadata>>
ReadModuleFromSymbolRepo(absl::string_view symbol_repo,
absl::string_view symbol_reference,
BackendType backend) {
std::unique_ptr<HloModuleAndMetadata> mod;
TF_ASSIGN_OR_RETURN(
mod, LookupSymbolInRepository(symbol_repo, symbol_reference, backend));
if (mod == nullptr) {
return absl::NotFoundError(
absl::StrCat("Could not find ", symbol_reference, " in ", symbol_repo));
}
return mod;
}
static absl::StatusOr<bool> LoadAutotuneDataFromModule(
HloModuleAndMetadata* mod, BackendType backend) {
if (backend == BackendType::kGpu) {
#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM
if (auto* data = static_cast<gpu::GpuBackendSpecificData*>(
mod->backend_specific_data.get());
data != nullptr && data->autotune_results.has_value()) {
TF_RETURN_IF_ERROR(
gpu::AutotunerUtil::LoadAutotuneResults(*data->autotune_results));
return true;
}
#endif
}
return false;
}
static std::unique_ptr<Compiler::TargetConfig> ReadTargetConfigFromModule(
HloModuleAndMetadata* mod, BackendType backend) {
if (backend == BackendType::kGpu) {
#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM
if (auto* data = static_cast<gpu::GpuBackendSpecificData*>(
mod->backend_specific_data.get());
data != nullptr) {
return std::move(mod->target_config);
}
#endif
}
return nullptr;
}
absl::Status XlaCompileMain(const XlaCompileOptions& options) {
std::unique_ptr<HloModule> hlo_module;
std::unique_ptr<Compiler::TargetConfig> target_config;
if (options.platform != "cpu" && options.platform != "gpu") {
return absl::UnimplementedError(
absl::StrCat("platform", options.platform, " is not supported"));
}
const BackendType backend =
(options.platform == "gpu" ? BackendType::kGpu : BackendType::kCpu);
absl::string_view symbol_repo = options.repo_options.symbol_repo;
if (absl::string_view symbol_id = options.repo_options.symbol_id;
!symbol_id.empty()) {
TF_ASSIGN_OR_RETURN(
std::unique_ptr<HloModuleAndMetadata> mod,
ReadModuleFromSymbolRepo(symbol_repo, symbol_id, backend));
hlo_module = std::move(mod->hlo_module);
target_config = ReadTargetConfigFromModule(mod.get(), backend);
} else {
TF_ASSIGN_OR_RETURN(hlo_module, LoadModule(options.module_path));
}
#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM
bool found_autotune = false;
#endif
if (absl::string_view optimized_symbol_id =
options.repo_options.optimized_symbol_id;
!optimized_symbol_id.empty()) {
TF_ASSIGN_OR_RETURN(
std::unique_ptr<HloModuleAndMetadata> optimized_mod,
ReadModuleFromSymbolRepo(symbol_repo, optimized_symbol_id, backend));
#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM
TF_ASSIGN_OR_RETURN(found_autotune, LoadAutotuneDataFromModule(
optimized_mod.get(), backend));
#endif
}
xla::TimerStats stats;
xla::ScopedLoggingTimer timer("compilation", true, "xla_compile_main.cc", 1,
&stats);
CompilationResult compilation_result;
absl::Cleanup cleanup([&] {
timer.StopAndLog();
if (!options.result_output_file.empty()) {
TF_QCHECK_OK(WriteResultFile(options.result_output_file, stats,
compilation_result));
}
});
std::optional<Compiler::TargetConfig> cfg = std::nullopt;
if (backend == BackendType::kGpu) {
#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM
if (absl::string_view gpu_target_config_path =
options.gpu_options.gpu_target_config_path;
!gpu_target_config_path.empty()) {
std::string gpu_target_config_string;
TF_RETURN_IF_ERROR(tsl::ReadFileToString(
tsl::Env::Default(), std::string(gpu_target_config_path),
&gpu_target_config_string));
stream_executor::GpuTargetConfigProto gpu_target_config_proto;
if (!tsl::protobuf::TextFormat::ParseFromString(
gpu_target_config_string, &gpu_target_config_proto)) {
return FailedPrecondition("Failed to parse GpuTargetConfigProto");
}
target_config =
std::make_unique<Compiler::TargetConfig>(gpu_target_config_proto);
if (absl::string_view autotune_results_path =
options.gpu_options.autotune_results_path;
!found_autotune && !autotune_results_path.empty()) {
TF_RETURN_IF_ERROR(gpu::AutotunerUtil::LoadAutotuneResultsFromFile(
autotune_results_path));
}
}
cfg = (options.gpu_options.use_attached_device)
? std::nullopt
: std::make_optional(*std::move(target_config));
#endif
}
auto result = CompileExecutable(std::move(hlo_module), backend,
std::move(cfg), compilation_result);
*compilation_result.mutable_status() = tsl::StatusToProto(result.status());
if (!result.ok()) {
return result.status();
}
TF_RETURN_IF_ERROR(tsl::WriteStringToFile(tsl::Env::Default(),
options.output_path, *result));
if (options.repo_options.wait_for_uploads) {
MaybeWaitForUploads();
}
return absl::OkStatus();
}
} | #include "xla/tools/xla_compile_lib.h"
#include <memory>
#include <optional>
#include <string>
#include <utility>
#include "google/protobuf/duration.pb.h"
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "absl/strings/string_view.h"
#include "absl/synchronization/mutex.h"
#include "xla/hlo/ir/hlo_module.h"
#include "xla/service/platform_util.h"
#include "xla/service/symbol_repository.h"
#include "xla/service/xla_compile_result.pb.h"
#include "xla/stream_executor/device_description.pb.h"
#include "xla/tests/hlo_test_base.h"
#include "xla/tests/test_macros.h"
#include "xla/util.h"
#include "tsl/lib/core/status_test_util.h"
#include "tsl/platform/env.h"
#include "tsl/platform/env_time.h"
#include "tsl/platform/path.h"
#include "tsl/platform/status_matchers.h"
#include "tsl/platform/statusor.h"
#include "tsl/platform/test.h"
#include "tsl/protobuf/error_codes.pb.h"
#include "tsl/protobuf/status.pb.h"
namespace xla {
namespace {
using ::testing::IsEmpty;
using ::testing::IsNull;
using ::testing::Not;
using ::tsl::testing::IsOk;
using ::tsl::testing::IsOkAndHolds;
using ::tsl::testing::StatusIs;
#if XLA_TEST_BACKEND_CPU
static constexpr absl::string_view kPlatformName = "Host";
#elif XLA_TEST_BACKEND_GPU
static constexpr absl::string_view kPlatformName =
#if TENSORFLOW_USE_ROCM
"ROCM";
#else
"CUDA";
#endif
#endif
class XlaCompileLibTest : public HloTestBase {
protected:
XlaCompileLibTest()
: HloTestBase(*PlatformUtil::GetPlatform(std::string(kPlatformName)),
GetReferencePlatform()) {}
void SetUp() override {
const std::string hlo_path = tsl::io::JoinPath(tsl::testing::XlaSrcRoot(),
"tools", "data", "add.hlo");
std::string hlo;
TF_ASSERT_OK(tsl::ReadFileToString(tsl::Env::Default(), hlo_path, &hlo));
TF_ASSERT_OK_AND_ASSIGN(module_, ParseAndReturnVerifiedModule(hlo));
}
std::unique_ptr<HloModule> module_;
};
TEST_F(XlaCompileLibTest, DISABLED_ON_GPU(CompilesForCpu)) {
CompilationResult result;
EXPECT_THAT(CompileExecutable(std::move(module_), BackendType::kCpu,
std::nullopt, result),
IsOkAndHolds(Not(IsEmpty())));
}
TEST_F(XlaCompileLibTest, DISABLED_ON_CPU(CompilesForGpuWithDevice)) {
CompilationResult result;
EXPECT_THAT(CompileExecutable(std::move(module_), BackendType::kGpu,
std::nullopt, result),
IsOkAndHolds(Not(IsEmpty())));
EXPECT_TRUE(result.has_hlo_module()) << result.DebugString();
}
TEST_F(XlaCompileLibTest, DISABLED_ON_CPU(CompilesForGpuWithoutDevice)) {
const std::string target_config_path =
tsl::io::JoinPath(tsl::testing::XlaSrcRoot(), "service",
"xla_aot_compile_test_gpu_target_config.prototxt");
stream_executor::GpuTargetConfigProto target_config;
TF_ASSERT_OK(tsl::ReadTextProto(tsl::Env::Default(), target_config_path,
&target_config));
CompilationResult result;
EXPECT_THAT(CompileExecutable(std::move(module_), BackendType::kGpu,
std::nullopt, result),
IsOkAndHolds(Not(IsEmpty())));
EXPECT_TRUE(result.has_hlo_module()) << result.DebugString();
}
TEST_F(XlaCompileLibTest, DISABLED_ON_GPU(ErrorsOnUnexpectedPlatform)) {
XlaCompileOptions options;
options.platform = "tpu";
EXPECT_THAT(XlaCompileMain(options), StatusIs(tsl::error::UNIMPLEMENTED));
}
TEST_F(XlaCompileLibTest, DISABLED_ON_GPU(WriteResultFilePropagatesErrors)) {
TimerStats stats;
CompilationResult result;
EXPECT_THAT(WriteResultFile("/does/not/exist", stats, result), Not(IsOk()));
}
TEST_F(XlaCompileLibTest, DISABLED_ON_GPU(WriteResultFileWritesTheFile)) {
std::string result_output_file;
ASSERT_TRUE(tsl::Env::Default()->LocalTempFilename(&result_output_file));
TimerStats stats;
{
absl::MutexLock ml(&stats.stats_mutex);
stats.cumulative_secs = 5.5;
stats.max_secs = 5.5;
}
CompilationResult result;
google::protobuf::Duration duration;
duration.set_seconds(5);
duration.set_nanos(0.5 * tsl::EnvTime::kSecondsToNanos);
*result.mutable_perf_stats()->mutable_compilation_duration() = duration;
*result.mutable_perf_stats()->mutable_total_duration() = duration;
TF_ASSERT_OK(WriteResultFile(result_output_file, stats, result));
CompilationResult got_result;
TF_ASSERT_OK(tsl::ReadBinaryProto(tsl::Env::Default(), result_output_file,
&got_result));
EXPECT_EQ(5, got_result.perf_stats().compilation_duration().seconds());
EXPECT_EQ(0.5 * tsl::EnvTime::kSecondsToNanos,
got_result.perf_stats().compilation_duration().nanos());
EXPECT_EQ(5, got_result.perf_stats().total_duration().seconds());
EXPECT_EQ(0.5 * tsl::EnvTime::kSecondsToNanos,
got_result.perf_stats().total_duration().nanos());
}
TEST_F(XlaCompileLibTest, LoadModuleErrors) {
EXPECT_THAT(LoadModule("/does/not/exist"), Not(IsOk()));
}
TEST_F(XlaCompileLibTest, LoadModuleLoadsTextFormat) {
const std::string module_file =
tsl::io::JoinPath(tsl::testing::TmpDir(), "module.txt");
TF_ASSERT_OK(tsl::WriteStringToFile(tsl::Env::Default(), module_file,
module_->ToString()));
EXPECT_THAT(LoadModule(module_file), IsOkAndHolds(Not(IsNull())));
}
TEST_F(XlaCompileLibTest, DISABLED_ON_GPU(MainForCpu)) {
const std::string module_file =
tsl::io::JoinPath(tsl::testing::TmpDir(), "module.txt");
TF_ASSERT_OK(tsl::WriteStringToFile(tsl::Env::Default(), module_file,
module_->ToString()));
const std::string output_path =
tsl::io::JoinPath(tsl::testing::TmpDir(), "cpu_output");
const std::string result_file =
tsl::io::JoinPath(tsl::testing::TmpDir(), "cpu_result.pb");
XlaCompileOptions options;
options.module_path = module_file;
options.output_path = output_path;
options.platform = "cpu";
options.result_output_file = result_file;
TF_EXPECT_OK(XlaCompileMain(options));
CompilationResult result;
TF_ASSERT_OK(tsl::ReadBinaryProto(tsl::Env::Default(), result_file, &result));
EXPECT_TRUE(result.has_status());
EXPECT_EQ(result.status().code(), tensorflow::error::OK);
}
TEST_F(XlaCompileLibTest, DISABLED_ON_CPU(MainForGpu)) {
const std::string module_file =
tsl::io::JoinPath(tsl::testing::TmpDir(), "module.txt");
TF_ASSERT_OK(tsl::WriteStringToFile(tsl::Env::Default(), module_file,
module_->ToString()));
const std::string output_path =
tsl::io::JoinPath(tsl::testing::TmpDir(), "gpu_output");
const std::string result_file =
tsl::io::JoinPath(tsl::testing::TmpDir(), "gpu_result.pb");
XlaCompileOptions options;
options.module_path = module_file;
options.output_path = output_path;
options.platform = "gpu";
options.result_output_file = result_file;
options.gpu_options.use_attached_device = true;
TF_EXPECT_OK(XlaCompileMain(options));
CompilationResult result;
TF_ASSERT_OK(tsl::ReadBinaryProto(tsl::Env::Default(), result_file, &result));
EXPECT_TRUE(result.has_status());
EXPECT_EQ(result.status().code(), tensorflow::error::OK);
}
}
} | 2,188 |
#ifndef XLA_TOOLS_HLO_DECOMPOSER_H_
#define XLA_TOOLS_HLO_DECOMPOSER_H_
#include <memory>
#include <vector>
#include "absl/status/statusor.h"
#include "xla/hlo/ir/hlo_computation.h"
#include "xla/hlo/ir/hlo_instruction.h"
#include "xla/hlo/ir/hlo_module.h"
namespace xla {
absl::StatusOr<std::vector<std::unique_ptr<HloModule>>> DecomposeHloModule(
const HloModule& module, bool deduplicate_modules);
std::unique_ptr<HloModule> ExtractInstructionIntoNewModule(
const HloInstruction& hlo);
std::unique_ptr<HloModule> ExtractInstructionIntoNewModule(
const std::vector<HloInstruction*>& instructions);
std::unique_ptr<HloModule> ExtractProducerConsumerIntoNewModule(
const HloInstruction& producer, const HloInstruction& consumer);
std::unique_ptr<HloModule> ExtractComputationIntoNewModule(
const HloComputation& computation);
}
#endif
#include "xla/tools/hlo_decomposer.h"
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "absl/container/flat_hash_map.h"
#include "absl/container/flat_hash_set.h"
#include "absl/container/inlined_vector.h"
#include "absl/log/check.h"
#include "absl/status/status.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/hlo/ir/hlo_opcode.h"
#include "xla/service/call_graph.h"
#include "xla/service/compilation_environments.h"
#include "tsl/platform/statusor.h"
namespace xla {
namespace {
bool ShouldIsolateOpcode(HloOpcode opcode) {
switch (opcode) {
case HloOpcode::kConstant:
case HloOpcode::kGetTupleElement:
case HloOpcode::kParameter:
case HloOpcode::kTuple:
return false;
default:
return true;
}
}
absl::StatusOr<std::vector<std::unique_ptr<HloModule>>> Decompose(
const HloModule& module) {
std::vector<std::unique_ptr<HloModule>> modules;
absl::flat_hash_set<const HloComputation*> computations_to_visit{
module.entry_computation()};
absl::flat_hash_set<const HloComputation*> visited_computations;
while (!computations_to_visit.empty()) {
const HloComputation* computation = *computations_to_visit.begin();
computations_to_visit.erase(computations_to_visit.begin());
visited_computations.insert(computation);
for (const HloInstruction* instruction : computation->instructions()) {
if (GetInstructionCallContext(instruction->opcode()) !=
CallContext::kEmbedded) {
for (const HloComputation* called_computation :
instruction->called_computations()) {
if (!visited_computations.contains(called_computation)) {
computations_to_visit.insert(called_computation);
}
}
}
if (ShouldIsolateOpcode(instruction->opcode())) {
modules.push_back(ExtractInstructionIntoNewModule(*instruction));
}
}
}
return modules;
}
}
absl::StatusOr<std::vector<std::unique_ptr<HloModule>>> DecomposeHloModule(
const HloModule& module, bool deduplicate_modules) {
std::vector<std::unique_ptr<HloModule>> modules;
absl::flat_hash_set<std::string> module_fingerprints;
auto should_add_module = [&](const HloModule* module) {
if (!deduplicate_modules) {
return true;
}
const std::string fingerprint = module->GetFingerprint128();
if (module_fingerprints.contains(fingerprint)) {
return false;
}
module_fingerprints.insert(fingerprint);
return true;
};
TF_ASSIGN_OR_RETURN(std::vector<std::unique_ptr<HloModule>> isolated_modules,
Decompose(module));
for (auto& module : isolated_modules) {
if (should_add_module(module.get())) {
modules.push_back(std::move(module));
}
}
return modules;
}
std::unique_ptr<HloModule> ExtractInstructionIntoNewModule(
const std::vector<HloInstruction*>& instructions) {
CHECK(!instructions.empty());
HloInstruction& first_instruction = *instructions[0];
auto new_hlo_module = std::make_unique<HloModule>(
first_instruction.GetModule()->name() + "_collective_ops",
HloModuleConfig{},
std::make_unique<CompilationEnvironments>(
first_instruction.GetModule()->comp_envs()));
int parameter_number = 0;
HloComputation::Builder builder("entry_computation");
HloCloneContext clone_context(new_hlo_module.get());
std::vector<HloInstruction*> new_instructions;
for (auto* hlo : instructions) {
std::vector<HloInstruction*> new_operands;
for (const HloInstruction* operand : hlo->operands()) {
std::unique_ptr<HloInstruction> new_parameter =
HloInstruction::CreateParameter(parameter_number, operand->shape(),
operand->name());
++parameter_number;
new_operands.push_back(builder.AddInstruction(std::move(new_parameter)));
}
std::unique_ptr<HloInstruction> new_instruction =
hlo->CloneWithNewOperands(hlo->shape(), new_operands, &clone_context);
new_instructions.push_back(
builder.AddInstruction(std::move(new_instruction)));
}
std::unique_ptr<HloInstruction> tuple_instruction =
HloInstruction::CreateTuple(new_instructions);
builder.AddInstruction(std::move(tuple_instruction));
new_hlo_module->AddEntryComputationWithLayouts(builder.Build());
return new_hlo_module;
}
std::unique_ptr<HloModule> ExtractInstructionIntoNewModule(
const HloInstruction& hlo) {
auto new_hlo_module = std::make_unique<HloModule>(
std::string(hlo.name()), HloModuleConfig{},
std::make_unique<CompilationEnvironments>(hlo.GetModule()->comp_envs()));
int parameter_number = 0;
HloComputation::Builder builder("entry_computation");
HloCloneContext clone_context(new_hlo_module.get());
std::vector<HloInstruction*> new_operands;
for (const HloInstruction* operand : hlo.operands()) {
std::unique_ptr<HloInstruction> new_parameter =
HloInstruction::CreateParameter(parameter_number, operand->shape(),
operand->name());
++parameter_number;
new_operands.push_back(builder.AddInstruction(std::move(new_parameter)));
}
std::unique_ptr<HloInstruction> new_instruction =
hlo.CloneWithNewOperands(hlo.shape(), new_operands, &clone_context);
builder.AddInstruction(std::move(new_instruction));
new_hlo_module->AddEntryComputationWithLayouts(builder.Build());
return new_hlo_module;
}
std::unique_ptr<HloModule> ExtractProducerConsumerIntoNewModule(
const HloInstruction& producer, const HloInstruction& consumer) {
auto new_hlo_module =
std::make_unique<HloModule>("extracted", HloModuleConfig{},
std::make_unique<CompilationEnvironments>(
consumer.GetModule()->comp_envs()));
int parameter_number = 0;
HloComputation::Builder builder("entry_computation");
HloCloneContext clone_context(new_hlo_module.get());
absl::InlinedVector<HloInstruction*, 8> producer_operands;
for (const HloInstruction* operand : producer.operands()) {
HloInstruction* new_parameter =
builder.AddInstruction(HloInstruction::CreateParameter(
parameter_number, operand->shape(), operand->name()));
++parameter_number;
producer_operands.push_back(new_parameter);
}
HloInstruction* new_producer =
builder.AddInstruction(producer.CloneWithNewOperands(
producer.shape(), producer_operands, &clone_context));
absl::flat_hash_map<const HloInstruction*, HloInstruction*> operand_map;
operand_map.emplace(&producer, new_producer);
absl::InlinedVector<HloInstruction*, 8> consumer_operands;
for (const HloInstruction* operand : consumer.operands()) {
auto it = operand_map.find(operand);
if (it != operand_map.end()) {
consumer_operands.push_back(it->second);
} else {
HloInstruction* new_parameter =
builder.AddInstruction(HloInstruction::CreateParameter(
parameter_number, operand->shape(), operand->name()));
++parameter_number;
consumer_operands.push_back(new_parameter);
}
}
builder.AddInstruction(consumer.CloneWithNewOperands(
consumer.shape(), consumer_operands, &clone_context));
new_hlo_module->AddEntryComputationWithLayouts(builder.Build());
return new_hlo_module;
}
std::unique_ptr<HloModule> ExtractComputationIntoNewModule(
const HloComputation& computation) {
auto new_hlo_module =
std::make_unique<HloModule>("extracted", HloModuleConfig{},
std::make_unique<CompilationEnvironments>(
computation.parent()->comp_envs()));
HloCloneContext clone_context(new_hlo_module.get());
new_hlo_module->AddEntryComputationWithLayouts(
computation.CloneInContext(clone_context));
return new_hlo_module;
}
} | #include "xla/tools/hlo_decomposer.h"
#include <memory>
#include <vector>
#include <gtest/gtest.h>
#include "absl/algorithm/container.h"
#include "absl/strings/string_view.h"
#include "xla/hlo/ir/hlo_module.h"
#include "xla/tests/filecheck.h"
#include "xla/tests/hlo_test_base.h"
#include "tsl/platform/statusor.h"
namespace xla {
namespace {
class HloDecomposerTest : public HloTestBase {
protected:
std::unique_ptr<HloModule> GetModule() {
absl::string_view kHlo = R"(
HloModule test_module, entry_computation_layout={(bf16[1024,8192]{1,0}, f32[8192]{0}, f32[16384]{0})->(bf16[1024]{0}, bf16[1024]{0}, f32[16384]{0}, f32[16384]{0})}
add {
p0 = f32[] parameter(0)
p1 = f32[] parameter(1)
ROOT add.1 = f32[] add(p0, p1)
}
fused_computation.1 {
param_1.3 = f32[8192]{0} parameter(1)
broadcast.2 = f32[1024,8192]{1,0} broadcast(param_1.3), dimensions={1}
param_0.3 = bf16[1024,8192]{1,0} parameter(0)
convert.5 = f32[1024,8192]{1,0} convert(param_0.3)
multiply.2 = f32[1024,8192]{1,0} multiply(broadcast.2, convert.5)
c0_1 = f32[] constant(0)
reduce.1 = f32[1024]{0} reduce(multiply.2, c0_1), dimensions={1}, to_apply=add
ROOT convert.4 = bf16[1024]{0} convert(reduce.1)
}
fused_computation.2 {
p0.0 = bf16[1024,8192]{1,0} parameter(0)
c.0 = f32[1024,8192]{1,0} convert(p0.0)
co0_1.1 = f32[] constant(0)
p.0 = f32[8192]{0} parameter(1)
b.0 = f32[1024,8192]{1,0} broadcast(p.0), dimensions={1}
m.0 = f32[1024,8192]{1,0} multiply(b.0, c.0)
r.0 = f32[1024]{0} reduce(m.0, co0_1.1), dimensions={1}, to_apply=add
ROOT c.1 = bf16[1024]{0} convert(r.0)
}
exp {
param_0.5 = f32[16384]{0} parameter(0)
m.4 = f32[16384]{0} multiply(param_0.5, param_0.5)
e = f32[16384]{0} exponential(m.4)
l.clone.1 = f32[16384]{0} log(m.4)
ROOT tuple = (f32[16384]{0}, f32[16384]{0}) tuple(e, l.clone.1)
}
ENTRY main {
p0.1 = bf16[1024,8192]{1,0} parameter(0)
p1.1 = f32[8192]{0} parameter(1)
fusion.1 = bf16[1024]{0} fusion(p0.1, p1.1), kind=kInput, calls=fused_computation.1
fusion.2 = bf16[1024]{0} fusion(p0.1, p1.1), kind=kInput, calls=fused_computation.2
p2 = f32[16384]{0} parameter(2)
e.1 = (f32[16384]{0}, f32[16384]{0}) fusion(p2), kind=kInput, calls=exp
get-tuple-element.1 = f32[16384]{0} get-tuple-element(e.1), index=1
get-tuple-element = f32[16384]{0} get-tuple-element(e.1), index=0
ROOT result = (bf16[1024]{0}, bf16[1024]{0}, f32[16384]{0}, f32[16384]{0}) tuple(fusion.1, fusion.2, get-tuple-element.1, get-tuple-element)
})";
return ParseAndReturnVerifiedModule(kHlo).value();
}
void FindAndCompare(const std::vector<std::unique_ptr<HloModule>>& modules,
absl::string_view module_name,
absl::string_view pattern) {
auto iter =
absl::c_find_if(modules, [&](const std::unique_ptr<HloModule>& module) {
return module->name() == module_name;
});
EXPECT_NE(iter, modules.end()) << "No module named " << module_name;
if (iter == modules.end()) {
return;
}
EXPECT_TRUE(*RunFileCheck((*iter)->ToString(), pattern));
}
};
TEST_F(HloDecomposerTest, DecomposeNoDedup) {
auto module = GetModule();
TF_ASSERT_OK_AND_ASSIGN(
auto decomposed,
DecomposeHloModule(*module, false));
EXPECT_EQ(decomposed.size(), 3);
FindAndCompare(decomposed, "fusion.1", R"(
CHECK: %add{{.*}} {
CHECK: %fused_computation.1
CHECK: ENTRY
CHECK-THEN: %parameter.0 = bf16[1024,8192]{1,0} parameter(0)
CHECK-THEN: %parameter.1 = f32[8192]{0} parameter(1)
CHECK-THEN: ROOT %fusion.1
)");
FindAndCompare(decomposed, "fusion.2", R"(
CHECK: %add{{.*}} {
CHECK: %fused_computation.2
CHECK: ENTRY
CHECK-THEN: %parameter.0 = bf16[1024,8192]{1,0} parameter(0)
CHECK-THEN: %parameter.1 = f32[8192]{0} parameter(1)
CHECK-THEN: ROOT %fusion.2
)");
FindAndCompare(decomposed, "e.1", R"(
CHECK: %exp{{.*}} {
CHECK: ENTRY
CHECK-THEN: %parameter.0 = f32[16384]{0} parameter(0)
CHECK-THEN: ROOT %e.1
)");
}
TEST_F(HloDecomposerTest, DecomposeDedup) {
auto module = GetModule();
TF_ASSERT_OK_AND_ASSIGN(
auto decomposed,
DecomposeHloModule(*module, true));
EXPECT_EQ(decomposed.size(), 2);
FindAndCompare(decomposed, "fusion.1", R"(
CHECK: %add{{.*}} {
CHECK: %fused_computation.1
CHECK: ENTRY
CHECK-THEN: %parameter.0 = bf16[1024,8192]{1,0} parameter(0)
CHECK-THEN: %parameter.1 = f32[8192]{0} parameter(1)
CHECK-THEN: ROOT %fusion.1
)");
FindAndCompare(decomposed, "e.1", R"(
CHECK: %exp{{.*}} {
CHECK: ENTRY
CHECK-THEN: %parameter.0 = f32[16384]{0} parameter(0)
CHECK-THEN: ROOT %e.1
)");
}
}
} | 2,189 |
#ifndef XLA_TOOLS_HLO_SLICER_H_
#define XLA_TOOLS_HLO_SLICER_H_
#include <functional>
#include <memory>
#include <vector>
#include "absl/container/flat_hash_map.h"
#include "absl/container/flat_hash_set.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"
namespace xla {
using FrontierSelector = std::function<bool(const HloInstruction*)>;
class SliceOutput {
public:
SliceOutput(absl::flat_hash_map<const HloComputation*,
absl::flat_hash_set<const HloInstruction*>>
sliced_instructions,
absl::flat_hash_map<const HloComputation*,
absl::flat_hash_set<const HloInstruction*>>
frontier_instructions,
const HloInstruction* nearest_common_ancestor_root = nullptr)
: sliced_instructions_(sliced_instructions),
frontier_instructions_(frontier_instructions),
nearest_common_ancestor_root_(nearest_common_ancestor_root) {}
explicit SliceOutput(
absl::flat_hash_map<const HloComputation*,
absl::flat_hash_set<const HloInstruction*>>
sliced_instructions)
: sliced_instructions_(sliced_instructions) {}
SliceOutput() = default;
const absl::flat_hash_map<const HloComputation*,
absl::flat_hash_set<const HloInstruction*>>&
sliced_instructions() const {
return sliced_instructions_;
}
const absl::flat_hash_map<const HloComputation*,
absl::flat_hash_set<const HloInstruction*>>&
frontier_instructions() const {
return frontier_instructions_;
}
int NumSlicedInstructions() const {
return CountMapOfSet(sliced_instructions_);
}
int NumFrontierInstructions() const {
return CountMapOfSet(frontier_instructions_);
}
const HloInstruction* nearest_common_ancestor_root() const {
return nearest_common_ancestor_root_;
}
static absl::flat_hash_map<const HloComputation*,
absl::flat_hash_set<const HloInstruction*>>
IntersectSlicedInstructions(SliceOutput slice_a, SliceOutput slice_b) {
absl::flat_hash_map<const HloComputation*,
absl::flat_hash_set<const HloInstruction*>>
intersect_sliced_instructions;
auto& sliced_instructions_a = slice_a.sliced_instructions();
auto& sliced_instructions_b = slice_b.sliced_instructions();
for (auto& [computation, instructions] : sliced_instructions_a) {
for (auto& instruction : instructions) {
if (sliced_instructions_b.contains(computation) &&
sliced_instructions_b.at(computation).contains(instruction)) {
intersect_sliced_instructions[computation].insert(instruction);
}
}
}
return intersect_sliced_instructions;
}
static absl::flat_hash_map<const HloComputation*,
absl::flat_hash_set<const HloInstruction*>>
UnionSlicedInstructions(SliceOutput slice_a, SliceOutput slice_b) {
absl::flat_hash_map<const HloComputation*,
absl::flat_hash_set<const HloInstruction*>>
union_sliced_instructions;
auto& sliced_instructions_a = slice_a.sliced_instructions();
auto& sliced_instructions_b = slice_b.sliced_instructions();
for (auto& sliced_instructions :
{sliced_instructions_a, sliced_instructions_b}) {
for (auto& [computation, instructions] : sliced_instructions) {
for (auto& instruction : instructions) {
union_sliced_instructions[computation].insert(instruction);
}
}
}
return union_sliced_instructions;
}
private:
absl::flat_hash_map<const HloComputation*,
absl::flat_hash_set<const HloInstruction*>>
sliced_instructions_;
absl::flat_hash_map<const HloComputation*,
absl::flat_hash_set<const HloInstruction*>>
frontier_instructions_;
const HloInstruction* nearest_common_ancestor_root_;
int CountMapOfSet(
const absl::flat_hash_map<const HloComputation*,
absl::flat_hash_set<const HloInstruction*>>&
to_count) const {
int count = 0;
for (const auto& [key, set] : to_count) {
count += set.size();
}
return count;
}
};
SliceOutput SliceModule(
const HloModule* hlo_module,
absl::Span<const HloInstruction*> slice_starting_instructions,
FrontierSelector frontier_selector = nullptr,
bool ignore_control_dependency = false, bool forward_slice = true,
bool nearest_common_ancestor_as_root = false);
struct SlicingConfiguration {
enum class ForwardSlicingConfig { kRoot, kNca };
ForwardSlicingConfig forward_slicing = ForwardSlicingConfig::kRoot;
bool backward_slicing = false;
bool remove_sharding = false;
bool reduce_tuple_parameter = false;
int slicing_group = -1;
};
std::vector<std::unique_ptr<HloModule>> SliceModuleAndExtract(
const HloModule* hlo_module,
absl::Span<const HloInstruction*> slice_starting_instructions,
const SlicingConfiguration& slicing_configuration);
}
#endif
#include "xla/tools/hlo_slicer.h"
#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/log/log.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/call_graph.h"
#include "xla/service/hlo_verifier.h"
#include "xla/shape.h"
#include "xla/shape_util.h"
#include "xla/tools/hlo_extractor.h"
#include "tsl/platform/status.h"
namespace xla {
namespace {
void ReduceTupleParameterHelper(HloModule* hlo_module,
HloInstruction* tuple_parameter) {
for (HloInstruction* user_inst : tuple_parameter->users()) {
if (user_inst->opcode() != HloOpcode::kGetTupleElement) {
return;
}
}
VLOG(1) << "Parameter instruction to be reduced: "
<< tuple_parameter->ToString()
<< " shape size: " << tuple_parameter->shape().tuple_shapes_size()
<< " users size: " << tuple_parameter->users().size();
std::vector<Shape> used_shapes;
for (HloInstruction* user_inst : tuple_parameter->users()) {
used_shapes.push_back(user_inst->shape());
}
Shape new_tuple_shape =
ShapeUtil::MakeTupleShape(absl::MakeSpan(used_shapes));
tuple_parameter->mutable_shape()->mutable_tuple_shapes()->clear();
for (const auto& shape : used_shapes) {
tuple_parameter->mutable_shape()->mutable_tuple_shapes()->push_back(shape);
}
for (int i = 0; i < tuple_parameter->users().size(); ++i) {
tuple_parameter->users()[i]->set_tuple_index(i);
}
hlo_module->mutable_config().SetComputationLayoutIfExists(
hlo_module->entry_computation()->ComputeProgramShape());
}
void ReduceTupleParameter(HloModule* hlo_module) {
std::vector<HloInstruction*> tuple_parameters;
for (HloInstruction* parameter :
hlo_module->entry_computation()->parameter_instructions()) {
if (parameter->shape().IsTuple()) {
tuple_parameters.push_back(parameter);
}
}
for (HloInstruction* tuple_parameter : tuple_parameters) {
ReduceTupleParameterHelper(hlo_module, tuple_parameter);
}
}
HloInstruction* FindShardingInstruction(HloModule* hlo_module) {
for (HloComputation* computation : hlo_module->computations()) {
for (HloInstruction* instruction : computation->instructions()) {
if (instruction->opcode() == HloOpcode::kCustomCall &&
instruction->custom_call_target() == "Sharding") {
CHECK_EQ(instruction->operand_count(), 1);
return instruction;
}
}
}
return nullptr;
}
void RemoveSharding(HloModule* hlo_module) {
while (HloInstruction* custom_call_instruction =
FindShardingInstruction(hlo_module)) {
for (HloInstruction* user_instruction : custom_call_instruction->users()) {
CHECK_OK(custom_call_instruction->ReplaceUseWith(
user_instruction, custom_call_instruction->mutable_operand(0)));
}
custom_call_instruction->DetachFromOperandsAndUsers();
CHECK_OK(custom_call_instruction->parent()->RemoveInstruction(
custom_call_instruction));
VLOG(1) << "Removed sharding custom-call: "
<< custom_call_instruction->ToString();
HloVerifier verifier(false,
true);
TF_CHECK_OK(verifier.Run(hlo_module).status());
}
}
void IntraComputationSlicing(
const HloComputation* computation,
absl::flat_hash_set<const HloInstruction*>& sliced_instructions,
absl::flat_hash_set<const HloInstruction*>& frontier_instructions,
bool forward_slice, FrontierSelector frontier_selector,
bool ignore_control_dependency) {
std::deque<const HloInstruction*> worklist(sliced_instructions.begin(),
sliced_instructions.end());
while (!worklist.empty()) {
const HloInstruction* inst = worklist.back();
worklist.pop_back();
if (frontier_selector && !frontier_selector(inst)) {
frontier_instructions.insert(inst);
continue;
}
std::vector<HloInstruction*> instructions_to_propagate =
forward_slice ? std::vector<HloInstruction*>(inst->users().begin(),
inst->users().end())
: std::vector<HloInstruction*>(inst->operands().begin(),
inst->operands().end());
if (!ignore_control_dependency) {
if (forward_slice) {
instructions_to_propagate.insert(instructions_to_propagate.end(),
inst->control_successors().begin(),
inst->control_successors().end());
} else {
instructions_to_propagate.insert(instructions_to_propagate.end(),
inst->control_predecessors().begin(),
inst->control_predecessors().end());
}
}
for (auto next_inst : instructions_to_propagate) {
if (!sliced_instructions.contains(next_inst)) {
worklist.push_front(next_inst);
sliced_instructions.insert(next_inst);
}
}
}
}
SliceOutput SliceModuleHelper(
const HloModule* hlo_module,
absl::Span<const HloInstruction*> slice_starting_instructions,
FrontierSelector frontier_selector, bool ignore_control_dependency,
bool forward_slice, bool nearest_common_ancestor_as_root) {
absl::flat_hash_map<const HloComputation*,
absl::flat_hash_set<const HloInstruction*>>
sliced_computation_instructions_map;
for (auto inst : slice_starting_instructions) {
sliced_computation_instructions_map[inst->parent()].insert(inst);
}
absl::flat_hash_map<const HloComputation*,
absl::flat_hash_set<const HloInstruction*>>
frontier_computation_instructions_map;
std::unique_ptr<CallGraph> call_graph = CallGraph::Build(hlo_module);
std::vector<HloComputation*> post_order_computations =
hlo_module->MakeComputationPostOrder();
std::vector<HloComputation*> computations_to_traverse =
forward_slice
? post_order_computations
: std::vector<HloComputation*>(post_order_computations.rbegin(),
post_order_computations.rend());
absl::flat_hash_set<const HloComputation*>
nearest_common_ancestor_computations;
if (nearest_common_ancestor_as_root) {
std::vector<const HloComputation*> starting_computations;
for (const auto& [computation, instructions] :
sliced_computation_instructions_map) {
starting_computations.push_back(computation);
}
nearest_common_ancestor_computations =
call_graph->NearestCommonAncestorComputations(starting_computations);
CHECK(!nearest_common_ancestor_computations.empty());
}
for (auto computation : computations_to_traverse) {
if (sliced_computation_instructions_map.contains(computation)) {
auto slicing_starting_instructions = std::vector<const HloInstruction*>(
sliced_computation_instructions_map[computation].begin(),
sliced_computation_instructions_map[computation].end());
IntraComputationSlicing(
computation, sliced_computation_instructions_map[computation],
frontier_computation_instructions_map[computation], forward_slice,
frontier_selector, ignore_control_dependency);
if (forward_slice) {
if (nearest_common_ancestor_as_root &&
nearest_common_ancestor_computations.contains(computation)) {
const HloInstruction* nearest_common_ancestor_instruction =
*(call_graph->NearestCommonAncestorInstructions(
slicing_starting_instructions))
.begin();
CHECK_NE(nearest_common_ancestor_instruction, nullptr);
return SliceOutput{sliced_computation_instructions_map,
frontier_computation_instructions_map,
nearest_common_ancestor_instruction};
}
if (!sliced_computation_instructions_map[computation].contains(
computation->root_instruction()) ||
frontier_computation_instructions_map[computation].contains(
computation->root_instruction())) {
continue;
}
for (auto caller_inst :
call_graph->GetComputationCallers(computation)) {
sliced_computation_instructions_map[caller_inst->parent()].insert(
caller_inst);
}
}
if (!forward_slice) {
for (const auto& callsite :
call_graph->GetNode(computation).callsites()) {
if (sliced_computation_instructions_map[computation].contains(
callsite.instruction())) {
for (auto callee : callsite.called_computations()) {
sliced_computation_instructions_map[callee].insert(
callee->root_instruction());
}
}
}
}
}
}
return SliceOutput{sliced_computation_instructions_map,
frontier_computation_instructions_map};
}
}
SliceOutput SliceModule(
const HloModule* hlo_module,
absl::Span<const HloInstruction*> slice_starting_instructions,
FrontierSelector frontier_selector, bool ignore_control_dependency,
bool forward_slice, bool nearest_common_ancestor_as_root) {
if (forward_slice) {
if (!nearest_common_ancestor_as_root) {
return SliceModuleHelper(hlo_module, slice_starting_instructions,
frontier_selector, ignore_control_dependency,
true,
false);
} else {
CHECK(forward_slice) << "Option `nearest_common_ancestor_as_root` can "
"only be enabled when "
"forward slicing";
CHECK((frontier_selector == nullptr))
<< "Option `nearest_common_ancestor_as_root` can not be specified "
"with `frontier_selector`";
SliceOutput forward_slice_output =
SliceModuleHelper(hlo_module, slice_starting_instructions,
nullptr,
ignore_control_dependency, true,
true);
std::vector<const HloInstruction*> nearest_common_ancestor(
{forward_slice_output.nearest_common_ancestor_root()});
CHECK_EQ(nearest_common_ancestor.size(), 1);
SliceOutput backward_slice_output =
SliceModuleHelper(hlo_module,
absl::MakeSpan(nearest_common_ancestor),
nullptr,
ignore_control_dependency, false,
false);
return SliceOutput{SliceOutput::IntersectSlicedInstructions(
forward_slice_output, backward_slice_output),
backward_slice_output.frontier_instructions(),
forward_slice_output.nearest_common_ancestor_root()};
}
} else {
return SliceModuleHelper(hlo_module, slice_starting_instructions,
frontier_selector, ignore_control_dependency,
false,
false);
}
}
std::vector<std::unique_ptr<HloModule>> SliceModuleAndExtract(
const HloModule* hlo_module,
absl::Span<const HloInstruction*> slice_starting_instructions,
const SlicingConfiguration& slicing_configuration) {
std::vector<std::unique_ptr<HloModule>> sliced_modules;
int slicing_group = slicing_configuration.slicing_group;
CHECK(slicing_group >= 1 || slicing_group == -1);
std::vector<absl::Span<const HloInstruction*>> grouped_instructions;
if (slicing_group == -1) {
grouped_instructions = {slice_starting_instructions};
} else {
for (int i = 0; i < slice_starting_instructions.size();
i += slicing_group) {
grouped_instructions.push_back(
slice_starting_instructions.subspan(i, slicing_group));
}
}
for (const auto& grouped_slice_starting_instructions : grouped_instructions) {
SliceOutput forward_slice_output;
if (slicing_configuration.forward_slicing ==
SlicingConfiguration::ForwardSlicingConfig::kRoot) {
forward_slice_output = SliceModule(
hlo_module, grouped_slice_starting_instructions,
nullptr,
false, true,
false);
} else if (slicing_configuration.forward_slicing ==
SlicingConfiguration::ForwardSlicingConfig::kNca) {
forward_slice_output = SliceModule(
hlo_module, grouped_slice_starting_instructions,
nullptr,
false, true,
true);
}
VLOG(1) << "[Num of forward sliced insts]: "
<< forward_slice_output.NumSlicedInstructions();
SliceOutput backw | #include "xla/tools/hlo_slicer.h"
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "absl/log/check.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_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 HloSlicerTest = HloTestBase;
TEST_F(HloSlicerTest, SingleComputationForwardSlice) {
const std::string& hlo_string = R"(
HloModule axpy_module
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[] constant(1)
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.1 = f32[10] add(x, p.3)
}
)";
TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> hlo_module,
ParseAndReturnVerifiedModule(hlo_string));
auto p2 = FindInstruction(hlo_module.get(), "p.2");
EXPECT_THAT(p2, op::Parameter());
auto p3 = FindInstruction(hlo_module.get(), "p.3");
EXPECT_THAT(p3, op::Parameter());
auto x = FindInstruction(hlo_module.get(), "x");
EXPECT_THAT(x, op::Subtract());
auto y = FindInstruction(hlo_module.get(), "y");
EXPECT_THAT(y, op::Multiply());
auto add0 = FindInstruction(hlo_module.get(), "add.0");
EXPECT_THAT(add0, op::Add());
auto add1 = FindInstruction(hlo_module.get(), "add.1");
EXPECT_THAT(add1, op::Add());
auto entry_comp = FindComputation(hlo_module.get(), "axpy_computation");
EXPECT_NE(entry_comp, nullptr);
auto hlo_selector = [](const HloInstruction* hlo_inst) -> bool {
return true;
};
{
std::vector<const HloInstruction*> relevant_instructions({p2, x});
auto sliced_result = SliceModule(
hlo_module.get(), absl::MakeSpan(relevant_instructions), hlo_selector);
auto sliced_instructions = sliced_result.sliced_instructions();
EXPECT_EQ(sliced_instructions.size(), 1);
EXPECT_EQ(sliced_instructions[entry_comp].size(), 4);
EXPECT_TRUE(sliced_instructions[entry_comp].contains(p2));
EXPECT_TRUE(sliced_instructions[entry_comp].contains(x));
EXPECT_TRUE(sliced_instructions[entry_comp].contains(y));
EXPECT_TRUE(sliced_instructions[entry_comp].contains(add1));
EXPECT_EQ(sliced_result.NumFrontierInstructions(), 0);
}
{
std::vector<const HloInstruction*> relevant_instructions({add0, p3});
auto sliced_result = SliceModule(
hlo_module.get(), absl::MakeSpan(relevant_instructions), hlo_selector);
auto sliced_instructions = sliced_result.sliced_instructions();
EXPECT_EQ(sliced_instructions.size(), 1);
EXPECT_EQ(sliced_instructions[entry_comp].size(), 4);
EXPECT_TRUE(sliced_instructions[entry_comp].contains(add0));
EXPECT_TRUE(sliced_instructions[entry_comp].contains(x));
EXPECT_TRUE(sliced_instructions[entry_comp].contains(p3));
EXPECT_TRUE(sliced_instructions[entry_comp].contains(add1));
EXPECT_EQ(sliced_result.NumFrontierInstructions(), 0);
}
}
TEST_F(HloSlicerTest, MultipleComputationForwardSlice) {
const std::string& hlo_string = R"(
HloModule test
calculate_alpha {
constant.5 = s32[] constant(2)
constant.6 = s32[] constant(3)
ROOT ret = s32[] subtract(constant.5, constant.6)
}
While.body {
loop_var.1 = (s32[], s32[3]{0}) parameter(0)
get_tuple_element.1 = s32[] get-tuple-element(loop_var.1), index=0
constant.1 = s32[] constant(23)
add.3 = s32[] add(get_tuple_element.1, constant.1)
get_tuple_element.2 = s32[3]{0} get-tuple-element(loop_var.1), index=1
multiply = s32[3]{0} multiply(get_tuple_element.2, get_tuple_element.2)
ROOT tuple = (s32[], s32[3]{0}) tuple(add.3, multiply)
}
While.condition {
loop_var.2 = (s32[], s32[3]{0}) parameter(0)
get_tuple_element.3 = s32[] get-tuple-element(loop_var.2), index=0
constant.2 = s32[] constant(100)
ROOT less_than = pred[] compare(get_tuple_element.3, constant.2), direction=LT
}
ENTRY Test {
p.1 = s32[] parameter(0)
p.2 = s32[] parameter(1)
add.1 = s32[] add(p.1, p.2)
constant.3 = s32[] call(), to_apply=calculate_alpha
constant.4 = s32[3]{0} constant({0, 1, 2})
tuple.1 = (s32[], s32[3]{0}) tuple(constant.3, constant.4)
while.1 = (s32[], s32[3]{0}) while(tuple.1), condition=While.condition, body=While.body
loop_count = s32[] get-tuple-element(while.1), index=0
ROOT add.2 = s32[] add(loop_count, add.1)
}
)";
TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> hlo_module,
ParseAndReturnVerifiedModule(hlo_string));
auto add1 = FindInstruction(hlo_module.get(), "add.1");
EXPECT_THAT(add1, op::Add());
auto while1 = FindInstruction(hlo_module.get(), "while.1");
EXPECT_THAT(while1, op::While());
auto loop_count = FindInstruction(hlo_module.get(), "loop_count");
EXPECT_THAT(loop_count, op::GetTupleElement());
auto add2 = FindInstruction(hlo_module.get(), "add.2");
EXPECT_THAT(add2, op::Add());
auto gte1 = FindInstruction(hlo_module.get(), "get_tuple_element.1");
EXPECT_THAT(gte1, op::GetTupleElement());
auto gte2 = FindInstruction(hlo_module.get(), "get_tuple_element.2");
EXPECT_THAT(gte2, op::GetTupleElement());
auto constant5 = FindInstruction(hlo_module.get(), "constant.5");
EXPECT_THAT(constant5, op::Constant());
auto tuple1 = FindInstruction(hlo_module.get(), "tuple.1");
EXPECT_THAT(tuple1, op::Tuple());
auto entry_comp = FindComputation(hlo_module.get(), "Test");
EXPECT_NE(entry_comp, nullptr);
auto while_cond_comp = FindComputation(hlo_module.get(), "While.condition");
EXPECT_NE(while_cond_comp, nullptr);
auto while_body_comp = FindComputation(hlo_module.get(), "While.body");
EXPECT_NE(while_body_comp, nullptr);
auto calculate_alpha_comp =
FindComputation(hlo_module.get(), "calculate_alpha");
EXPECT_NE(calculate_alpha_comp, nullptr);
auto hlo_selector = [](const HloInstruction* hlo_inst) -> bool {
return true;
};
{
std::vector<const HloInstruction*> relevant_instructions({add1, while1});
auto sliced_result = SliceModule(
hlo_module.get(), absl::MakeSpan(relevant_instructions), hlo_selector);
auto sliced_instructions = sliced_result.sliced_instructions();
EXPECT_EQ(sliced_instructions.size(), 1);
EXPECT_EQ(sliced_instructions[entry_comp].size(), 4);
EXPECT_TRUE(sliced_instructions[entry_comp].contains(add2));
EXPECT_TRUE(sliced_instructions[entry_comp].contains(add1));
EXPECT_TRUE(sliced_instructions[entry_comp].contains(while1));
EXPECT_TRUE(sliced_instructions[entry_comp].contains(loop_count));
EXPECT_EQ(sliced_result.NumFrontierInstructions(), 0);
}
{
std::vector<const HloInstruction*> relevant_instructions({constant5});
auto sliced_result = SliceModule(
hlo_module.get(), absl::MakeSpan(relevant_instructions), hlo_selector);
auto sliced_instructions = sliced_result.sliced_instructions();
EXPECT_EQ(sliced_instructions.size(), 2);
EXPECT_TRUE(sliced_instructions.contains(entry_comp));
EXPECT_TRUE(sliced_instructions.contains(calculate_alpha_comp));
EXPECT_FALSE(sliced_instructions[entry_comp].contains(add1));
EXPECT_EQ(sliced_result.NumFrontierInstructions(), 0);
}
{
std::vector<const HloInstruction*> relevant_instructions({gte2});
auto sliced_result = SliceModule(
hlo_module.get(), absl::MakeSpan(relevant_instructions), hlo_selector);
auto sliced_instructions = sliced_result.sliced_instructions();
EXPECT_EQ(sliced_instructions.size(), 2);
EXPECT_TRUE(sliced_instructions.contains(entry_comp));
EXPECT_TRUE(sliced_instructions.contains(while_body_comp));
EXPECT_FALSE(sliced_instructions.contains(while_cond_comp));
EXPECT_FALSE(sliced_instructions[entry_comp].contains(tuple1));
EXPECT_FALSE(sliced_instructions[entry_comp].contains(add1));
EXPECT_TRUE(sliced_instructions[entry_comp].contains(add2));
EXPECT_FALSE(sliced_instructions[while_body_comp].contains(gte1));
EXPECT_EQ(sliced_result.NumFrontierInstructions(), 0);
}
}
TEST_F(HloSlicerTest, SingleComputationForwardFrontier) {
const std::string& hlo_string = R"(
HloModule axpy_module
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[] constant(1)
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)
p.4 = f32[10] parameter(4)
p.5 = f32[10] parameter(5)
sub.1 = f32[10] subtract(p.4, p.5)
add.2 = f32[10] add(p.3, sub.1)
ROOT add.1 = f32[10] add(x, add.2)
}
)";
TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> hlo_module,
ParseAndReturnVerifiedModule(hlo_string));
auto broadcast = FindInstruction(hlo_module.get(), "broadcast");
EXPECT_THAT(broadcast, op::Broadcast());
auto x = FindInstruction(hlo_module.get(), "x");
EXPECT_THAT(x, op::Subtract());
auto y = FindInstruction(hlo_module.get(), "y");
EXPECT_THAT(y, op::Multiply());
auto add0 = FindInstruction(hlo_module.get(), "add.0");
EXPECT_THAT(add0, op::Add());
auto p5 = FindInstruction(hlo_module.get(), "p.5");
EXPECT_THAT(p5, op::Parameter());
auto sub1 = FindInstruction(hlo_module.get(), "sub.1");
EXPECT_THAT(sub1, op::Subtract());
auto entry_comp = FindComputation(hlo_module.get(), "axpy_computation");
EXPECT_NE(entry_comp, nullptr);
{
auto hlo_selector = [](const HloInstruction* hlo_inst) -> bool {
return hlo_inst->opcode() != HloOpcode::kSubtract;
};
std::vector<const HloInstruction*> relevant_instructions({broadcast, add0});
auto sliced_result = SliceModule(
hlo_module.get(), absl::MakeSpan(relevant_instructions), hlo_selector);
auto sliced_instructions = sliced_result.sliced_instructions();
EXPECT_EQ(sliced_result.NumSlicedInstructions(), 4);
EXPECT_EQ(sliced_instructions.size(), 1);
EXPECT_TRUE(sliced_instructions[entry_comp].contains(add0));
EXPECT_TRUE(sliced_instructions[entry_comp].contains(broadcast));
EXPECT_TRUE(sliced_instructions[entry_comp].contains(y));
EXPECT_TRUE(sliced_instructions[entry_comp].contains(x));
EXPECT_EQ(sliced_result.NumFrontierInstructions(), 1);
auto frontier_instructions = sliced_result.frontier_instructions();
EXPECT_TRUE(frontier_instructions[entry_comp].contains(x));
}
{
auto hlo_selector = [](const HloInstruction* hlo_inst) -> bool {
return hlo_inst->opcode() != HloOpcode::kSubtract;
};
std::vector<const HloInstruction*> relevant_instructions({add0, y, p5});
auto sliced_result = SliceModule(
hlo_module.get(), absl::MakeSpan(relevant_instructions), hlo_selector);
auto sliced_instructions = sliced_result.sliced_instructions();
EXPECT_EQ(sliced_result.NumSlicedInstructions(), 5);
EXPECT_EQ(sliced_instructions.size(), 1);
EXPECT_TRUE(sliced_instructions[entry_comp].contains(add0));
EXPECT_TRUE(sliced_instructions[entry_comp].contains(y));
EXPECT_TRUE(sliced_instructions[entry_comp].contains(x));
EXPECT_TRUE(sliced_instructions[entry_comp].contains(p5));
EXPECT_TRUE(sliced_instructions[entry_comp].contains(sub1));
EXPECT_EQ(sliced_result.NumFrontierInstructions(), 2);
auto frontier_instructions = sliced_result.frontier_instructions();
EXPECT_TRUE(frontier_instructions[entry_comp].contains(x));
EXPECT_TRUE(frontier_instructions[entry_comp].contains(sub1));
}
}
TEST_F(HloSlicerTest, MultipleComputationForwardFrontier) {
const std::string& hlo_string = R"(
HloModule axpy_module
calculate_alpha {
c.0 = f32[] constant(1)
c.1 = f32[] constant(2)
c.2 = f32[] add(c.0, c.1)
c.3 = f32[] constant(4)
ROOT ret = f32[] multiply(c.2, c.3)
}
ENTRY axpy_computation {
p.0 = f32[] parameter(0)
alpha = f32[] call(), to_apply=calculate_alpha
ROOT add = f32[] add(p.0, alpha)
}
)";
TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> hlo_module,
ParseAndReturnVerifiedModule(hlo_string));
auto entry_comp = FindComputation(hlo_module.get(), "axpy_computation");
EXPECT_NE(entry_comp, nullptr);
auto calculate_alpha_comp =
FindComputation(hlo_module.get(), "calculate_alpha");
EXPECT_NE(calculate_alpha_comp, nullptr);
auto ret = FindInstruction(hlo_module.get(), "ret");
EXPECT_THAT(ret, op::Multiply());
auto c2 = FindInstruction(hlo_module.get(), "c.2");
EXPECT_THAT(c2, op::Add());
auto c3 = FindInstruction(hlo_module.get(), "c.3");
EXPECT_THAT(c3, op::Constant());
auto alpha = FindInstruction(hlo_module.get(), "alpha");
EXPECT_THAT(alpha, op::Call());
{
auto hlo_selector = [&ret](const HloInstruction* hlo_inst) -> bool {
return hlo_inst != ret;
};
std::vector<const HloInstruction*> relevant_instructions({c2});
auto sliced_result = SliceModule(
hlo_module.get(), absl::MakeSpan(relevant_instructions), hlo_selector);
auto sliced_instructions = sliced_result.sliced_instructions();
EXPECT_EQ(sliced_result.NumSlicedInstructions(), 2);
EXPECT_EQ(sliced_instructions.size(), 1);
EXPECT_TRUE(sliced_instructions.contains(calculate_alpha_comp));
EXPECT_EQ(sliced_instructions[calculate_alpha_comp].size(), 2);
EXPECT_TRUE(sliced_instructions[calculate_alpha_comp].contains(c2));
EXPECT_TRUE(sliced_instructions[calculate_alpha_comp].contains(ret));
EXPECT_EQ(sliced_result.NumFrontierInstructions(), 1);
auto frontier_instructions = sliced_result.frontier_instructions();
EXPECT_TRUE(frontier_instructions.contains(calculate_alpha_comp));
EXPECT_TRUE(frontier_instructions[calculate_alpha_comp].contains(ret));
}
{
auto hlo_selector = [](const HloInstruction* hlo_inst) -> bool {
return hlo_inst->opcode() != HloOpcode::kCall;
};
std::vector<const HloInstruction*> relevant_instructions({c2});
auto sliced_result = SliceModule(
hlo_module.get(), absl::MakeSpan(relevant_instructions), hlo_selector);
auto sliced_instructions = sliced_result.sliced_instructions();
EXPECT_EQ(sliced_instructions.size(), 2);
EXPECT_TRUE(sliced_instructions.contains(calculate_alpha_comp));
EXPECT_EQ(sliced_instructions[calculate_alpha_comp].size(), 2);
EXPECT_TRUE(sliced_instructions[calculate_alpha_comp].contains(c2));
EXPECT_TRUE(sliced_instructions[calculate_alpha_comp].contains(ret));
EXPECT_TRUE(sliced_instructions.contains(entry_comp));
EXPECT_EQ(sliced_instructions[entry_comp].size(), 1);
EXPECT_TRUE(sliced_instructions[entry_comp].contains(alpha));
EXPECT_EQ(sliced_result.NumFrontierInstructions(), 1);
auto frontier_instructions = sliced_result.frontier_instructions();
EXPECT_TRUE(frontier_instructions.contains(entry_comp));
EXPECT_TRUE(frontier_instructions[entry_comp].contains(alpha));
}
}
TEST_F(HloSlicerTest, SingleComputationBackwardSliceAndFrontier) {
const std::string& hlo_string = R"(
HloModule axpy_module
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[] constant(1)
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.1 = f32[10] add(x, p.3)
}
)";
TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> hlo_module,
ParseAndReturnVerifiedModule(hlo_string));
auto alpha = FindInstruction(hlo_module.get(), "alpha");
EXPECT_THAT(alpha, op::Constant());
auto p0 = FindInstruction(hlo_module.get(), "p.0");
EXPECT_THAT(p0, op::Parameter());
auto p1 = FindInstruction(hlo_module.get(), "p.1");
EXPECT_THAT(p1, op::Parameter());
auto p2 = FindInstruction(hlo_module.get(), "p.2");
EXPECT_THAT(p2, op::Parameter());
auto p3 = FindInstruction(hlo_module.get(), "p.3");
EXPECT_THAT(p3, op::Parameter());
auto broadcast = FindInstruction(hlo_module.get(), "broadcast");
EXPECT_THAT(broadcast, op::Broadcast());
auto x = FindInstruction(hlo_module.get(), "x");
EXPECT_THAT(x, op::Subtract());
auto y = FindInstruction(hlo_module.get(), "y");
EXPECT_THAT(y, op::Multiply());
auto add0 = FindInstruction(hlo_module.get(), "add.0");
EXPECT_THAT(add0, op::Add());
auto entry_comp = FindComputation(hlo_module.get(), "axpy_computation");
EXPECT_NE(entry_comp, nullptr);
auto hlo_selector = [](const HloInstruction* hlo_inst) -> bool {
return true;
};
{
std::vector<const HloInstruction*> relevant_instructions({y});
auto sliced_result = SliceModule(
hlo_module.get(), absl::MakeSpan(relevant_instructions), hlo_selector,
false, false);
auto sliced_instructions = sliced_result.sliced_instructions();
EXPECT_EQ(sliced_instructions.size(), 1);
EXPECT_EQ(sliced_instructions[entry_comp].size(), 4);
EXPECT_TRUE(sliced_instructions[entry_comp].contains(y));
EXPECT_TRUE(sliced_instructions[entry_comp].contains(broadcast));
EXPECT_TRUE(sliced_instructions[entry_comp].contains(p2));
EXPECT_TRUE(sliced_instructions[entry_comp].contains(alpha));
EXPECT_EQ(sliced_result.NumFrontierInstructions(), 0);
}
{
std::vector<const HloInstruction*> relevant_instructions({add0, y});
auto sliced_result = SliceModule(
hlo_module.get(), absl::MakeSpan(relevant_instructions), hlo_selector,
false, false);
auto sliced_instructions = sliced_result.sliced_instructions();
EXPECT_EQ(sliced_instructions.size(), 1);
EXPECT_EQ(sliced_instructions[entry_comp].size(), 7);
EXPECT_TRUE(sliced_instructions[entry_comp].contains(y));
EXPECT_TRUE(sliced_instructions[entry_comp].contains(broadcast));
EXPECT_TRUE(sliced_instructions[entry_comp].contains(p2));
EXPECT_TRUE(sliced_instructions[entry_comp].contains(alpha));
EXPECT_TRUE(sliced_instructions[entry_comp].contains(add0));
EXPECT_TRUE(sliced_instructions[entry_comp].contains(p0));
EXPECT_TRUE(sliced_instructions[entry_comp].contains(p1));
EXPECT_EQ(sliced_result.NumFrontierInstructions(), 0);
}
auto broadcast_slicer = [](const HloInstruction* hlo_inst) -> bool {
return hlo_inst->opcode() != HloOpcode::kBroadcast;
};
{
std::vector<const HloInstruction*> relevant_instructions({y});
auto sliced_result = SliceModule(
hlo_module.get(), absl::MakeSpan(relevant_instructions),
broadcast_slicer,
false, false);
auto sliced_instructions = sliced_result.sliced_instructions();
EXPECT_EQ(sliced_instructions.size(), 1);
EXPECT_EQ(sliced_instructions[entry_comp].size(), 3);
EXPECT_TRUE(sliced_instructions[entry_comp].contains(y));
EXPECT_TRUE(sliced_instructions[entry_comp].contains(p2));
EXPECT_TRUE(sliced_instructions[entry_comp].contains(broadcast));
EXPECT_EQ(sliced_result.NumFrontierInstructions(), 1);
auto frontier_instructions = sliced_result.frontier_instructions();
EXPECT_TRUE(frontier_instructions[entry_comp].contains(broadcast));
}
}
TEST_F(HloSlicerTest, MultipleComputationBackwardSliceAndFrontier) {
const std::string& hlo_string = R"(
HloModule axpy_module
calculate_alpha {
c.0 = f32[] constant(1)
c.1 = f32[] constant(2)
c.2 = f32[] add(c.0, c.1)
c.3 = f32[] constant(4)
ROOT ret = f32[] multiply(c.2, c.3)
}
ENTRY axpy_computation {
p.0 = f32[] parameter(0)
alpha = f32[] call(), to_apply=calculate_alpha
ROOT add = f32[] add(p.0, alpha)
}
)";
TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> hlo_module,
ParseAndReturnVerifiedModule(hlo_string));
auto entry_comp = FindComputation(hlo_module.get(), "axpy_computation");
EXPECT_NE(entry_comp, nullptr);
auto calculate_alpha_comp =
FindComputation(hlo_module.get(), "calculate_alpha");
EXPECT_NE(calculate_alpha_comp, nullptr);
auto ret = FindInstruction(hlo_module.get(), "ret");
EXPECT_THAT(ret, op::Multiply());
auto c0 = FindInstruction(hlo_module.get(), "c.0");
EXPECT_THAT(c0, op::Constant());
auto c1 = FindInstruction(hlo_module.get(), "c.1");
EXPECT_THAT(c1, op::Constant());
auto c2 = FindInstruction(hlo_module.get(), "c.2");
EXPECT_THAT(c2, op::Add());
auto c3 = FindInstruction(hlo_module.get(), "c.3");
EXPECT_THAT(c3, op::Constant());
auto alpha = FindInstruction(hlo_module.get(), "alpha");
EXPECT_THAT(alpha, op::Call());
{
auto hlo_selector = [](const HloInstruction* hlo_inst) -> bool {
return true;
};
std::vector<const HloInstruction*> relevant_instructions({c2});
auto sliced_result = SliceModule(
hlo_module.get(), absl::MakeSpan(relevant_instructions), hlo_selector,
false, false);
auto sliced_instructions = sliced_result.sliced_instructions();
EXPECT_EQ(sliced_result.NumSlicedInstructions(), 3);
EXPECT_EQ(sliced_instructions.size(), 1);
EXPECT_TRUE(sliced_instructions.contains(calculate_alpha_comp));
EXPECT_EQ(sliced_instructions[calculate_alpha_comp].size(), 3);
EXPECT_TRUE(sliced_instructions[calculate_alpha_comp].contains(c0));
EXPECT_TRUE(sliced_instructions[calculate_alpha_comp].contains(c1));
EXPECT_TRUE(sliced_instructions[calculate_alpha_comp].contains(c2));
EXPECT_EQ(sliced_result.NumFrontierInstructions(), 0);
}
{
auto hlo_selector = [](const HloInstruction* hlo_inst) -> bool {
return true;
};
std::vector<const HloInstruction*> relevant_instructions({alpha});
auto sliced_result = SliceModule(
hlo_module.get(), absl::MakeSpan(relevant_instructions), hlo_selector,
false, false);
auto sliced_instructions = sliced_result.sliced_instructions();
EXPECT_EQ(sliced_instructions.size(), 2);
EXPECT_TRUE(sliced_instructions.contains(calculate_alpha_comp));
EXPECT_EQ(sliced_instructions[calculate_alpha_comp].size(), 5);
EXPECT_TRUE(sliced_instructions[calculate_alpha_comp].contains(c0));
EXPECT_TRUE(sliced_instructions[calculate_alpha_comp].contains(c1));
EXPECT_TRUE(sliced_instructions[calculate_alpha_comp].contains(c2));
EXPECT_TRUE(sliced_instructions[calculate_alpha_comp].contains(c3));
EXPECT_TRUE(sliced_instructions[calculate_alpha_comp].contains(ret));
EXPECT_TRUE(sliced_instructions.contains(entry_comp));
EXPECT_EQ(sliced_instructions[entry_comp].size(), 1);
EXPECT_TRUE(sliced_instructions[entry_comp].contains(alpha));
EXPECT_EQ(sliced_result.NumFrontierInstructions(), 0);
}
{
auto add_slicer = [](const HloInstruction* hlo_inst) -> bool {
return hlo_inst->opcode() != HloOpcode::kAdd;
};
std::vector<const HloInstruction*> relevant_instructions({ret});
auto sliced_result = SliceModule(
hlo_module.get(), absl::MakeSpan(relevant_instructions), add_slicer,
false, false);
auto sliced_instructions = sliced_result.sliced_instructions();
EXPECT_EQ(sliced_result.NumSlicedInstructions(), 3);
EXPECT_EQ(sliced_instructions.size(), 1);
EXPECT_TRUE(sliced_instructions.contains(calculate_alpha_comp));
EXPECT_EQ(sliced_instructions[calculate_alpha_comp].size(), 3);
EXPECT_TRUE(sliced_instructions[calculate_alpha_comp].contains(ret));
EXPECT_TRUE(sliced_instructions[calculate_alpha_comp].contains(c3));
EXPECT_TRUE(sliced_instructions[calculate_alpha_comp].contains(c2));
EXPECT_EQ(sliced_result.NumFrontierInstructions(), 1);
auto frontier_instructions = sliced_result.frontier_instructions();
EXPECT_TRUE(frontier_instructions.contains(calculate_alpha_comp));
EXPECT_TRUE(frontier_instructions[calculate_alpha_comp].contains(c2));
}
{
auto mul_slicer = [](const HloInstruction* hlo_inst) -> bool {
return hlo_inst->opcode() != HloOpcode::kMultiply;
};
std::vector<const HloInstruction*> relevant_instructions({alpha});
auto sliced_result = SliceModule(
hlo_module.get(), absl::MakeSpan(relevant_instructions), mul_slicer,
false, false);
auto sliced_instructions = sliced_result.sliced_instructions();
EXPECT_EQ(sliced_result.NumSlicedInstructions(), 2);
EXPECT_EQ(sliced_instructions.size(), 2);
EXPECT_TRUE(sliced_instructions.contains(calculate_alpha_comp));
EXPECT_EQ(sliced_instructions[calculate_alpha_comp].size(), 1);
EXPECT_TRUE(sliced_instructions[calculate_alpha_comp].contains(ret));
EXPECT_TRUE(sliced_instructions.contains(entry_comp));
EXPECT_EQ(sliced_instructions[entry_comp].size(), 1);
EXPECT_TRUE(sliced_instructions[entry_comp].contains(alpha));
EXPECT_EQ(sliced_result.NumFrontierInstructions(), 1);
auto frontier_instructions = sliced_result.frontier_instructions();
EXPECT_TRUE(frontier_instructions.contains(calculate_alpha_comp));
EXPECT_TRUE(frontier_instructions[calculate_alpha_comp].contains(ret));
}
}
TEST_F(HloSlicerTest, ForwardSlicingNearestCommonAncestor) {
const std::string& hlo_string = R"(
HloModule module
ENTRY computation {
p.0 = f32[10] parameter(0)
p.1 = f32[10] parameter(1)
add.0 = f32[10] add(p.0, p.1)
p.2 = f32[10] parameter(2)
mul.0 = f32[10] multiply(p.1, p.2)
sub.0 = f32[10] subtract(add.0, mul.0)
add.1 = f32[10] add(add.0, p.2)
ROOT add.2 = f32[10] add(sub.0, add.1)
}
)";
TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> hlo_module,
ParseAndReturnVerifiedModule(hlo_string));
auto p0 = FindInstruction(hlo_module.get(), "p.0");
auto p2 = FindInstruction(hlo_module.get(), "p.2");
auto mul0 = FindInstruction(hlo_module.get(), "mul.0");
auto add0 = FindInstruction(hlo_module.get(), "add.0");
auto sub0 = FindInstruction(hlo_module.get(), "sub.0");
auto add1 = FindInstruction(hlo_module.get(), "add.1");
const HloComputation* computation = hlo_module->entry_computation();
{
std::vector<const HloInstruction*> relevant_instructions({p0});
auto sliced_result =
SliceModule(hlo_module.get(), absl::MakeSpan(relevant_instructions),
nullptr,
false, true,
true);
EXPECT_NE(sliced_result.nearest_common_ancestor_root(), nullptr);
EXPECT_EQ(sliced_result.nearest_common_ancestor_root(), p0);
EXPECT_EQ(sliced_result.NumSlicedInstructions(), 1);
}
{
std::vector<const HloInstruction*> relevant_instructions({p0, p2});
auto sliced_result =
SliceModule(hlo_module.get(), absl::MakeSpan(relevant_instructions),
nullptr,
false, true,
true);
EXPECT_NE(sliced_result.nearest_common_ancestor_root(), nullptr);
EXPECT_TRUE(sliced_result.nearest_common_ancestor_root() == sub0 ||
sliced_result.nearest_common_ancestor_root() == add1);
EXPECT_TRUE(sliced_result.sliced_instructions().contains(computation));
auto sliced_instructions = sliced_result.sliced_instructions();
EXPECT_TRUE(sliced_instructions[computation].contains(add0));
}
{
std::vector<const HloInstruction*> relevant_instructions({p0, mul0});
auto sliced_result =
SliceModule(hlo_module.get(), absl::MakeSpan(relevant_instructions),
nullptr,
false,
true,
true);
EXPECT_NE(sliced_result.nearest_common_ancestor_root(), nullptr);
EXPECT_EQ(sliced_result.nearest_common_ancestor_root(), sub0);
EXPECT_EQ(sliced_result.NumSlicedInstructions(), 4);
EXPECT_TRUE(sliced_result.sliced_instructions().contains(computation));
auto sliced_instructions = sliced_result.sliced_instructions();
EXPECT_TRUE(sliced_instructions[computation].contains(p0));
EXPECT_TRUE(sliced_instructions[computation].contains(add0));
EXPECT_TRUE(sliced_instructions[computation].contains(mul0));
EXPECT_TRUE(sliced_instructions[computation].contains(sub0));
}
}
TEST_F(HloSlicerTest, MultipleComputationForwardSlicingNearestCommonAncestor) {
const std::string& hlo_string = R"(
HloModule axpy_module
calculate_alpha {
c.0 = f32[] constant(1)
c.1 = f32[] constant(2)
ROOT ret.0 = f32[] multiply(c.0, c.1)
}
calculate_y {
c.2 = f32[] constant(2)
c.3 = f32[] constant(3)
ROOT ret.1 = f32[] add(c.2, c.3)
}
ENTRY axpy_computation {
alpha = f32[] call(), to_apply=calculate_alpha
y = f32[] call(), to_apply=calculate_y
add.0 = f32[] add(alpha, y)
p.0 = f32[] parameter(0)
ROOT add.1 = f32[] add(add.0, p.0)
}
)";
TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> hlo_module,
ParseAndReturnVerifiedModule(hlo_string));
auto c0 = FindInstruction(hlo_module.get(), "c.0");
auto ret0 = FindInstruction(hlo_module.get(), "ret.0");
auto c2 = FindInstruction(hlo_module.get(), "c.2");
auto ret1 = FindInstruction(hlo_module.get(), "ret.1");
auto alpha = FindInstruction(hlo_module.get(), "alpha");
auto y = FindInstruction(hlo_module.get(), "y");
auto add0 = FindInstruction(hlo_module.get(), "add.0");
const HloComputation* computation = hlo_module->entry_computation();
const HloComputation* calculate_alpha =
FindComputation(hlo_module.get(), "calculate_alpha");
const HloComputation* calculate_y =
FindComputation(hlo_module.get(), "calculate_y");
{
std::vector<const HloInstruction*> relevant_instructions({c0, c2});
auto sliced_result =
SliceModule(hlo_module.get(), absl::MakeSpan(relevant_instructions),
nullptr,
false,
true,
true);
EXPECT_NE(sliced_result.nearest_common_ancestor_root(), nullptr);
EXPECT_EQ(sliced_result.nearest_common_ancestor_root(), add0);
EXPECT_EQ(sliced_result.sliced_instructions().size(), 3);
EXPECT_TRUE(sliced_result.sliced_instructions().contains(computation));
EXPECT_TRUE(sliced_result.sliced_instructions().contains(calculate_alpha));
EXPECT_TRUE(sliced_result.sliced_instructions().contains(calculate_y));
auto sliced_instructions = sliced_result.sliced_instructions();
EXPECT_EQ(sliced_result.NumSlicedInstructions(), 7);
EXPECT_TRUE(sliced_instructions[calculate_alpha].contains(c0));
EXPECT_TRUE(sliced_instructions[calculate_alpha].contains(ret0));
EXPECT_TRUE(sliced_instructions[calculate_y].conta | 2,190 |
#ifndef XLA_TOOLS_RUN_HLO_MODULE_H_
#define XLA_TOOLS_RUN_HLO_MODULE_H_
#include <functional>
#include <memory>
#include <random>
#include <string>
#include "absl/status/status.h"
#include "xla/hlo/ir/hlo_module.h"
#include "xla/service/hlo_runner.h"
#include "xla/tools/run_hlo_module.pb.h"
#include "tsl/platform/status.h"
namespace xla {
class BufferAssignmentProto;
struct RunHloModuleOptions {
std::string platform;
std::string reference_platform{"default"};
bool print_literals{false};
bool flatten_control_flow{false};
bool run_test_hlo_passes{true};
bool run_reference_hlo_passes{true};
bool use_large_float_range{false};
bool treat_gte_as_data_formatting{false};
float abs_error_bound{1e-3};
float rel_error_bound{1e-3};
std::string input_format;
bool use_buffer_assignment_from_proto{false};
std::string input_compilation_environments;
int iterations{1};
std::string output_literals_file;
std::string input_literals_file;
bool random_init_input_literals{true};
bool force_fake_data{false};
bool isolate_instructions{false};
};
absl::Status RunAndCompare(
std::unique_ptr<HloModule> test_module,
const BufferAssignmentProto* buffer_assignment_proto,
HloRunnerInterface* test_runner, HloRunnerInterface* reference_runner,
std::minstd_rand0* engine, const RunHloModuleOptions& options,
xla::RunHloModuleIterationLiterals* iteration_literals_proto = nullptr,
std::function<absl::Status(const HloModule&, HloRunnerInterface*,
HloModule*)>
reference_module_modifier_hook = {},
std::function<void(HloModuleConfig*)> config_modifier_hook = {});
absl::Status RunAndCompare(
const std::string& hlo_filename, HloRunnerInterface* test_runner,
HloRunnerInterface* reference_runner, std::minstd_rand0* engine,
const RunHloModuleOptions& options,
xla::RunHloModuleIterationLiterals* iteration_literals_proto = nullptr,
std::function<absl::Status(const HloModule&, HloRunnerInterface*,
HloModule*)>
reference_module_modifier_hook = {},
std::function<void(HloModuleConfig*)> config_modifier_hook = {},
std::function<absl::Status(const RunHloModuleOptions& options,
HloModule& module)>
compilation_env_modifier_hook = {});
void ReadInputLiteralsFromFile(const std::string& file_path,
xla::RunHloModuleLiterals* input_literals_proto);
}
#endif
#include "xla/tools/run_hlo_module.h"
#include <functional>
#include <iomanip>
#include <iostream>
#include <map>
#include <memory>
#include <optional>
#include <random>
#include <sstream>
#include <string>
#include <utility>
#include <vector>
#include "absl/algorithm/container.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_replace.h"
#include "absl/strings/string_view.h"
#include "absl/types/span.h"
#include "xla/error_spec.h"
#include "xla/hlo/ir/hlo_instruction.h"
#include "xla/hlo/ir/hlo_module.h"
#include "xla/hlo/ir/hlo_opcode.h"
#include "xla/literal.h"
#include "xla/literal_comparison.h"
#include "xla/service/hlo.pb.h"
#include "xla/service/hlo_module_config.h"
#include "xla/service/hlo_verifier.h"
#include "xla/tests/test_utils.h"
#include "xla/tools/hlo_control_flow_flattening.h"
#include "xla/tools/hlo_decomposer.h"
#include "xla/tools/hlo_module_loader.h"
#include "xla/tools/prepare_reference_module.h"
#include "xla/tools/run_hlo_module.pb.h"
#include "xla/util.h"
#include "xla/xla_data.pb.h"
#include "tsl/platform/env.h"
#include "tsl/platform/errors.h"
#include "tsl/platform/path.h"
#include "tsl/platform/status.h"
#include "tsl/platform/statusor.h"
namespace xla {
namespace {
enum class ModuleResult {
kMatched,
kRan,
kSkipped,
kDidntRun,
kOtherError,
kCompilationError,
kRuntimeError,
kMismatch,
};
constexpr absl::string_view ModuleResultToString(ModuleResult result) {
switch (result) {
case ModuleResult::kMatched:
return "MATCHED";
case ModuleResult::kRan:
return "RAN";
case ModuleResult::kSkipped:
return "SKIPPED";
case ModuleResult::kDidntRun:
return "DIDN'T RUN";
case ModuleResult::kOtherError:
return "OTHER ERROR";
case ModuleResult::kCompilationError:
return "COMPILATION ERROR";
case ModuleResult::kRuntimeError:
return "RUNTIME ERROR";
case ModuleResult::kMismatch:
return "MISMATCH";
}
}
void WriteLiteralToTempFile(const LiteralSlice& literal,
const std::string& name) {
auto* env = tsl::Env::Default();
std::string binary_filename;
std::string text_filename;
std::string outdir;
if (tsl::io::GetTestUndeclaredOutputsDir(&outdir)) {
std::string filename = tsl::io::JoinPath(
outdir, absl::StrFormat("tempfile-%d-%s", env->NowMicros(), name));
binary_filename = absl::StrCat(filename, ".pb");
text_filename = absl::StrCat(filename, ".txt");
} else {
binary_filename = tsl::io::GetTempFilename(absl::StrCat(name, ".pb"));
text_filename = tsl::io::GetTempFilename(absl::StrCat(name, ".txt"));
}
TF_CHECK_OK(tsl::WriteBinaryProto(env, binary_filename, literal.ToProto()));
TF_CHECK_OK(tsl::WriteStringToFile(env, text_filename, literal.ToString()));
LOG(ERROR) << "wrote Literal to " << name << " binary: " << binary_filename
<< " text: " << text_filename;
}
void OnMiscompare(const LiteralSlice& expected, const LiteralSlice& actual,
const LiteralSlice& mismatches,
const ShapeIndex& ,
const literal_comparison::ErrorBuckets& ) {
LOG(INFO) << "expected: " << ShapeUtil::HumanString(expected.shape()) << " "
<< literal_comparison::ToStringTruncated(expected);
LOG(INFO) << "actual: " << ShapeUtil::HumanString(actual.shape()) << " "
<< literal_comparison::ToStringTruncated(actual);
LOG(INFO) << "Dumping literals to temp files...";
WriteLiteralToTempFile(expected, "expected");
WriteLiteralToTempFile(actual, "actual");
WriteLiteralToTempFile(mismatches, "mismatches");
}
absl::StatusOr<Literal> ExecuteWithRunner(
std::unique_ptr<HloModule> module,
const BufferAssignmentProto* buffer_assignment_proto,
absl::Span<const Literal> args, HloRunnerInterface* runner,
bool run_hlo_passes) {
TF_RETURN_WITH_CONTEXT_IF_ERROR(
VerifyHloModule(module.get(), false,
true),
absl::StrCat("(on ", runner->Name(), ")"));
std::cerr << "Running HLO module with runner " << runner->Name() << "...\n";
XLA_VLOG_LINES(1, module->ToString());
const auto start = std::chrono::high_resolution_clock::now();
ExecutionProfile profile;
auto result_status =
(buffer_assignment_proto == nullptr)
? runner->Execute(std::move(module), args, run_hlo_passes, &profile)
: runner->ExecuteWithBufferAssignment(std::move(module),
buffer_assignment_proto, args,
run_hlo_passes, &profile);
const auto end = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> diff = end - start;
std::cerr << "... compiled and ran in " << diff.count() << "s.\n";
double run_time = static_cast<double>(profile.compute_time_ns()) / 1e9;
std::cerr << "execution time for runner " << runner->Name() << ": "
<< run_time << "s.\n";
TF_RETURN_WITH_CONTEXT_IF_ERROR(
result_status.status(),
absl::StrCat("Failed to execute on ", runner->Name()));
return std::move(result_status).value();
}
absl::Status RunAndCompareInternal(
std::unique_ptr<HloModule> test_module,
const BufferAssignmentProto* buffer_assignment_proto,
HloRunnerInterface* test_runner, HloRunnerInterface* reference_runner,
std::minstd_rand0* engine, const RunHloModuleOptions& options,
xla::RunHloModuleIterationLiterals* iteration_literals_proto,
std::function<absl::Status(const HloModule&, HloRunnerInterface*,
HloModule*)>
reference_module_modifier_hook,
std::function<void(HloModuleConfig*)> config_modifier_hook,
ModuleResult* test_run_result, ModuleResult* reference_run_result) {
auto copy_result_on_failure = [](auto status, ModuleResult result,
ModuleResult* out_result) {
if (!status.ok() && out_result != nullptr) {
*out_result = result;
}
return status;
};
if (!config_modifier_hook) {
config_modifier_hook = [](HloModuleConfig* config) {
config->set_seed(42);
};
}
if (options.flatten_control_flow) {
HloControlFlowFlattening control_flow_flattening(
HloControlFlowFlattening::Options{1});
TF_RETURN_IF_ERROR(
copy_result_on_failure(control_flow_flattening.Run(test_module.get()),
ModuleResult::kCompilationError, test_run_result)
.status());
}
TF_ASSIGN_OR_RETURN(
auto args, copy_result_on_failure(
MakeFakeArguments(test_module.get(), engine,
options.use_large_float_range,
options.treat_gte_as_data_formatting),
ModuleResult::kOtherError, test_run_result));
if (iteration_literals_proto != nullptr &&
iteration_literals_proto->arguments_size() != 0) {
if (iteration_literals_proto->arguments_size() != args.size()) {
if (test_run_result != nullptr) {
*test_run_result = ModuleResult::kOtherError;
}
return xla::InvalidArgument(
"Failed to use input literals as arguments; mismatched "
"number of expected arguments.");
} else {
for (int i = 0; i < args.size(); ++i) {
if (!literal_comparison::EqualShapes(
xla::Shape(args[i].shape()),
xla::Shape(iteration_literals_proto->arguments(i).shape()))
.ok()) {
if (test_run_result != nullptr) {
*test_run_result = ModuleResult::kOtherError;
}
return xla::InvalidArgument(
"Failed to use input literals for argument %d "
"because of a shape mismatch.",
i);
}
TF_ASSIGN_OR_RETURN(
args[i],
copy_result_on_failure(xla::Literal::CreateFromProto(
iteration_literals_proto->arguments(i)),
ModuleResult::kOtherError, test_run_result));
}
}
}
if (options.print_literals) {
for (int i = 0; i < args.size(); ++i) {
std::cout << "\n** Argument " << i << " **\n"
<< args[i].ToString() << "\n";
}
}
if (iteration_literals_proto != nullptr &&
iteration_literals_proto->arguments_size() == 0) {
for (int i = 0; i < args.size(); ++i) {
*iteration_literals_proto->add_arguments() = args[i].ToProto();
}
}
std::unique_ptr<HloModule> reference_module;
if (reference_runner != nullptr) {
TF_ASSIGN_OR_RETURN(
reference_module,
copy_result_on_failure(
PrepareReferenceModule(*test_module, test_runner,
config_modifier_hook,
reference_module_modifier_hook),
ModuleResult::kCompilationError, reference_run_result));
}
TF_ASSIGN_OR_RETURN(
auto test_result,
copy_result_on_failure(
ExecuteWithRunner(std::move(test_module), buffer_assignment_proto,
args, test_runner, options.run_test_hlo_passes),
ModuleResult::kRuntimeError, test_run_result));
if (test_run_result != nullptr) {
*test_run_result = ModuleResult::kRan;
}
if (options.print_literals) {
std::cout << "\n** Result with test runner " << test_runner->Name()
<< " **\n"
<< test_result.ToString() << "\n";
}
if (iteration_literals_proto != nullptr) {
LiteralProto test_result_proto = test_result.ToProto();
iteration_literals_proto->mutable_result()->Swap(&test_result_proto);
}
if (reference_module == nullptr) {
std::cerr << "Skipping reference runner\n";
return absl::OkStatus();
}
if (const HloInstruction* root_instruction =
reference_module->entry_computation()->root_instruction();
root_instruction->opcode() == HloOpcode::kCustomCall) {
std::cerr << "Skipping reference runner for a custom call "
<< root_instruction->custom_call_target() << "\n";
if (reference_run_result != nullptr) {
*reference_run_result = ModuleResult::kSkipped;
}
return absl::OkStatus();
}
TF_ASSIGN_OR_RETURN(
auto reference_result,
copy_result_on_failure(
ExecuteWithRunner(std::move(reference_module),
nullptr, args,
reference_runner, options.run_reference_hlo_passes),
ModuleResult::kRuntimeError, reference_run_result));
if (reference_run_result != nullptr) {
*reference_run_result = ModuleResult::kRan;
}
if (options.print_literals) {
std::cout << "\n** Result with reference runner "
<< reference_runner->Name() << " **\n"
<< reference_result.ToString() << "\n";
}
if (iteration_literals_proto != nullptr) {
LiteralProto reference_result_proto = reference_result.ToProto();
iteration_literals_proto->mutable_reference_result()->Swap(
&reference_result_proto);
}
ErrorSpec error_spec(static_cast<float>(options.abs_error_bound),
static_cast<float>(options.rel_error_bound));
absl::Status comparison_status =
literal_comparison::Near(reference_result,
test_result,
error_spec,
true, &OnMiscompare);
const ModuleResult comparison_result =
comparison_status.ok() ? ModuleResult::kMatched : ModuleResult::kMismatch;
if (test_run_result != nullptr) {
*test_run_result = comparison_result;
}
if (reference_run_result != nullptr) {
*reference_run_result = comparison_result;
}
return comparison_status;
}
struct ChunkResult {
std::string module_name;
ModuleResult test_result = ModuleResult::kDidntRun;
ModuleResult reference_result = ModuleResult::kDidntRun;
absl::Status status;
bool operator<(const ChunkResult& other) const {
if (test_result != other.test_result) {
return test_result < other.test_result;
}
return reference_result < other.reference_result;
}
};
std::string BuildResultsTable(absl::Span<const ChunkResult> chunk_results,
size_t num_modules) {
constexpr int kStatusWidth = 21;
constexpr int kNameWidth = 30;
constexpr int kThreeColumnsWidth = 5 + 2 * kStatusWidth + kNameWidth;
constexpr int kTableWidth = kThreeColumnsWidth + 30;
std::ostringstream strstr;
auto print_row = [&](absl::string_view reference, absl::string_view test,
absl::string_view module_name, absl::string_view error) {
std::string formatted_error = absl::StrReplaceAll(
error, {{"\n", absl::StrCat("\n", std::string(kThreeColumnsWidth, ' '),
"|")}});
strstr << " " << std::left << std::setw(kStatusWidth) << reference << "| "
<< std::setw(kStatusWidth) << test << "| " << std::setw(kNameWidth)
<< module_name << "| " << formatted_error << "\n";
};
auto print_line = [&](int line_width) {
strstr << std::string(line_width, '-') << "\n";
};
print_row("Reference", "Test", "Module", "Status");
print_line(kTableWidth);
std::map<std::pair<ModuleResult, ModuleResult>, int> result_counts;
for (const ChunkResult& chunk_result : chunk_results) {
const std::pair<ModuleResult, ModuleResult> result_pair(
chunk_result.reference_result, chunk_result.test_result);
++result_counts[result_pair];
print_row(ModuleResultToString(chunk_result.reference_result),
ModuleResultToString(chunk_result.test_result),
chunk_result.module_name, chunk_result.status.ToString());
}
print_line(kTableWidth);
print_row("Reference", "Test", "Module", "Status");
print_line(kTableWidth);
strstr << "\n\n";
print_line(kThreeColumnsWidth);
print_row("Reference", "Test", "Total count", "");
print_line(kThreeColumnsWidth);
for (const auto& [result, count] : result_counts) {
print_row(ModuleResultToString(result.first),
ModuleResultToString(result.second), absl::StrCat(count), "");
}
print_line(kThreeColumnsWidth);
if (chunk_results.size() < num_modules) {
strstr << "\n(did not " << (num_modules - chunk_results.size())
<< " modules due to earlier failures)\n\n";
}
return strstr.str();
}
absl::Status RunIsolatedAndCompare(
std::unique_ptr<HloModule> test_module,
const BufferAssignmentProto* buffer_assignment_proto,
HloRunnerInterface* test_runner, HloRunnerInterface* reference_runner,
std::minstd_rand0* engine, const RunHloModuleOptions& options,
xla::RunHloModuleIterationLiterals* iteration_literals_proto,
std::function<absl::Status(const HloModule&, HloRunnerInterface*,
HloModule*)>
reference_module_modifier_hook,
std::function<void(HloModuleConfig*)> config_modifier_hook) {
CHECK(test_module);
CHECK(iteration_literals_proto == nullptr)
<< "Cannot run decomposed module if input literals are provided.";
if (options.run_test_hlo_passes || (options.run_reference_hlo_passes &&
!options.reference_platform.empty())) {
LOG(WARNING)
<< "!!! Warning !!! When running decomposed module, running HLO "
"passes is likely not what you want. If you have unoptimized "
"HLO, first convert it to the optimized e.g. using the "
"hlo-opt tool, and then isolate without HLO passes.";
}
std::vector<ChunkResult> chunk_results;
TF_ASSIGN_OR_RETURN(
std::vector<std::unique_ptr<HloModule>> modules,
DecomposeHloModule(*test_module, true));
absl::Status status = absl::OkStatus();
for (std::unique_ptr<HloModule>& module : modules) {
const std::string module_name = module->name();
ModuleResult test_module_result = ModuleResult::kDidntRun;
ModuleResult reference_module_result = ModuleResult::kDidntRun;
absl::Status chunk_status = RunAndCompareInternal(
std::move(module), buffer_assignment_proto, test_runner,
reference_runner, engine, options, iteration_literals_proto,
reference_module_modifier_hook, config_modifier_hook,
&test_module_result, &reference_module_result);
chunk_results.push_back({std::move(module_name), test_module_result,
reference_module_result, chunk_status});
status.Update(chunk_status);
}
absl::c_sort(chunk_results);
std::cout << BuildResultsTable(chunk_results, modules.size());
return status;
}
}
absl::Status RunAndCompare(
std::unique_ptr<HloModule> test_module,
const BufferAssignmentProto* buffer_assignment_proto,
HloRunnerInterface* test_runner, HloRunnerInterface* reference_runner,
std::minstd_rand0* engine, const RunHloModuleOptions& options,
xla::RunHloModuleIterationLiterals* iteration_literals_proto,
std::function<absl::Status(const HloModule&, HloRunnerInterface*,
HloModule*)>
reference_module_modifier_hook,
std::function<void(HloModuleConfig*)> config_modifier_hook) {
if (options.isolate_instructions) {
return RunIsolatedAndCompare(
std::move(test_module), buffer_assignment_proto, test_runner,
reference_runner, engine, options, iteration_literals_proto,
reference_module_modifier_hook, config_modifier_hook);
}
return RunAndCompareInternal(
std::move(test_module), buffer_assignment_proto, test_runner,
reference_runner, engine, options, iteration_literals_proto,
reference_module_modifier_hook, config_modifier_hook, nullptr, nullptr);
}
absl::Status RunAndCompare(
const std::string& hlo_filename, HloRunnerInterface* test_runner,
HloRunnerInterface* reference_runner, std::minstd_rand0* engine,
const RunHloModuleOptions& options,
xla::RunHloModuleIterationLiterals* iteration_literals_proto,
std::function<absl::Status(const HloModule&, HloRunnerInterface*,
HloModule*)>
reference_module_modifier_hook,
std::function<void(HloModuleConfig*)> config_modifier_hook,
std::function<absl::Status(const RunHloModuleOptions& options,
HloModule& module)>
compilation_env_modifier_hook) {
std::string input_format = options.input_format;
if (input_format.empty()) {
input_format = std::string(tsl::io::Extension(hlo_filename));
}
BufferAssignmentProto buffer_assignment_proto;
TF_ASSIGN_OR_RETURN(
auto test_module,
LoadModuleFromFile(
hlo_filename, input_format, hlo_module_loader_details::Config(),
config_modifier_hook,
options.use_buffer_assignment_from_proto ? &buffer_assignment_proto
: nullptr));
HloVerifier verifier(
HloVerifierOpts{}.WithLayoutSensitive(false).WithAllowMixedPrecision(
true));
TF_RETURN_IF_ERROR(verifier.Run(test_module.get()).status());
if (compilation_env_modifier_hook) {
TF_CHECK_OK(compilation_env_modifier_hook(options, *test_module))
<< "Could not adjust the compilation environment for user provided "
"hlo module.";
}
if (options.print_literals) {
std::cout << "\n** Buffer assignment proto **\n"
<< buffer_assignment_proto.DebugString() << "\n";
}
std::unique_ptr<RunHloModuleIterationLiterals> iteration_literals_proto_local;
if (iteration_literals_proto == nullptr) {
if (!options.force_fake_data && !options.isolate_instructions &&
(input_format == "pb" || input_format == "pbtxt")) {
LOG(INFO) << "Using input data from the user-provided snapshot.";
TF_ASSIGN_OR_RETURN(iteration_literals_proto_local,
LoadInputFromFile(hlo_filename, input_format));
iteration_literals_proto = iteration_literals_proto_local.get();
} else if (input_format == "pb" || input_format == "pbtxt") {
LOG(INFO)
<< "Ignoring input data from snapshot and using fake data instead.";
}
}
return RunAndCompare(
std::move(test_module),
options.use_buffer_assignment_from_proto ? &buffer_assignment_proto
: nullptr,
test_runner, reference_runner, engine, options, iteration_literals_proto,
reference_module_modifier_hook, config_modifier_hook);
}
void ReadInputLiteralsFromFile(const std::string& file_path,
RunHloModuleLiterals* input_literals_proto) {
if (!tsl::ReadTextOrBinaryProto(tsl::Env::Default(), file_path,
input_literals_proto)
.ok() ||
input_literals_proto->iterations().empty()) {
xla::RunHloModuleIterationLiterals iteration_literals_proto;
if (!tsl::ReadTextOrBinaryProto(tsl::Env::Default(), file_path,
&iteration_literals_proto)
.ok()) {
LOG(QFATAL) << "Failed to deserialize input literals from file "
<< file_path << "\n";
}
input_literals_proto->clear_iterations();
*input_literals_proto->add_iterations() = iteration_literals_proto;
}
}
} | #include "xla/tools/run_hlo_module.h"
#include <string>
#include "xla/literal.h"
#include "xla/literal_util.h"
#include "xla/tools/run_hlo_module.pb.h"
#include "xla/xla_data.pb.h"
#include "tsl/lib/core/status_test_util.h"
#include "tsl/platform/env.h"
#include "tsl/platform/test.h"
namespace xla {
namespace {
RunHloModuleIterationLiterals GetTestProto() {
RunHloModuleIterationLiterals result;
*result.add_arguments() = LiteralUtil::CreateR1<float>({0.1, 0.2}).ToProto();
*result.add_arguments() = LiteralUtil::CreateR1<float>({0.3, 0.4}).ToProto();
*result.mutable_result() = LiteralUtil::CreateR1<float>({0.5, 0.6}).ToProto();
*result.mutable_reference_result() =
LiteralUtil::CreateR1<float>({0.5, 0.6}).ToProto();
return result;
}
TEST(ReadInputLiteralsFromFile, ReadRunHloModuleLiteralsBinaryProto) {
std::string file_path;
auto env = tsl::Env::Default();
EXPECT_TRUE(env->LocalTempFilename(&file_path));
auto proto = GetTestProto();
RunHloModuleLiterals wrapped_proto;
*wrapped_proto.add_iterations() = proto;
TF_ASSERT_OK(tsl::WriteBinaryProto(env, file_path, wrapped_proto));
RunHloModuleLiterals result;
ReadInputLiteralsFromFile(file_path, &result);
EXPECT_EQ(result.SerializeAsString(), wrapped_proto.SerializeAsString());
}
TEST(ReadInputLiteralsFromFile, ReadRunHloModuleLiteralsTextProto) {
std::string file_path;
auto env = tsl::Env::Default();
EXPECT_TRUE(env->LocalTempFilename(&file_path));
auto proto = GetTestProto();
RunHloModuleLiterals wrapped_proto;
*wrapped_proto.add_iterations() = proto;
TF_ASSERT_OK(tsl::WriteTextProto(env, file_path, wrapped_proto));
RunHloModuleLiterals result;
ReadInputLiteralsFromFile(file_path, &result);
EXPECT_EQ(result.SerializeAsString(), wrapped_proto.SerializeAsString());
}
TEST(ReadInputLiteralsFromFile, ReadRunHloModuleIterationLiteralsBinaryProto) {
std::string file_path;
auto env = tsl::Env::Default();
EXPECT_TRUE(env->LocalTempFilename(&file_path));
auto proto = GetTestProto();
TF_ASSERT_OK(tsl::WriteBinaryProto(env, file_path, proto));
RunHloModuleLiterals result;
ReadInputLiteralsFromFile(file_path, &result);
EXPECT_EQ(result.iterations_size(), 1);
EXPECT_EQ(result.iterations(0).SerializeAsString(),
proto.SerializeAsString());
}
TEST(ReadInputLiteralsFromFile, ReadRunHloModuleIterationLiteralsTextProto) {
std::string file_path;
auto env = tsl::Env::Default();
EXPECT_TRUE(env->LocalTempFilename(&file_path));
auto proto = GetTestProto();
TF_ASSERT_OK(tsl::WriteTextProto(env, file_path, proto));
RunHloModuleLiterals result;
ReadInputLiteralsFromFile(file_path, &result);
EXPECT_EQ(result.iterations_size(), 1);
EXPECT_EQ(result.iterations(0).SerializeAsString(),
proto.SerializeAsString());
}
}
} | 2,191 |
#ifndef XLA_TOOLS_HLO_EXPAND_H_
#define XLA_TOOLS_HLO_EXPAND_H_
#include <string>
#include <vector>
#include "xla/service/hlo_pass_pipeline.h"
#include "xla/tsl/util/command_line_flags.h"
namespace xla {
struct HloExpandConfig {
bool help{false};
std::string input_format;
std::string output_file;
std::string output_format;
bool batch_norm_expander{false};
bool expand_all{false};
bool rng_bit_generator_expander{false};
bool batch_norm_grad_expander{false};
bool batch_norm_inference_expander{false};
bool batch_norm_training_expander{false};
bool cholesky_expander{false};
bool rng_expander{false};
bool rng_bit_generator_philox_expander{false};
bool rng_bit_generator_three_fry_expander{false};
bool triangular_solve_expander{false};
bool spmd_expander{false};
bool verify_hlo{false};
};
void AddPassesToPipeline(xla::HloExpandConfig& config,
xla::HloPassPipeline& pipeline,
const xla::HloModuleConfig& hlo_module_config);
std::vector<tsl::Flag> GetFlags(xla::HloExpandConfig& config);
void ParseCompoundFlags(xla::HloExpandConfig& config);
}
#endif
#include "xla/tools/hlo_expand.h"
#include <vector>
#include "xla/service/batchnorm_expander.h"
#include "xla/service/cholesky_expander.h"
#include "xla/service/hlo.pb.h"
#include "xla/service/hlo_pass_pipeline.h"
#include "xla/service/hlo_verifier.h"
#include "xla/service/rng_bit_generator_expander.h"
#include "xla/service/rng_expander.h"
#include "xla/service/sharding_propagation.h"
#include "xla/service/spmd/stateful_rng_spmd_partitioner.h"
#include "xla/service/triangular_solve_expander.h"
#include "xla/tsl/util/command_line_flags.h"
#include "xla/xla_data.pb.h"
namespace xla {
void AddPassesToPipeline(HloExpandConfig& config, HloPassPipeline& pipeline,
const HloModuleConfig& hlo_module_config) {
if (config.batch_norm_grad_expander || config.batch_norm_inference_expander ||
config.batch_norm_training_expander) {
pipeline.AddPass<xla::BatchNormExpander>(
config.batch_norm_training_expander,
config.batch_norm_inference_expander,
config.batch_norm_grad_expander);
}
if (config.cholesky_expander) {
pipeline.AddPass<xla::CholeskyExpander>();
}
if (config.rng_expander) {
pipeline.AddPass<xla::RngExpander>();
}
if (config.rng_bit_generator_philox_expander) {
pipeline.AddPass<xla::RngBitGeneratorExpander>(
xla::RandomAlgorithm::RNG_PHILOX);
}
if (config.rng_bit_generator_three_fry_expander) {
pipeline.AddPass<xla::RngBitGeneratorExpander>(
xla::RandomAlgorithm::RNG_THREE_FRY);
}
if (config.triangular_solve_expander) {
pipeline.AddPass<xla::TriangularSolveExpander>();
}
if (config.spmd_expander) {
pipeline.AddPass<ShardingPropagation>(
true, false,
hlo_module_config.allow_spmd_sharding_propagation_to_output(),
hlo_module_config.allow_spmd_sharding_propagation_to_parameters());
pipeline.AddPass<spmd::StatefulRngSpmdPartitioner>(
hlo_module_config.num_partitions(), hlo_module_config.replica_count(),
hlo_module_config.debug_options()
.xla_gpu_threshold_for_windowed_einsum_mib());
}
if (config.verify_hlo) {
pipeline.AddPass<xla::HloVerifier>(false,
false);
}
}
std::vector<tsl::Flag> GetFlags(HloExpandConfig& config) {
return {
tsl::Flag("h", &config.help, "Alias of --help"),
tsl::Flag("help", &config.help, "Display available options"),
tsl::Flag(
"input_format", &config.input_format,
"The format of the input file. If this flag is not specified, it's"
"inferred from the file extension instead. Valid values:\n "
"* hlo|txt : HLO textual format\n"
"* pb : xla::HloProto in binary proto format\n"
"* pbtxt : xla::HloProto in text proto format"),
tsl::Flag("o", &config.output_file, "Alias of --output_file="),
tsl::Flag("output_file", &config.output_file, "Full output file path"),
tsl::Flag("output_format", &config.output_format,
"The format of the output file. Defaults to input_format. "
"Valid values:\n"
"* hlo|txt : HLO textual format\n"
"* pb : xla::HloProto in binary proto format\n"
"* pbtxt : xla::HloProto in text proto format"),
tsl::Flag("batch_norm_expander", &config.batch_norm_expander,
"Overrides and expands batch_norm_grad, batch_norm_inference, "
"and batch_norm_training ops"),
tsl::Flag("batch_norm_grad_expander", &config.batch_norm_grad_expander,
"Expands batch_norm_grad op"),
tsl::Flag("batch_norm_inference_expander",
&config.batch_norm_inference_expander,
"Expands batch_norm_inference_grad op"),
tsl::Flag("batch_norm_training_expander",
&config.batch_norm_training_expander,
"Expands batch_norm_training_grad op"),
tsl::Flag("cholesky_expander", &config.cholesky_expander,
"Expands cholesky op"),
tsl::Flag("spmd_expander", &config.spmd_expander,
"Expands SPMD sharding"),
tsl::Flag("expand_all", &config.expand_all,
"Overrides and expands all supported passes below"),
tsl::Flag("rng_expander", &config.rng_expander, "Expands rng op"),
tsl::Flag(
"rng_bit_generator_expander", &config.rng_bit_generator_expander,
"Overrides and expands rng_bit_generator op on all prng algorithms"),
tsl::Flag("rng_bit_generator_philox_expander",
&config.rng_bit_generator_philox_expander,
"Expands rng_bit_generator op using philox prng algorithm"),
tsl::Flag("rng_bit_generator_three_fry_expander",
&config.rng_bit_generator_three_fry_expander,
"Expands rng_bit_generator op using three_fry prng algorithm"),
tsl::Flag("triangular_solve_expander", &config.triangular_solve_expander,
"Expands triangular_solve op"),
tsl::Flag("verify_hlo", &config.verify_hlo,
"Run HLO verifier after passes"),
};
}
void ParseCompoundFlags(HloExpandConfig& config) {
config.batch_norm_grad_expander |=
config.expand_all || config.batch_norm_expander;
config.batch_norm_inference_expander |=
config.expand_all || config.batch_norm_expander;
config.batch_norm_training_expander |=
config.expand_all || config.batch_norm_expander;
config.cholesky_expander |= config.expand_all;
config.rng_bit_generator_philox_expander |=
config.expand_all || config.rng_bit_generator_expander;
config.rng_bit_generator_three_fry_expander |=
config.expand_all || config.rng_bit_generator_expander;
config.rng_expander |= config.expand_all;
config.triangular_solve_expander |= config.expand_all;
}
} | #include <string>
#include <vector>
#include <gmock/gmock.h>
#include "tsl/platform/path.h"
#include "tsl/platform/subprocess.h"
#include "tsl/platform/test.h"
namespace xla {
namespace {
class HloExpandTest : public ::testing::Test {
protected:
void HloOpt(std::vector<std::string>& additional_flags) {
std::string hlo_opt_bin =
tsl::io::JoinPath(tsl::testing::XlaSrcRoot(), "tools", "hlo-expand");
tsl::SubProcess proc;
std::vector<std::string> argv = {hlo_opt_bin};
argv.insert(argv.end(), additional_flags.begin(), additional_flags.end());
proc.SetProgram(hlo_opt_bin, argv);
proc.SetChannelAction(tsl::CHAN_STDOUT, tsl::ACTION_PIPE);
proc.SetChannelAction(tsl::CHAN_STDERR, tsl::ACTION_PIPE);
EXPECT_TRUE(proc.Start());
stdout_output_ = stderr_output_ = "";
int status = proc.Communicate(nullptr, &stdout_output_, &stderr_output_);
#if defined(_WIN32) || defined(_WIN64)
exited_normally_ = (status == 0);
exit_status_ = status;
#else
exited_normally_ = WIFEXITED(status);
exit_status_ = exited_normally_ ? WEXITSTATUS(status) : -1;
#endif
}
std::string stdout_output_;
std::string stderr_output_;
bool exited_normally_ = false;
int exit_status_ = -1;
};
TEST_F(HloExpandTest, CholeskyHlo) {
std::string hlo_path = tsl::io::JoinPath(tsl::testing::XlaSrcRoot(), "tools",
"tests", "cholesky.hlo");
std::vector<std::string> additional_flags = {"--input_format=hlo", hlo_path};
HloOpt(additional_flags);
const std::string& expected_hlo_string =
R"(HloModule main, entry_computation_layout={()->f64[3,3]{1,0}}
ENTRY %main.3 () -> f64[3,3] {
%constant.1 = f64[3,3]{1,0} constant({ { 1, 2, 3 }, { 2, 20, 26 }, { 3, 26, 70 } })
ROOT %cholesky.2 = f64[3,3]{1,0} cholesky(f64[3,3]{1,0} %constant.1), lower=true
})";
EXPECT_TRUE(exited_normally_);
EXPECT_EQ(exit_status_, 0);
EXPECT_THAT(stdout_output_, testing::HasSubstr(expected_hlo_string));
}
TEST_F(HloExpandTest, SpmdHlo) {
std::string hlo_path = tsl::io::JoinPath(tsl::testing::XlaSrcRoot(), "tools",
"tests", "spmd.hlo");
std::vector<std::string> additional_flags = {"--spmd_expander", hlo_path};
HloOpt(additional_flags);
const std::string& expected_hlo_string =
R"(HloModule module, entry_computation_layout={(f32[24,64]{1,0}, f32[39296,64]{1,0})->f32[24,19648]{1,0}}, num_partitions=2
ENTRY %entry_spmd (param: f32[24,64], param.1: f32[39296,64]) -> f32[24,19648] {
%param = f32[24,64]{1,0} parameter(0), sharding={replicated}
%lhs.copy.1 = f32[24,64]{1,0} copy(f32[24,64]{1,0} %param)
%param.1 = f32[39296,64]{1,0} parameter(1), sharding={replicated}
%constant = s32[2]{0} constant({0, 19648})
%partition-id = u32[] partition-id()
%dynamic-slice = s32[1]{0} dynamic-slice(s32[2]{0} %constant, u32[] %partition-id), dynamic_slice_sizes={1}
%reshape = s32[] reshape(s32[1]{0} %dynamic-slice)
%constant.1 = s32[] constant(0)
%dynamic-slice.1 = f32[19648,64]{1,0} dynamic-slice(f32[39296,64]{1,0} %param.1, s32[] %reshape, s32[] %constant.1), dynamic_slice_sizes={19648,64}
%rhs.copy.1 = f32[19648,64]{1,0} copy(f32[19648,64]{1,0} %dynamic-slice.1)
ROOT %dot.1 = f32[24,19648]{1,0} dot(f32[24,64]{1,0} %lhs.copy.1, f32[19648,64]{1,0} %rhs.copy.1), lhs_contracting_dims={1}, rhs_contracting_dims={1}
})";
EXPECT_TRUE(exited_normally_);
EXPECT_EQ(exit_status_, 0);
EXPECT_THAT(stdout_output_, testing::HasSubstr(expected_hlo_string));
}
TEST_F(HloExpandTest, CholeskyExpanderHlo) {
std::string hlo_path = tsl::io::JoinPath(tsl::testing::XlaSrcRoot(), "tools",
"tests", "cholesky.hlo");
std::vector<std::string> additional_flags = {"--input_format=hlo", hlo_path,
"--expand_all"};
HloOpt(additional_flags);
const std::string& expected_hlo_string = "%xla.cholesky_f64";
EXPECT_TRUE(exited_normally_);
EXPECT_EQ(exit_status_, 0);
EXPECT_THAT(stdout_output_, testing::HasSubstr(expected_hlo_string));
}
TEST_F(HloExpandTest, InvalidArgc) {
std::vector<std::string> additional_flags = {"--input_format=hlo", "foo",
"bar", "baz"};
HloOpt(additional_flags);
const std::string& expected_string =
"Cannot parse more than one argument. See usage below:";
EXPECT_TRUE(exited_normally_);
EXPECT_EQ(exit_status_, 1);
EXPECT_THAT(stderr_output_, testing::HasSubstr(expected_string));
}
TEST_F(HloExpandTest, InvalidInputFileExtension) {
std::string hlo_path = tsl::io::JoinPath(tsl::testing::XlaSrcRoot(), "tools",
"tests", "foo.bar");
std::vector<std::string> additional_flags = {hlo_path};
HloOpt(additional_flags);
const std::string& expected_string =
"input_format must be specified as [hlo|pb|pbtxt|txt].";
EXPECT_TRUE(exited_normally_);
EXPECT_EQ(exit_status_, 1);
EXPECT_THAT(stderr_output_, testing::HasSubstr(expected_string));
}
TEST_F(HloExpandTest, InvalidInputFormat) {
std::vector<std::string> additional_flags = {"--input_format=foo"};
HloOpt(additional_flags);
const std::string& expected_string =
"input_format must be specified as [hlo|pb|pbtxt|txt].";
EXPECT_TRUE(exited_normally_);
EXPECT_EQ(exit_status_, 1);
EXPECT_THAT(stderr_output_, testing::HasSubstr(expected_string));
}
TEST_F(HloExpandTest, InvalidOutputFileExtension) {
std::string hlo_path = tsl::io::JoinPath(tsl::testing::XlaSrcRoot(), "tools",
"tests", "cholesky.hlo");
std::string output_path = tsl::io::JoinPath(tsl::testing::XlaSrcRoot(),
"tools", "tests", "foo.bar");
std::vector<std::string> additional_flags = {"--input_format=", hlo_path,
"--output_file=" + output_path};
HloOpt(additional_flags);
const std::string& expected_string =
"output_format must be specified as [hlo|pb|pbtxt].";
EXPECT_TRUE(exited_normally_);
EXPECT_EQ(exit_status_, 1);
EXPECT_THAT(stderr_output_, testing::HasSubstr(expected_string));
}
TEST_F(HloExpandTest, InvalidOutputFormat) {
std::string hlo_path = tsl::io::JoinPath(tsl::testing::XlaSrcRoot(), "tools",
"tests", "cholesky.hlo");
std::vector<std::string> additional_flags = {"--input_format=", hlo_path,
"--output_format=foo"};
HloOpt(additional_flags);
const std::string& expected_string =
"output_format must be specified as [hlo|pb|pbtxt].";
EXPECT_TRUE(exited_normally_);
EXPECT_EQ(exit_status_, 1);
EXPECT_THAT(stderr_output_, testing::HasSubstr(expected_string));
}
TEST_F(HloExpandTest, InvalidFile) {
std::string hlo_path = tsl::io::JoinPath(tsl::testing::XlaSrcRoot(), "tools",
"tests", "foo.bar");
std::vector<std::string> additional_flags = {"--input_format=hlo", hlo_path};
HloOpt(additional_flags);
const std::string& expected_string = "Try: hlo-expand --help";
EXPECT_TRUE(exited_normally_);
EXPECT_EQ(exit_status_, 1);
EXPECT_THAT(stderr_output_, testing::HasSubstr(expected_string));
}
TEST_F(HloExpandTest, UnsupportedOutputFormat) {
std::string hlo_path = tsl::io::JoinPath(tsl::testing::XlaSrcRoot(), "tools",
"tests", "cholesky.hlo");
std::vector<std::string> additional_flags = {"--input_format=hlo",
"--output_format=pb", hlo_path};
HloOpt(additional_flags);
const std::string& expected_string =
"Printing to stdout must specify supported "
"output_format=[hlo|pbtxt|txt].";
EXPECT_TRUE(exited_normally_);
EXPECT_EQ(exit_status_, 1);
EXPECT_THAT(stderr_output_, testing::HasSubstr(expected_string));
}
TEST_F(HloExpandTest, VerificationFailure) {
std::string hlo_path = tsl::io::JoinPath(tsl::testing::XlaSrcRoot(), "tools",
"tests", "invalid_concat.hlo");
std::vector<std::string> additional_flags = {"--verify_hlo", hlo_path};
HloOpt(additional_flags);
const std::string& expected_string =
"Cannot concatenate arrays that differ in dimensions";
EXPECT_TRUE(exited_normally_);
EXPECT_EQ(exit_status_, 1);
EXPECT_THAT(stderr_output_, testing::HasSubstr(expected_string));
}
}
} | 2,192 |
#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()));
}
}
}
} | 2,193 |
#ifndef XLA_TOOLS_HLO_MODULE_LOADER_H_
#define XLA_TOOLS_HLO_MODULE_LOADER_H_
#include <functional>
#include <memory>
#include <string>
#include <string_view>
#include "absl/status/statusor.h"
#include "absl/strings/string_view.h"
#include "xla/hlo/ir/hlo_module.h"
#include "xla/tools/run_hlo_module.pb.h"
namespace xla {
namespace hlo_module_loader_details {
struct Config {
Config() {}
int64_t num_replicas = 1;
int64_t num_partitions = 1;
};
}
std::string StripLogHeaders(std::string_view hlo_string);
absl::StatusOr<std::unique_ptr<HloModule>> LoadModuleFromData(
const std::string& data, std::string_view format,
const hlo_module_loader_details::Config& ovr_config =
hlo_module_loader_details::Config(),
const std::function<void(HloModuleConfig*)>& config_modifier_hook = {},
BufferAssignmentProto* buffer_assignment_proto = nullptr);
absl::StatusOr<std::unique_ptr<HloModule>> LoadModuleFromFile(
const std::string& path, std::string format = "",
const hlo_module_loader_details::Config& ovr_config =
hlo_module_loader_details::Config(),
const std::function<void(HloModuleConfig*)>& config_modifier_hook = {},
BufferAssignmentProto* buffer_assignment_proto = nullptr);
absl::StatusOr<std::unique_ptr<RunHloModuleIterationLiterals>>
LoadInputFromData(const std::string& data, std::string_view format);
absl::StatusOr<std::unique_ptr<RunHloModuleIterationLiterals>>
LoadInputFromFile(const std::string& path, std::string format = "");
}
#endif
#include "xla/tools/hlo_module_loader.h"
#include <functional>
#include <memory>
#include <string>
#include <string_view>
#include <utility>
#include "absl/strings/str_cat.h"
#include "absl/strings/str_join.h"
#include "absl/strings/str_split.h"
#include "xla/debug_options_flags.h"
#include "xla/hlo/ir/hlo_computation.h"
#include "xla/hlo/ir/hlo_instruction.h"
#include "xla/service/hlo_module_config.h"
#include "xla/service/hlo_parser.h"
#include "tsl/platform/env.h"
#include "tsl/platform/logging.h"
#include "tsl/platform/path.h"
#include "tsl/platform/protobuf.h"
namespace xla {
namespace {
absl::Status OverrideConfig(const hlo_module_loader_details::Config& ovr_config,
HloModuleConfig* config) {
config->set_replica_count(ovr_config.num_replicas);
config->set_num_partitions(ovr_config.num_partitions);
return absl::OkStatus();
}
}
std::string StripLogHeaders(std::string_view hlo_string) {
static RE2* matcher = new RE2(
"[IWEF]\\d{4} "
"\\d{2}:\\d{2}:\\d{2}\\.\\d+\\s+\\d+\\s+[^:]+:\\d+\\]\\s?(.*)");
std::string_view matches[4];
std::vector<std::string> lines = absl::StrSplit(hlo_string, '\n');
for (auto& line : lines) {
if (matcher->Match(line, 0, line.size(), RE2::ANCHOR_START, matches, 4)) {
line = std::string(matches[1]);
}
}
return absl::StrJoin(lines, "\n",
[](std::string* out, const std::string& line) {
absl::StrAppend(out, line);
});
}
absl::StatusOr<std::unique_ptr<HloModule>> LoadModuleFromData(
const std::string& data, std::string_view format,
const hlo_module_loader_details::Config& ovr_config,
const std::function<void(HloModuleConfig*)>& config_modifier_hook,
BufferAssignmentProto* buffer_assignment_proto) {
DebugOptions debug_options = GetDebugOptionsFromFlags();
std::unique_ptr<HloModule> module;
if (format == "hlo" || format == "txt") {
std::string hlo_string = StripLogHeaders(data);
HloModuleConfig config;
config.set_debug_options(debug_options);
TF_RETURN_IF_ERROR(OverrideConfig(ovr_config, &config));
if (config_modifier_hook) {
config_modifier_hook(&config);
}
TF_ASSIGN_OR_RETURN(module,
ParseAndReturnUnverifiedModule(hlo_string, config));
} else {
HloSnapshot proto;
if (format == "pb") {
if (!proto.ParseFromString(data) &&
!proto.mutable_hlo()->ParseFromString(data) &&
!proto.mutable_hlo()->mutable_hlo_module()->ParseFromString(data)) {
return InvalidArgument("Failed to parse input as HLO protobuf binary");
}
if (buffer_assignment_proto != nullptr) {
if (proto.hlo().has_buffer_assignment()) {
*buffer_assignment_proto = proto.hlo().buffer_assignment();
} else {
return InvalidArgument(
"Expected buffer assignment in HLO protobuf binary.");
}
}
} else if (format == "pbtxt") {
if (!tsl::protobuf::TextFormat::ParseFromString(data, &proto) &&
!tsl::protobuf::TextFormat::ParseFromString(data,
proto.mutable_hlo()) &&
!tsl::protobuf::TextFormat::ParseFromString(
data, proto.mutable_hlo()->mutable_hlo_module())) {
return InvalidArgument("Failed to parse input as HLO protobuf text");
}
} else {
return InvalidArgument(
"Invalid format from file extension: '%s'. Expected: hlo, txt, pb, "
"or pbtxt",
format);
}
TF_ASSIGN_OR_RETURN(HloModuleConfig config,
HloModule::CreateModuleConfigFromProto(
proto.hlo().hlo_module(), debug_options));
TF_RETURN_IF_ERROR(OverrideConfig(ovr_config, &config));
if (config_modifier_hook) {
config_modifier_hook(&config);
}
TF_ASSIGN_OR_RETURN(
module, HloModule::CreateFromProto(proto.hlo().hlo_module(), config));
}
return std::move(module);
}
absl::StatusOr<std::unique_ptr<HloModule>> LoadModuleFromFile(
const std::string& path, std::string format,
const hlo_module_loader_details::Config& ovr_config,
const std::function<void(HloModuleConfig*)>& config_modifier_hook,
BufferAssignmentProto* buffer_assignment_proto) {
std::string data;
if (format.empty()) {
format = std::string(tsl::io::Extension(path));
}
TF_RETURN_IF_ERROR(tsl::ReadFileToString(tsl::Env::Default(), path, &data));
return LoadModuleFromData(data, format, ovr_config, config_modifier_hook,
buffer_assignment_proto);
}
absl::StatusOr<std::unique_ptr<RunHloModuleIterationLiterals>>
LoadInputFromData(const std::string& data, std::string_view format) {
HloSnapshot proto;
if (format == "pb") {
if (!proto.ParseFromString(data) &&
!proto.mutable_hlo()->ParseFromString(data) &&
!proto.mutable_hlo()->mutable_hlo_module()->ParseFromString(data)) {
return InvalidArgument("Failed to parse input as HLO protobuf binary");
}
} else if (format == "pbtxt") {
if (!tsl::protobuf::TextFormat::ParseFromString(data, &proto) &&
!tsl::protobuf::TextFormat::ParseFromString(data,
proto.mutable_hlo()) &&
!tsl::protobuf::TextFormat::ParseFromString(
data, proto.mutable_hlo()->mutable_hlo_module())) {
return InvalidArgument("Failed to parse input as HLO protobuf text");
}
} else {
return InvalidArgument(
"Invalid format from file extension: '%s'. Expected: pb, "
"or pbtxt",
format);
}
auto iteration_literals_proto =
std::make_unique<RunHloModuleIterationLiterals>();
for (const auto& i : proto.arguments()) {
*iteration_literals_proto->add_arguments() = i;
}
return std::move(iteration_literals_proto);
}
absl::StatusOr<std::unique_ptr<RunHloModuleIterationLiterals>>
LoadInputFromFile(const std::string& path, std::string format) {
std::string data;
if (format.empty()) {
format = std::string(tsl::io::Extension(path));
}
TF_RETURN_IF_ERROR(tsl::ReadFileToString(tsl::Env::Default(), path, &data));
return LoadInputFromData(data, format);
}
} | #include "xla/tools/hlo_module_loader.h"
#include <string>
#include "xla/tests/hlo_test_base.h"
#include "tsl/lib/core/status_test_util.h"
#include "tsl/platform/test.h"
namespace xla {
namespace {
class HloModuleLoaderTest : public HloTestBase {};
TEST_F(HloModuleLoaderTest, StripsLogHeaders) {
const std::string& hlo_string = R"(
I0521 12:04:45.883483 1509 service.cc:186] HloModule test_log_stripping
I0521 12:04:45.883483 1509 service.cc:186]
I0521 12:04:45.883483 1509 service.cc:186] ENTRY entry {
I0521 12:04:45.883483 1509 service.cc:186] p0 = f32[4]{0} parameter(0)
I0521 12:04:45.883483 1509 service.cc:186] p1 = f32[4]{0} parameter(1)
I0521 12:04:45.883483 1509 service.cc:186] add = f32[4]{0} add(p0, p1)
I0521 12:04:45.883483 1509 service.cc:186] ROOT rooty = (f32[4]{0}, f32[4]{0}) tuple(p1, add)
I0521 12:04:45.883483 1509 service.cc:186] }
)";
TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> hlo_module,
LoadModuleFromData(hlo_string, "txt"));
EXPECT_NE(FindInstruction(hlo_module.get(), "p0"), nullptr);
EXPECT_NE(FindInstruction(hlo_module.get(), "p1"), nullptr);
EXPECT_NE(FindInstruction(hlo_module.get(), "add"), nullptr);
EXPECT_NE(FindInstruction(hlo_module.get(), "rooty"), nullptr);
}
}
} | 2,194 |
#ifndef XLA_TOOLS_MULTIHOST_HLO_RUNNER_FUNCTIONAL_HLO_RUNNER_H_
#define XLA_TOOLS_MULTIHOST_HLO_RUNNER_FUNCTIONAL_HLO_RUNNER_H_
#include <functional>
#include <memory>
#include <optional>
#include <random>
#include <string>
#include <string_view>
#include <vector>
#include "absl/container/btree_map.h"
#include "absl/status/statusor.h"
#include "absl/strings/string_view.h"
#include "absl/types/span.h"
#include "xla/hlo/ir/hlo_module.h"
#include "xla/literal.h"
#include "xla/pjrt/distributed/distributed.h"
#include "xla/pjrt/gpu/se_gpu_pjrt_client.h"
#include "xla/pjrt/pjrt_client.h"
#include "xla/pjrt/pjrt_executable.h"
#include "xla/xla.pb.h"
#include "tsl/platform/logging.h"
#include "tsl/platform/statusor.h"
namespace xla {
struct PjRtEnvironment {
std::unique_ptr<xla::PjRtClient> client;
std::unique_ptr<xla::DistributedRuntimeService> service;
std::shared_ptr<xla::KeyValueStoreInterface> kv_store;
std::shared_ptr<xla::DistributedRuntimeClient> distributed_client;
};
absl::StatusOr<PjRtEnvironment> GetPjRtClient(absl::string_view device_type,
absl::string_view address,
int node_id, int num_nodes,
bool enable_mock_nccl,
absl::Duration init_timeout);
enum class InputFormat {
kText,
kProtoText,
kProtoBinary,
kSnapshotProtoBinary,
};
class ProfilerInterface {
public:
virtual ~ProfilerInterface() = default;
virtual void CreateSession() = 0;
virtual void UploadSession() = 0;
};
bool AbslParseFlag(absl::string_view text, InputFormat* input_format,
std::string* error);
std::string AbslUnparseFlag(InputFormat input_format);
class FunctionalHloRunner {
public:
FunctionalHloRunner() = delete;
using LiteralVec = std::vector<Literal>;
using ShapeVec = std::vector<Shape>;
using PerDeviceLiteralVecType = absl::btree_map<int, LiteralVec>;
using PerDeviceShapeVecType = absl::btree_map<int, ShapeVec>;
using PerDeviceIndexVecType = absl::btree_map<int, std::vector<int>>;
enum class LogOutputMode { kLogOutput, kNotLogOutput };
enum class HloPassesMode {
kRunXLABackendOnly,
kDisableAllHloPasses,
kStandardCompile
};
enum class SpmdMode { kUseSpmdPartitioning, kNotUseSpmdPartitioning };
enum class SpmdPartitionedMode {
kIsSpmdPartitionedModule,
kIsNotSpmdPartitionedModule
};
enum class XlaTextDumpMode { kDumpAsText, kNotDumpAsText };
enum class XlaProtoDumpMode { kDumpAsProto, kNotDumpAsProto };
enum class ModuleArgumentMode {
kUseDeviceIdAsInput,
kUseRandomInputs,
kUseSharedRandomInputs,
kUseZerosAsInput,
kUninitialized,
};
enum class ModuleOutputMode {
kReturnOutputs,
kNotReturnOutputs,
kReturnDevice0Outputs
};
struct PreprocessingOptions {
SpmdPartitionedMode spmd_partitioned_mode =
SpmdPartitionedMode::kIsNotSpmdPartitionedModule;
std::optional<int> while_execution_count = std::nullopt;
bool remove_infeed_outfeed = true;
bool flatten_while_loop() const {
return while_execution_count.has_value();
}
bool is_spmd_partitioned_module() const {
return spmd_partitioned_mode ==
SpmdPartitionedMode::kIsSpmdPartitionedModule;
}
};
struct RawCompileOptions {
HloPassesMode hlo_passes_mode = HloPassesMode::kStandardCompile;
SpmdMode spmd_mode = SpmdMode::kNotUseSpmdPartitioning;
std::optional<ExecutionOptions> execution_options = std::nullopt;
std::optional<int> num_replicas = 1;
std::optional<int> num_partitions = 1;
std::optional<int> num_slices = std::nullopt;
std::string xla_dump_to = "";
XlaTextDumpMode xla_text_dump_mode = XlaTextDumpMode::kNotDumpAsText;
XlaProtoDumpMode xla_proto_dump_mode = XlaProtoDumpMode::kNotDumpAsProto;
};
struct RunningOptions {
ModuleArgumentMode module_argument_mode =
ModuleArgumentMode::kUseRandomInputs;
ModuleOutputMode module_output_mode = ModuleOutputMode::kReturnOutputs;
size_t num_repeats = 1;
bool recreate_buffers_between_repeats = false;
LogOutputMode log_input_output_mode = LogOutputMode::kNotLogOutput;
const MultiSliceConfig* multi_slice_config = nullptr;
ProfilerInterface* profiler = nullptr;
std::optional<bool> untuple_result = std::nullopt;
bool log_input_output() const {
return log_input_output_mode == LogOutputMode::kLogOutput;
}
};
struct HloModuleAndArguments {
std::unique_ptr<HloModule> hlo_module;
std::vector<Literal> arguments;
};
struct ReplicasAndPartitions {
int replicas = 1;
int partitions = 1;
};
static absl::StatusOr<std::unique_ptr<PjRtClient>> CreateHostClient();
static absl::StatusOr<std::unique_ptr<PjRtClient>> CreateGpuClient(
GpuClientOptions options);
static absl::StatusOr<std::unique_ptr<PjRtClient>> CreateMockGpuClient(
int num_nodes = 1);
static absl::StatusOr<ExecutionOptions> LoadExecutionOptions(
absl::string_view path);
static absl::StatusOr<CompileOptions> CreateCompileOptions(
const PjRtClient& client,
const FunctionalHloRunner::RawCompileOptions& raw_options,
int task_id = 0, int num_nodes = 1,
std::shared_ptr<xla::KeyValueStoreInterface> kv_store = nullptr);
static absl::Status LoadAndRunAndDump(
PjRtClient& client, const DebugOptions& debug_options,
const xla::FunctionalHloRunner::PreprocessingOptions& preproc_options,
const xla::FunctionalHloRunner::RawCompileOptions& raw_compile_options,
const xla::FunctionalHloRunner::RunningOptions& running_options,
absl::string_view hlo_text, InputFormat input_format,
std::string dump_output_to = "", int task_id = 0, int num_nodes = 1,
std::shared_ptr<xla::KeyValueStoreInterface> kv_store = nullptr);
static absl::StatusOr<PerDeviceLiteralVecType> LoadAndRun(
PjRtClient& client, const DebugOptions& debug_options,
const PreprocessingOptions& preproc_options,
const CompileOptions& compile_options,
const RunningOptions& running_options, absl::string_view hlo_text,
InputFormat input_format, const PerDeviceLiteralVecType& arguments = {});
static absl::Status LoadAndCompile(
PjRtClient& client, const DebugOptions& debug_options,
const PreprocessingOptions& preproc_options,
const RawCompileOptions& raw_compile_options, std::string_view hlo_file,
InputFormat input_format, int task_id = 0, int num_nodes = 1,
std::shared_ptr<xla::KeyValueStoreInterface> kv_store = nullptr);
static absl::StatusOr<PerDeviceLiteralVecType> CompileAndRun(
PjRtClient& client, const DebugOptions& debug_options,
const PreprocessingOptions& preproc_options,
const CompileOptions& compile_options,
const RunningOptions& running_options, HloModule* hlo_module,
const PerDeviceLiteralVecType& arguments = {});
static absl::StatusOr<std::unique_ptr<PjRtLoadedExecutable>> Compile(
PjRtClient& client, HloModule* hlo_module,
const DebugOptions& debug_options,
const PreprocessingOptions& preproc_options,
const CompileOptions& compile_options);
static absl::StatusOr<std::unique_ptr<PjRtExecutable>> Compile(
PjRtClient& client, HloModule* hlo_module,
const DebugOptions& debug_options,
const PreprocessingOptions& preproc_options,
const CompileOptions& compile_options,
const PjRtTopologyDescription& topology);
static absl::StatusOr<PerDeviceLiteralVecType> Run(
PjRtClient& client, PjRtLoadedExecutable* executable,
const PerDeviceLiteralVecType& arguments,
const RunningOptions& running_options,
std::minstd_rand0* engine = nullptr);
static absl::StatusOr<std::unique_ptr<HloModule>> ReadModuleFromHloTextFile(
absl::string_view hlo_file);
static absl::StatusOr<std::unique_ptr<HloModule>>
ReadModuleFromBinaryProtoFile(absl::string_view hlo_file);
static absl::StatusOr<std::unique_ptr<HloModule>> ReadModuleFromTextProtoFile(
absl::string_view hlo_file);
static absl::StatusOr<HloModuleAndArguments>
ReadModuleFromSnapshotBinaryProtoFile(absl::string_view hlo_file);
static absl::StatusOr<HloModuleAndArguments> LoadHloModuleAndArguments(
absl::string_view hlo_file, InputFormat input_format);
static absl::StatusOr<std::unique_ptr<HloModule>> ReadModuleFromString(
absl::string_view hlo_text);
static absl::StatusOr<std::unique_ptr<HloModule>> ReadModuleFromProto(
const HloModuleProto& proto);
static absl::Status PrepareHloModuleForCompilation(
HloModule* hlo_module, const DebugOptions& debug_options,
const PreprocessingOptions& preproc_options);
static CompileOptions CompleteCompileOptions(const HloModule& hlo_module,
CompileOptions compile_options);
static absl::Status DumpOutput(
const FunctionalHloRunner::PerDeviceLiteralVecType& output,
absl::string_view dump_output_to, int task_id);
private:
static ReplicasAndPartitions GetReplicasAndPartitions(
const std::optional<ExecutionOptions>& execution_options,
int device_count, const std::optional<int>& num_replicas,
const std::optional<int>& num_partitions, int num_slices = 1);
static ExecutableBuildOptions
CreateExecutableBuildOptionsFromExecutionOptions(
const ExecutionOptions& execution_options);
static absl::Span<PjRtDevice* const> GetLocalDevices(
const PjRtClient& client);
static absl::StatusOr<std::vector<std::vector<std::unique_ptr<PjRtBuffer>>>>
CreateArgumentsOnDevice(PjRtClient& client,
const PjRtLoadedExecutable* executable,
const RunningOptions& running_options,
bool flatten_arguments = false,
std::minstd_rand0* engine = nullptr);
static absl::StatusOr<std::vector<std::vector<std::unique_ptr<PjRtBuffer>>>>
CreateUninitializedArgumentsOnDevice(PjRtClient& client,
const PjRtLoadedExecutable* executable,
const RunningOptions& running_options,
bool flatten_arguments = false);
static absl::StatusOr<std::vector<std::vector<std::unique_ptr<PjRtBuffer>>>>
CopyArgumentsToDevice(PjRtClient& client,
const PjRtLoadedExecutable* executable,
const PerDeviceLiteralVecType& arguments,
bool log_input, bool flattened_arguments,
bool clone_device0_arguments = false);
static absl::StatusOr<PerDeviceLiteralVecType> RunInternal(
PjRtClient& client, PjRtLoadedExecutable* executable,
std::function<absl::StatusOr<
std::vector<std::vector<std::unique_ptr<PjRtBuffer>>>>(bool)>
create_argument_buffers_on_device,
const RunningOptions& running_options);
static absl::StatusOr<PerDeviceLiteralVecType> FetchAndLogOutput(
PjRtClient& client,
const std::vector<std::vector<std::unique_ptr<PjRtBuffer>>>&
output_buffers,
ModuleOutputMode module_output_mode, bool log_output);
static ReplicasAndPartitions GetReplicasAndPartitionsInternal(
const std::optional<ExecutionOptions>& execution_options,
int device_count, const std::optional<int>& num_replicas,
const std::optional<int>& num_partitions, int num_slices = 1);
};
bool AbslParseFlag(absl::string_view text,
FunctionalHloRunner::ModuleArgumentMode* argument_mode,
std::string* error);
std::string AbslUnparseFlag(
FunctionalHloRunner::ModuleArgumentMode argument_mode);
bool AbslParseFlag(absl::string_view text,
FunctionalHloRunner::ModuleOutputMode* output_mode,
std::string* error);
std::string AbslUnparseFlag(FunctionalHloRunner::ModuleOutputMode output_mode);
void AddShardingAnnotationsToSpmdPartitionedModule(HloModule* hlo_module);
}
#endif
#include "xla/tools/multihost_hlo_runner/functional_hlo_runner.h"
#include <cstddef>
#include <cstdint>
#include <functional>
#include <memory>
#include <optional>
#include <random>
#include <string>
#include <string_view>
#include <utility>
#include <vector>
#include "absl/algorithm/container.h"
#include "absl/container/btree_map.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/str_split.h"
#include "absl/strings/string_view.h"
#include "absl/synchronization/mutex.h"
#include "absl/time/time.h"
#include "absl/types/span.h"
#include "xla/client/executable_build_options.h"
#include "xla/client/xla_computation.h"
#include "xla/hlo/ir/hlo_input_output_alias_config.h"
#include "xla/hlo/ir/hlo_module.h"
#include "xla/hlo/ir/hlo_sharding.h"
#include "xla/layout.h"
#include "xla/literal.h"
#include "xla/literal_util.h"
#include "xla/pjrt/cpu/cpu_client.h"
#include "xla/pjrt/distributed/client.h"
#include "xla/pjrt/distributed/distributed.h"
#include "xla/pjrt/distributed/key_value_store_interface.h"
#include "xla/pjrt/distributed/service.h"
#include "xla/pjrt/gpu/se_gpu_pjrt_client.h"
#include "xla/pjrt/host_memory_spaces.h"
#include "xla/pjrt/pjrt_client.h"
#include "xla/pjrt/pjrt_compiler.h"
#include "xla/pjrt/pjrt_executable.h"
#include "xla/pjrt/pjrt_future.h"
#include "xla/primitive_util.h"
#include "xla/service/computation_layout.h"
#include "xla/service/computation_placer.h"
#include "xla/service/hlo_module_config.h"
#include "xla/service/hlo_parser.h"
#include "xla/service/hlo_pass_pipeline.h"
#include "xla/shape_util.h"
#include "xla/status_macros.h"
#include "xla/tests/test_utils.h"
#include "xla/tools/hlo_control_flow_flattening.h"
#include "xla/util.h"
#include "xla/xla.pb.h"
#include "tsl/platform/env.h"
#include "tsl/platform/errors.h"
#include "tsl/platform/status.h"
#include "tsl/platform/statusor.h"
namespace xla {
static absl::StatusOr<std::unique_ptr<xla::PjRtClient>> GetPjRtClient(
absl::string_view device_type, absl::string_view address, int node_id,
int num_nodes, bool enable_mock_nccl, absl::Duration init_timeout,
std::unique_ptr<xla::DistributedRuntimeService>& service,
std::shared_ptr<xla::KeyValueStoreInterface>& kv_store,
std::shared_ptr<xla::DistributedRuntimeClient>& distributed_client) {
if (device_type == "host") {
CHECK_EQ(num_nodes, 1);
return xla::FunctionalHloRunner::CreateHostClient();
}
if (device_type != "gpu") {
return absl::UnimplementedError(device_type);
}
if (enable_mock_nccl) {
CHECK_GT(num_nodes, 1);
return xla::FunctionalHloRunner::CreateMockGpuClient(num_nodes);
} else {
if (num_nodes == 1) {
return xla::FunctionalHloRunner::CreateGpuClient({});
} else {
TF_RET_CHECK(!address.empty());
TF_RET_CHECK(node_id >= 0)
<< "Node id is expected to be in range [0, num_nodes)";
TF_RET_CHECK(node_id < num_nodes)
<< "Node id is expected to be in range [0, num_nodes)";
CHECK_GT(address.length(), 0);
if (node_id == 0) {
std::string coordinator_bind_address =
"[::]:" + std::string(address).substr(address.rfind(':') + 1);
xla::CoordinationServiceImpl::Options options;
options.num_nodes = num_nodes;
auto status_or = xla::GetDistributedRuntimeService(
coordinator_bind_address, options);
TF_QCHECK_OK(status_or.status());
service = std::move(status_or.value());
}
xla::DistributedRuntimeClient::Options options;
options.node_id = node_id;
options.init_timeout = init_timeout;
distributed_client =
GetDistributedRuntimeClient(std::string(address), options);
TF_QCHECK_OK(distributed_client->Connect());
kv_store = GetDistributedKeyValueStore(distributed_client,
"gpu:");
GpuClientOptions gpu_client_options;
gpu_client_options.node_id = node_id;
gpu_client_options.num_nodes = num_nodes;
gpu_client_options.kv_store = kv_store;
return xla::FunctionalHloRunner::CreateGpuClient(
std::move(gpu_client_options));
}
}
}
absl::StatusOr<PjRtEnvironment> GetPjRtClient(absl::string_view device_type,
absl::string_view address,
int node_id, int num_nodes,
bool enable_mock_nccl,
absl::Duration init_timeout) {
PjRtEnvironment env;
TF_ASSIGN_OR_RETURN(env.client,
GetPjRtClient(device_type, address, node_id, num_nodes,
enable_mock_nccl, init_timeout, env.service,
env.kv_store, env.distributed_client));
return env;
}
namespace {
absl::StatusOr<std::unique_ptr<HloModule>> HloTextToModule(
absl::string_view hlo_text) {
return ParseAndReturnUnverifiedModule(hlo_text);
}
absl::StatusOr<std::unique_ptr<HloModule>> HloProtoToModule(
const HloModuleProto& proto) {
TF_ASSIGN_OR_RETURN(
HloModuleConfig config,
HloModule::CreateModuleConfigFromProto(proto, DebugOptions()));
TF_ASSIGN_OR_RETURN(std::unique_ptr<HloModule> module,
HloModule::CreateFromProto(proto, config));
return std::move(module);
}
template <typename ElementType>
void PopulateWithSameValue(Literal* literal, ElementType val) {
for (ElementType& element : literal->data<ElementType>()) {
element = static_cast<ElementType>(val);
}
}
absl::StatusOr<Literal> MakeFakeLiteralWithSameValue(const Shape& shape,
int value) {
if (shape.IsArray()) {
Shape new_shape = shape;
new_shape.mutable_layout()->clear_tiles();
return primitive_util::PrimitiveTypeSwitch<absl::StatusOr<Literal>>(
[&](auto type) -> absl::StatusOr<Literal> {
if constexpr (primitive_util::IsArrayType(type)) {
using NativeT = primitive_util::NativeTypeOf<type>;
Literal literal(new_shape);
PopulateWithSameValue(
&literal,
static_cast<NativeT>(type == PRED ? (value % 2) == 0 : value));
return literal;
}
return Unimplemented(
"Unsupported type for fake literal generation: %s",
ShapeUtil::HumanString(shape));
},
new_shape.element_type());
} else if (shape.IsTuple()) {
std::vector<Literal> subliterals;
for (const Shape& subshape : shape.tuple_shapes()) {
TF_ASSIGN_OR_RETURN(Literal subliteral,
MakeFakeLiteralWithSameValue(subshape, value));
subliterals.push_back(std::move(subliteral));
}
return LiteralUtil::MakeTupleOwned(std::move(subliterals));
}
return InvalidArgument("Unsupported type for fake literal generation: %s",
ShapeUtil::HumanString(shape));
}
}
bool AbslParseFlag(absl::string_view text, InputFormat* input_format,
std::string* error) {
if (text == "text") {
*input_format = InputFormat::kText;
return true;
}
if (text == "proto_text") {
*input_format = InputFormat::kProtoText;
return true;
}
if (text == "proto_binary") {
*input_format = InputFormat::kProtoBinary;
return true;
}
if (text == "snapshot_proto_binary") {
*input_format = InputFormat::kSnapshotProtoBinary;
return true;
}
*error = "unknown value for enumeration";
return false;
}
std::string AbslUnparseFlag(InputFormat input_format) {
switch (input_format) {
case InputFormat::kText:
return "text";
case InputFormat::kProtoText:
return "proto_text";
case InputFormat::kProtoBinary:
return "proto_binary";
case InputFormat::kSnapshotProtoBinary:
return "snapshot_proto_binary";
default:
return absl::StrCat(input_format);
}
}
bool AbslParseFlag(absl::string_view text,
FunctionalHloRunner::ModuleArgumentMode* argument_mode,
std::string* error) {
if (text == "use_device_id_as_input") {
*argument_mode =
FunctionalHloRunner::ModuleArgumentMode::kUseDeviceIdAsInput;
return true;
}
if (text == "use_random_inputs") {
*argument_mode = FunctionalHloRunner::ModuleArgumentMode::kUseRandomInputs;
return true;
}
if (text == "use_shared_random_inputs") {
*argument_mode =
FunctionalHloRunner::ModuleArgumentMode::kUseSharedRandomInputs;
return true;
}
if (text == "use_zeros_as_input") {
*argument_mode = FunctionalHloRunner::ModuleArgumentMode::kUseZerosAsInput;
return true;
}
if (text == "uninitialized") {
*argument_mode = FunctionalHloRunner::ModuleArgumentMode::kUninitialized;
return true;
}
*error =
"Unrecognized module argument mode specified. Expect "
"\"use_device_id_as_input\", \"use_random_inputs\", or "
"\"use_shared_random_inputs\".";
return false;
}
std::string AbslUnparseFlag(
FunctionalHloRunner::ModuleArgumentMode argument_mode) {
switch (argument_mode) {
case FunctionalHloRunner::ModuleArgumentMode::kUseDeviceIdAsInput:
return "use_device_id_as_input";
case FunctionalHloRunner::ModuleArgumentMode::kUseRandomInputs:
return "use_random_inputs";
case FunctionalHloRunner::ModuleArgumentMode::kUseSharedRandomInputs:
return "use_shared_random_inputs";
case FunctionalHloRunner::ModuleArgumentMode::kUseZerosAsInput:
return "use_zeros_as_input";
case FunctionalHloRunner::ModuleArgumentMode::kUninitialized:
return "uninitialized";
default:
LOG(FATAL) << "Unexpected argument mode.";
}
}
bool AbslParseFlag(absl::string_view text,
FunctionalHloRunner::ModuleOutputMode* output_mode,
std::string* error) {
if (text == "return_outputs") {
*output_mode = FunctionalHloRunner::ModuleOutputMode::kReturnOutputs;
return true;
}
if (text == "not_return_outputs") {
*output_mode = FunctionalHloRunner::ModuleOutputMode::kNotReturnOutputs;
return true;
}
if (text == "return_device_0_outputs") {
*output_mode = FunctionalHloRunner::ModuleOutputMode::kReturnDevice0Outputs;
return true;
}
*error =
"Unrecognized module output mode specified. Expect \"return_outputs\", "
"\"not_return_outputs\", or \"return_device_0_outputs\".";
return false;
}
std::string AbslUnparseFlag(FunctionalHloRunner::ModuleOutputMode output_mode) {
switch (output_mode) {
case FunctionalHloRunner::ModuleOutputMode::kReturnOutputs:
return "return_outputs";
case FunctionalHloRunner::ModuleOutputMode::kNotReturnOutputs:
return "not_return_outputs";
case FunctionalHloRunner::ModuleOutputMode::kReturnDevice0Outputs:
return "return_device_0_outputs";
default:
LOG(FATAL) << "Unexpected output mode.";
}
}
void AddShardingAnnotationsToSpmdPartitionedModule(HloModule* hlo_module) {
auto set_manual_sharding = [](HloInstruction* hlo) {
if (!hlo->has_sharding()) {
hlo->set_sharding(
HloSharding::Manual().NormalizeTupleSharding(hlo->shape()));
}
};
for (int64_t i = 0; i < hlo_module->entry_computation()->num_parameters();
++i) {
HloInstruction* param =
hlo_module->entry_computation()->parameter_instruction(i);
set_manual_sharding(param);
}
HloInstruction* entry_root =
hlo_module->entry_computation()->root_instruction();
set_manual_sharding(entry_root);
}
absl::StatusOr<std::unique_ptr<PjRtClient>>
FunctionalHloRunner::CreateHostClient() {
return GetTfrtCpuClient(CpuClientOptions());
}
absl::StatusOr<std::unique_ptr<PjRtClient>>
FunctionalHloRunner::CreateGpuClient(GpuClientOptions options) {
if (options.node_id < 0 || options.node_id >= options.num_nodes) {
return absl::InvalidArgumentError(
"Node id is expected to be in range [0, num_nodes)");
}
return GetStreamExecutorGpuClient(options);
}
absl::StatusOr<std::unique_ptr<PjRtClient>>
FunctionalHloRunner::CreateMockGpuClient(int num_nodes) {
GpuClientOptions options;
options.num_nodes = num_nodes;
options.enable_mock_nccl = true;
return GetStreamExecutorGpuClient(options);
}
absl::StatusOr<ExecutionOptions> FunctionalHloRunner::LoadExecutionOptions(
absl::string_view path) {
ExecutionOptions execution_options;
TF_RETURN_IF_ERROR(tsl::ReadTextOrBinaryProto(
tsl::Env::Default(), std::string(path), &execution_options));
return execution_options;
}
absl::StatusOr<CompileOptions> FunctionalHloRunner::CreateCompileOptions(
const PjRtClient& client,
const FunctionalHloRunner::RawCompileOptions& raw_options, int task_id,
int num_nodes, std::shared_ptr<xla::KeyValueStoreInterface> kv_store) {
CompileOptions compile_options;
if (raw_options.execution_options.has_value()) {
compile_options.executable_build_options =
CreateExecutabl | #include "xla/tools/multihost_hlo_runner/functional_hlo_runner.h"
#include <memory>
#include <string>
#include <vector>
#include <gtest/gtest.h>
#include "absl/log/check.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/match.h"
#include "absl/strings/str_format.h"
#include "absl/time/time.h"
#include "xla/debug_options_flags.h"
#include "xla/pjrt/distributed/key_value_store_interface.h"
#include "xla/pjrt/distributed/service.h"
#include "xla/pjrt/pjrt_client.h"
#include "xla/tests/filecheck.h"
#include "xla/tsl/util/command_line_flags.h"
#include "tsl/lib/core/status_test_util.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/statusor.h"
#include "tsl/platform/subprocess.h"
#include "tsl/platform/test.h"
namespace xla {
namespace {
using ::testing::SizeIs;
bool IsTestingCpu() {
#ifdef XLA_TEST_BACKEND_CPU
return true;
#endif
return false;
}
std::string GetHloPath(std::string file_name) {
return tsl::io::JoinPath(tsl::testing::XlaSrcRoot(), "tools",
"multihost_hlo_runner", "data", file_name);
}
absl::StatusOr<std::unique_ptr<xla::PjRtClient>> GetPjRtClient() {
if (IsTestingCpu()) {
return xla::FunctionalHloRunner::CreateHostClient();
}
return xla::FunctionalHloRunner::CreateGpuClient({});
}
using FunctionalHloRunnerTest = ::testing::Test;
TEST_F(FunctionalHloRunnerTest, SingleDeviceHlo) {
TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<xla::PjRtClient> client,
GetPjRtClient());
xla::DebugOptions debug_options;
FunctionalHloRunner::PreprocessingOptions preproc_options;
FunctionalHloRunner::RawCompileOptions raw_compile_options;
raw_compile_options.num_replicas = 1;
raw_compile_options.num_partitions = 1;
FunctionalHloRunner::RunningOptions running_options;
TF_EXPECT_OK(FunctionalHloRunner::LoadAndRunAndDump(
*client, debug_options, preproc_options, raw_compile_options,
running_options, {GetHloPath("single_device.hlo")}, InputFormat::kText));
}
TEST_F(FunctionalHloRunnerTest, Sharded2Devices) {
TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<xla::PjRtClient> client,
GetPjRtClient());
constexpr int kRequiredDeviceCount = 2;
const int kDeviceCount = client->device_count();
if (kDeviceCount < kRequiredDeviceCount) {
GTEST_SKIP() << "Requires " << kRequiredDeviceCount
<< " devices, but found only " << kDeviceCount;
return;
}
xla::DebugOptions debug_options;
FunctionalHloRunner::PreprocessingOptions preproc_options;
FunctionalHloRunner::RawCompileOptions raw_compile_options;
raw_compile_options.spmd_mode =
FunctionalHloRunner::SpmdMode::kUseSpmdPartitioning;
raw_compile_options.num_replicas = 1;
raw_compile_options.num_partitions = 2;
FunctionalHloRunner::RunningOptions running_options;
TF_EXPECT_OK(FunctionalHloRunner::LoadAndRunAndDump(
*client, debug_options, preproc_options, raw_compile_options,
running_options, {GetHloPath("sharded_2_devices.hlo")},
InputFormat::kText));
}
TEST_F(FunctionalHloRunnerTest, UseZerosAsInputs) {
TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<xla::PjRtClient> client,
GetPjRtClient());
constexpr int kRequiredDeviceCount = 2;
const int kDeviceCount = client->device_count();
if (kDeviceCount < kRequiredDeviceCount) {
GTEST_SKIP() << "Requires " << kRequiredDeviceCount
<< " devices, but found only " << kDeviceCount;
return;
}
xla::DebugOptions debug_options;
FunctionalHloRunner::PreprocessingOptions preproc_options;
FunctionalHloRunner::RawCompileOptions raw_compile_options;
raw_compile_options.spmd_mode =
FunctionalHloRunner::SpmdMode::kUseSpmdPartitioning;
raw_compile_options.num_replicas = 1;
raw_compile_options.num_partitions = 2;
FunctionalHloRunner::RunningOptions running_options;
running_options.module_argument_mode =
FunctionalHloRunner::ModuleArgumentMode::kUseZerosAsInput;
TF_EXPECT_OK(FunctionalHloRunner::LoadAndRunAndDump(
*client, debug_options, preproc_options, raw_compile_options,
running_options, {GetHloPath("sharded_2_devices.hlo")},
InputFormat::kText));
}
TEST_F(FunctionalHloRunnerTest, UseUninitializedInputs) {
TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<xla::PjRtClient> client,
GetPjRtClient());
constexpr int kRequiredDeviceCount = 2;
const int kDeviceCount = client->device_count();
if (kDeviceCount < kRequiredDeviceCount) {
GTEST_SKIP() << "Requires " << kRequiredDeviceCount
<< " devices, but found only " << kDeviceCount;
return;
}
xla::DebugOptions debug_options;
FunctionalHloRunner::PreprocessingOptions preproc_options;
FunctionalHloRunner::RawCompileOptions raw_compile_options;
raw_compile_options.spmd_mode =
FunctionalHloRunner::SpmdMode::kUseSpmdPartitioning;
raw_compile_options.num_replicas = 1;
raw_compile_options.num_partitions = 2;
FunctionalHloRunner::RunningOptions running_options;
running_options.module_argument_mode =
FunctionalHloRunner::ModuleArgumentMode::kUninitialized;
TF_EXPECT_OK(FunctionalHloRunner::LoadAndRunAndDump(
*client, debug_options, preproc_options, raw_compile_options,
running_options, {GetHloPath("sharded_2_devices.hlo")},
InputFormat::kText));
}
TEST_F(FunctionalHloRunnerTest, UseUninitializedInputsWithTupledArguments) {
TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<xla::PjRtClient> client,
GetPjRtClient());
xla::DebugOptions debug_options;
FunctionalHloRunner::PreprocessingOptions preproc_options;
FunctionalHloRunner::RawCompileOptions raw_compile_options;
raw_compile_options.spmd_mode =
FunctionalHloRunner::SpmdMode::kUseSpmdPartitioning;
raw_compile_options.num_replicas = 1;
raw_compile_options.num_partitions = 1;
FunctionalHloRunner::RunningOptions running_options;
running_options.module_argument_mode =
FunctionalHloRunner::ModuleArgumentMode::kUninitialized;
TF_EXPECT_OK(FunctionalHloRunner::LoadAndRunAndDump(
*client, debug_options, preproc_options, raw_compile_options,
running_options, {GetHloPath("single_device_tupled.hlo")},
InputFormat::kText));
}
TEST_F(FunctionalHloRunnerTest, CanCompileWithoutHavingEnoughGpus) {
tsl::Env* env = tsl::Env::Default();
std::string dump_dir;
ASSERT_TRUE(env->LocalTempFilename(&dump_dir));
tsl::FileSystem* fs = nullptr;
TF_ASSERT_OK(env->GetFileSystemForFile(dump_dir, &fs));
xla::DebugOptions debug_options;
FunctionalHloRunner::PreprocessingOptions preproc_options;
FunctionalHloRunner::RawCompileOptions raw_compile_options;
raw_compile_options.spmd_mode =
FunctionalHloRunner::SpmdMode::kUseSpmdPartitioning;
raw_compile_options.num_replicas = 1;
raw_compile_options.num_partitions = 16;
raw_compile_options.xla_dump_to = dump_dir;
TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<xla::PjRtClient> client,
GetPjRtClient());
TF_EXPECT_OK(FunctionalHloRunner::LoadAndCompile(
*client, debug_options, preproc_options, raw_compile_options,
GetHloPath("sharded_16_devices.hlo"), InputFormat::kText));
{
std::vector<std::string> after_opt_hlo_paths;
TF_ASSERT_OK(
fs->GetMatchingPaths(fs->JoinPath(dump_dir, "*after_optimizations.txt"),
&after_opt_hlo_paths));
ASSERT_THAT(after_opt_hlo_paths, SizeIs(1));
std::string after_opt_hlo;
TF_ASSERT_OK(
tsl::ReadFileToString(env, after_opt_hlo_paths[0], &after_opt_hlo));
absl::StatusOr<bool> file_check_result = RunFileCheck(after_opt_hlo, R"(
)");
TF_ASSERT_OK(file_check_result.status());
EXPECT_TRUE(file_check_result.value());
}
{
std::vector<std::string> ir_paths;
TF_ASSERT_OK(fs->GetMatchingPaths(fs->JoinPath(dump_dir, "*ir-no-opt.ll"),
&ir_paths));
ASSERT_THAT(ir_paths, SizeIs(1));
}
}
static const char* binary_name;
constexpr int kNumNodes = 3;
TEST_F(FunctionalHloRunnerTest, ShardedAutotuningWorks) {
if (IsTestingCpu()) {
GTEST_SKIP() << "GPU-only test.";
}
tsl::SubProcess child[kNumNodes];
for (int node_id = 0; node_id < kNumNodes; ++node_id) {
std::vector<std::string> argv;
argv.push_back(binary_name);
argv.push_back("--xla_gpu_shard_autotuning");
argv.push_back(absl::StrFormat("--node_id=%d", node_id));
child[node_id].SetProgram(binary_name, argv);
child[node_id].SetChannelAction(tsl::CHAN_STDOUT, tsl::ACTION_PIPE);
child[node_id].SetChannelAction(tsl::CHAN_STDERR, tsl::ACTION_PIPE);
ASSERT_TRUE(child[node_id].Start()) << "node " << node_id;
}
for (int node_id = 0; node_id < kNumNodes; ++node_id) {
std::string stdout_str;
std::string stderr_str;
int child_status =
child[node_id].Communicate(nullptr, &stdout_str, &stderr_str);
ASSERT_EQ(child_status, 0) << " node " << node_id << "\nstdout:\n"
<< stdout_str << "\nstderr:\n"
<< stderr_str;
}
}
absl::Status ShardedAutotuningWorksTestBody(const int node_id) {
tsl::setenv("CUDA_VISIBLE_DEVICES", std::to_string(node_id).data(),
true);
TF_ASSIGN_OR_RETURN(
PjRtEnvironment env,
xla::GetPjRtClient("gpu", "127.0.0.1:12345", node_id, kNumNodes,
false,
absl::Seconds(120)));
CHECK(env.kv_store != nullptr);
TF_RETURN_IF_ERROR(FunctionalHloRunner::LoadAndCompile(
*env.client, GetDebugOptionsFromFlags(),
FunctionalHloRunner::PreprocessingOptions{},
FunctionalHloRunner::RawCompileOptions{},
GetHloPath("multiple_gemm_fusions.hlo"), InputFormat::kText));
if (node_id == 0) {
TF_ASSIGN_OR_RETURN(std::string results0,
env.kv_store->Get("gemm_fusion_autotuning_results_1_0",
absl::Seconds(1)));
CHECK(absl::StrContains(results0, "run_time"));
TF_ASSIGN_OR_RETURN(std::string results1,
env.kv_store->Get("gemm_fusion_autotuning_results_1_1",
absl::Seconds(1)));
CHECK(absl::StrContains(results1, "run_time"));
CHECK_NE(results0, results1);
TF_ASSIGN_OR_RETURN(std::string results2,
env.kv_store->Get("gemm_fusion_autotuning_results_1_2",
absl::Seconds(1)));
CHECK(!absl::StrContains(results2, "run_time"));
}
return absl::OkStatus();
}
TEST_F(FunctionalHloRunnerTest, CanRunWithMockCollectives) {
if (IsTestingCpu()) {
GTEST_SKIP() << "GPU-only test";
}
xla::DebugOptions debug_options;
FunctionalHloRunner::PreprocessingOptions preproc_options;
FunctionalHloRunner::RawCompileOptions raw_compile_options;
raw_compile_options.spmd_mode =
FunctionalHloRunner::SpmdMode::kUseSpmdPartitioning;
raw_compile_options.num_replicas = 1;
raw_compile_options.num_partitions = 16;
FunctionalHloRunner::RunningOptions running_options;
running_options.module_argument_mode =
FunctionalHloRunner::ModuleArgumentMode::kUseZerosAsInput;
TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<xla::PjRtClient> client,
FunctionalHloRunner::CreateMockGpuClient(16));
TF_EXPECT_OK(FunctionalHloRunner::LoadAndRunAndDump(
*client, debug_options, preproc_options, raw_compile_options,
running_options, {GetHloPath("sharded_16_devices.hlo")},
InputFormat::kText));
}
}
}
int main(int argc, char* argv[]) {
xla::binary_name = argv[0];
int node_id = -1;
std::vector<tsl::Flag> flag_list = {
tsl::Flag("node_id", &node_id,
"Node ID for ShardedAutotuningWorks test."),
};
xla::AppendDebugOptionsFlags(&flag_list);
std::string usage = tsl::Flags::Usage(argv[0], flag_list);
tsl::Flags::Parse(&argc, argv, flag_list);
if (node_id >= 0) {
return !xla::ShardedAutotuningWorksTestBody(node_id).ok();
}
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
} | 2,195 |
#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);
}
}
}
} | 2,196 |
#ifndef XLA_FFI_EXECUTION_CONTEXT_H_
#define XLA_FFI_EXECUTION_CONTEXT_H_
#include <algorithm>
#include <cstdint>
#include <functional>
#include <memory>
#include <string_view>
#include <utility>
#include "absl/container/flat_hash_map.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "tsl/lib/gtl/int_type.h"
#include "tsl/platform/logging.h"
#include "tsl/platform/statusor.h"
namespace xla::ffi {
class ExecutionContext {
public:
template <typename T>
using Deleter = std::function<void(T*)>;
TSL_LIB_GTL_DEFINE_INT_TYPE(TypeId, int64_t);
static absl::StatusOr<TypeId> RegisterExternalTypeId(std::string_view name);
absl::Status Insert(TypeId type_id, void* data,
Deleter<void> deleter = nullptr);
template <typename T>
absl::Status Insert(T* data, Deleter<T> deleter = nullptr);
template <typename T, typename... Args>
absl::Status Emplace(Args&&... args);
template <typename T>
absl::StatusOr<T*> Lookup() const {
TF_ASSIGN_OR_RETURN(auto user_data, LookupUserData(GetTypeId<T>()));
return static_cast<T*>(user_data->data());
}
absl::StatusOr<void*> Lookup(TypeId type_id) const {
TF_ASSIGN_OR_RETURN(auto user_data, LookupUserData(type_id));
return user_data->data();
}
private:
class UserData {
public:
UserData(void* data, Deleter<void> deleter);
~UserData();
UserData(UserData&) = delete;
UserData& operator=(const UserData&) = delete;
void* data() const { return data_; }
private:
void* data_;
Deleter<void> deleter_;
};
static TypeId GetNextTypeId();
template <typename T>
static TypeId GetTypeId() {
static const TypeId id = GetNextTypeId();
return id;
}
absl::Status InsertUserData(TypeId type_id, std::unique_ptr<UserData> data);
absl::StatusOr<UserData*> LookupUserData(TypeId type_id) const;
absl::flat_hash_map<TypeId, std::unique_ptr<UserData>> user_data_;
};
template <typename T>
absl::Status ExecutionContext::Insert(T* data, Deleter<T> deleter) {
return InsertUserData(GetTypeId<T>(),
std::make_unique<UserData>(
data, [deleter = std::move(deleter)](void* data) {
if (deleter) deleter(static_cast<T*>(data));
}));
}
template <typename T, typename... Args>
absl::Status ExecutionContext::Emplace(Args&&... args) {
return InsertUserData(GetTypeId<T>(),
std::make_unique<UserData>(
new T(std::forward<Args>(args)...),
[](void* data) { delete static_cast<T*>(data); }));
}
}
#endif
#include "xla/ffi/execution_context.h"
#include <atomic>
#include <cstdint>
#include <memory>
#include <string>
#include <string_view>
#include <utility>
#include "absl/base/attributes.h"
#include "absl/base/const_init.h"
#include "absl/container/flat_hash_map.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/str_cat.h"
#include "absl/synchronization/mutex.h"
namespace xla::ffi {
ABSL_CONST_INIT absl::Mutex type_registry_mutex(absl::kConstInit);
using TypeRegistry = absl::flat_hash_map<std::string, ExecutionContext::TypeId>;
static TypeRegistry& StaticTypeRegistry() {
static auto* registry = new TypeRegistry();
return *registry;
}
ExecutionContext::TypeId ExecutionContext::GetNextTypeId() {
static auto* counter = new std::atomic<int64_t>(1);
return TypeId(counter->fetch_add(1));
}
ExecutionContext::UserData::UserData(void* data, Deleter<void> deleter)
: data_(data), deleter_(std::move(deleter)) {}
ExecutionContext::UserData::~UserData() {
if (deleter_) deleter_(data_);
}
absl::StatusOr<ExecutionContext::TypeId>
ExecutionContext::RegisterExternalTypeId(std::string_view name) {
absl::MutexLock lock(&type_registry_mutex);
auto& registry = StaticTypeRegistry();
auto emplaced = registry.emplace(name, TypeId(0));
if (!emplaced.second) {
return absl::AlreadyExistsError(
absl::StrCat("Type id ", emplaced.first->second.value(),
" already registered for type name ", name));
}
return emplaced.first->second = GetNextTypeId();
}
absl::Status ExecutionContext::Insert(TypeId type_id, void* data,
Deleter<void> deleter) {
return InsertUserData(type_id,
std::make_unique<UserData>(data, std::move(deleter)));
}
absl::Status ExecutionContext::InsertUserData(TypeId type_id,
std::unique_ptr<UserData> data) {
if (!data) return absl::InvalidArgumentError("User data must be not null");
auto emplaced = user_data_.emplace(type_id, std::move(data));
if (!emplaced.second) {
return absl::AlreadyExistsError(
absl::StrCat("User data with type id ", type_id.value(),
" already exists in execution context"));
}
return absl::OkStatus();
}
absl::StatusOr<ExecutionContext::UserData*> ExecutionContext::LookupUserData(
TypeId type_id) const {
auto it = user_data_.find(type_id);
if (it == user_data_.end()) {
return absl::NotFoundError(absl::StrCat("User data with type id ",
type_id.value(),
" not found in execution context"));
}
return it->second.get();
}
} | #include "xla/ffi/execution_context.h"
#include <cstdint>
#include <string>
#include "absl/status/status.h"
#include "tsl/lib/core/status_test_util.h"
#include "tsl/platform/statusor.h"
#include "tsl/platform/test.h"
namespace xla::ffi {
struct I32UserData {
explicit I32UserData(int32_t value) : value(value) {}
int32_t value;
};
struct StrUserData {
explicit StrUserData(std::string value) : value(value) {}
std::string value;
};
TEST(ExecutionContextTest, EmplaceUserData) {
ExecutionContext context;
TF_ASSERT_OK(context.Emplace<I32UserData>(42));
TF_ASSERT_OK(context.Emplace<StrUserData>("hello"));
TF_ASSERT_OK_AND_ASSIGN(auto* i32_data, context.Lookup<I32UserData>());
TF_ASSERT_OK_AND_ASSIGN(auto* str_data, context.Lookup<StrUserData>());
ASSERT_NE(i32_data, nullptr);
ASSERT_NE(str_data, nullptr);
ASSERT_EQ(i32_data->value, 42);
ASSERT_EQ(str_data->value, "hello");
}
TEST(ExecutionContextTest, InsertUserOwned) {
I32UserData user_data(42);
ExecutionContext context;
TF_ASSERT_OK(context.Insert(&user_data));
TF_ASSERT_OK_AND_ASSIGN(auto* i32_data, context.Lookup<I32UserData>());
ASSERT_EQ(i32_data, &user_data);
}
TEST(ExecutionContextTest, InsertUserOwnedWithTypeId) {
TF_ASSERT_OK_AND_ASSIGN(
ExecutionContext::TypeId type_id,
ExecutionContext::RegisterExternalTypeId("I32UserData"));
I32UserData user_data(42);
ExecutionContext context;
TF_ASSERT_OK(context.Insert(type_id, &user_data));
TF_ASSERT_OK_AND_ASSIGN(auto* i32_data, context.Lookup(type_id));
ASSERT_EQ(i32_data, &user_data);
}
TEST(ExecutionContextTest, UserDataNotFound) {
ExecutionContext context;
auto i32_data = context.Lookup<I32UserData>();
ASSERT_EQ(i32_data.status().code(), absl::StatusCode::kNotFound);
}
} | 2,197 |
#ifndef XLA_TESTS_LITERAL_TEST_UTIL_H_
#define XLA_TESTS_LITERAL_TEST_UTIL_H_
#include <initializer_list>
#include <memory>
#include <optional>
#include <random>
#include <string>
#include "absl/base/attributes.h"
#include "absl/types/span.h"
#include "xla/array2d.h"
#include "xla/array3d.h"
#include "xla/array4d.h"
#include "xla/error_spec.h"
#include "xla/literal.h"
#include "xla/literal_util.h"
#include "xla/test.h"
#include "xla/test_helpers.h"
#include "xla/types.h"
#include "xla/xla_data.pb.h"
#include "tsl/platform/errors.h"
#include "tsl/platform/test.h"
namespace xla {
class LiteralTestUtil {
public:
[[nodiscard]] static ::testing::AssertionResult EqualShapes(
const Shape& expected, const Shape& actual);
[[nodiscard]] static ::testing::AssertionResult EqualShapesAndLayouts(
const Shape& expected, const Shape& actual);
[[nodiscard]] static ::testing::AssertionResult Equal(
const LiteralSlice& expected, const LiteralSlice& actual);
template <typename NativeT>
static void ExpectR0Equal(NativeT expected, const LiteralSlice& actual);
template <typename NativeT>
static void ExpectR1Equal(absl::Span<const NativeT> expected,
const LiteralSlice& actual);
template <typename NativeT>
static void ExpectR2Equal(
std::initializer_list<std::initializer_list<NativeT>> expected,
const LiteralSlice& actual);
template <typename NativeT>
static void ExpectR3Equal(
std::initializer_list<
std::initializer_list<std::initializer_list<NativeT>>>
expected,
const LiteralSlice& actual);
template <typename NativeT>
static void ExpectR2EqualArray2D(const Array2D<NativeT>& expected,
const LiteralSlice& actual);
template <typename NativeT>
static void ExpectR3EqualArray3D(const Array3D<NativeT>& expected,
const LiteralSlice& actual);
template <typename NativeT>
static void ExpectR4EqualArray4D(const Array4D<NativeT>& expected,
const LiteralSlice& actual);
[[nodiscard]] static ::testing::AssertionResult Near(
const LiteralSlice& expected, const LiteralSlice& actual,
const ErrorSpec& error_spec,
std::optional<bool> detailed_message = std::nullopt);
template <typename NativeT>
static void ExpectR0Near(NativeT expected, const LiteralSlice& actual,
const ErrorSpec& error);
template <typename NativeT>
static void ExpectR1Near(absl::Span<const NativeT> expected,
const LiteralSlice& actual, const ErrorSpec& error);
template <typename NativeT>
static void ExpectR2Near(
std::initializer_list<std::initializer_list<NativeT>> expected,
const LiteralSlice& actual, const ErrorSpec& error);
template <typename NativeT>
static void ExpectR3Near(
std::initializer_list<
std::initializer_list<std::initializer_list<NativeT>>>
expected,
const LiteralSlice& actual, const ErrorSpec& error);
template <typename NativeT>
static void ExpectR4Near(
std::initializer_list<std::initializer_list<
std::initializer_list<std::initializer_list<NativeT>>>>
expected,
const LiteralSlice& actual, const ErrorSpec& error);
template <typename NativeT>
static void ExpectR2NearArray2D(const Array2D<NativeT>& expected,
const LiteralSlice& actual,
const ErrorSpec& error);
template <typename NativeT>
static void ExpectR3NearArray3D(const Array3D<NativeT>& expected,
const LiteralSlice& actual,
const ErrorSpec& error);
template <typename NativeT>
static void ExpectR4NearArray4D(const Array4D<NativeT>& expected,
const LiteralSlice& actual,
const ErrorSpec& error);
[[nodiscard]] static ::testing::AssertionResult NearOrEqual(
const LiteralSlice& expected, const LiteralSlice& actual,
const std::optional<ErrorSpec>& error);
private:
LiteralTestUtil(const LiteralTestUtil&) = delete;
LiteralTestUtil& operator=(const LiteralTestUtil&) = delete;
};
template <typename NativeT>
void LiteralTestUtil::ExpectR0Equal(NativeT expected,
const LiteralSlice& actual) {
EXPECT_TRUE(Equal(LiteralUtil::CreateR0<NativeT>(expected), actual));
}
template <typename NativeT>
void LiteralTestUtil::ExpectR1Equal(
absl::Span<const NativeT> expected, const LiteralSlice& actual) {
EXPECT_TRUE(Equal(LiteralUtil::CreateR1<NativeT>(expected), actual));
}
template <typename NativeT>
void LiteralTestUtil::ExpectR2Equal(
std::initializer_list<std::initializer_list<NativeT>> expected,
const LiteralSlice& actual) {
EXPECT_TRUE(Equal(LiteralUtil::CreateR2<NativeT>(expected), actual));
}
template <typename NativeT>
void LiteralTestUtil::ExpectR3Equal(
std::initializer_list<std::initializer_list<std::initializer_list<NativeT>>>
expected,
const LiteralSlice& actual) {
EXPECT_TRUE(Equal(LiteralUtil::CreateR3<NativeT>(expected), actual));
}
template <typename NativeT>
void LiteralTestUtil::ExpectR2EqualArray2D(
const Array2D<NativeT>& expected, const LiteralSlice& actual) {
EXPECT_TRUE(Equal(LiteralUtil::CreateR2FromArray2D(expected), actual));
}
template <typename NativeT>
void LiteralTestUtil::ExpectR3EqualArray3D(
const Array3D<NativeT>& expected, const LiteralSlice& actual) {
EXPECT_TRUE(Equal(LiteralUtil::CreateR3FromArray3D(expected), actual));
}
template <typename NativeT>
void LiteralTestUtil::ExpectR4EqualArray4D(
const Array4D<NativeT>& expected, const LiteralSlice& actual) {
EXPECT_TRUE(Equal(LiteralUtil::CreateR4FromArray4D(expected), actual));
}
template <typename NativeT>
void LiteralTestUtil::ExpectR0Near(NativeT expected,
const LiteralSlice& actual,
const ErrorSpec& error) {
EXPECT_TRUE(Near(LiteralUtil::CreateR0<NativeT>(expected), actual, error));
}
template <typename NativeT>
void LiteralTestUtil::ExpectR1Near(
absl::Span<const NativeT> expected, const LiteralSlice& actual,
const ErrorSpec& error) {
EXPECT_TRUE(Near(LiteralUtil::CreateR1<NativeT>(expected), actual, error));
}
template <typename NativeT>
void LiteralTestUtil::ExpectR2Near(
std::initializer_list<std::initializer_list<NativeT>> expected,
const LiteralSlice& actual, const ErrorSpec& error) {
EXPECT_TRUE(Near(LiteralUtil::CreateR2<NativeT>(expected), actual, error));
}
template <typename NativeT>
void LiteralTestUtil::ExpectR3Near(
std::initializer_list<std::initializer_list<std::initializer_list<NativeT>>>
expected,
const LiteralSlice& actual, const ErrorSpec& error) {
EXPECT_TRUE(Near(LiteralUtil::CreateR3<NativeT>(expected), actual, error));
}
template <typename NativeT>
void LiteralTestUtil::ExpectR4Near(
std::initializer_list<std::initializer_list<
std::initializer_list<std::initializer_list<NativeT>>>>
expected,
const LiteralSlice& actual, const ErrorSpec& error) {
EXPECT_TRUE(Near(LiteralUtil::CreateR4<NativeT>(expected), actual, error));
}
template <typename NativeT>
void LiteralTestUtil::ExpectR2NearArray2D(
const Array2D<NativeT>& expected, const LiteralSlice& actual,
const ErrorSpec& error) {
EXPECT_TRUE(Near(LiteralUtil::CreateR2FromArray2D(expected), actual, error));
}
template <typename NativeT>
void LiteralTestUtil::ExpectR3NearArray3D(
const Array3D<NativeT>& expected, const LiteralSlice& actual,
const ErrorSpec& error) {
EXPECT_TRUE(Near(LiteralUtil::CreateR3FromArray3D(expected), actual, error));
}
template <typename NativeT>
void LiteralTestUtil::ExpectR4NearArray4D(
const Array4D<NativeT>& expected, const LiteralSlice& actual,
const ErrorSpec& error) {
EXPECT_TRUE(Near(LiteralUtil::CreateR4FromArray4D(expected), actual, error));
}
}
#endif
#include "xla/tests/literal_test_util.h"
#include "absl/strings/str_format.h"
#include "xla/literal_comparison.h"
#include "tsl/platform/env.h"
#include "tsl/platform/path.h"
#include "tsl/platform/test.h"
namespace xla {
namespace {
void WriteLiteralToTempFile(const LiteralSlice& literal,
const std::string& name) {
std::string outdir;
if (!tsl::io::GetTestUndeclaredOutputsDir(&outdir)) {
outdir = tsl::testing::TmpDir();
}
auto* env = tsl::Env::Default();
std::string filename = tsl::io::JoinPath(
outdir, absl::StrFormat("tempfile-%d-%s", env->NowMicros(), name));
TF_CHECK_OK(tsl::WriteBinaryProto(env, absl::StrCat(filename, ".pb"),
literal.ToProto()));
TF_CHECK_OK(tsl::WriteStringToFile(env, absl::StrCat(filename, ".txt"),
literal.ToString()));
LOG(ERROR) << "wrote Literal to " << name << " file: " << filename
<< ".{pb,txt}";
}
void OnMiscompare(const LiteralSlice& expected, const LiteralSlice& actual,
const LiteralSlice& mismatches,
const ShapeIndex& ,
const literal_comparison::ErrorBuckets& ) {
LOG(INFO) << "expected: " << ShapeUtil::HumanString(expected.shape()) << " "
<< literal_comparison::ToStringTruncated(expected);
LOG(INFO) << "actual: " << ShapeUtil::HumanString(actual.shape()) << " "
<< literal_comparison::ToStringTruncated(actual);
LOG(INFO) << "Dumping literals to temp files...";
WriteLiteralToTempFile(expected, "expected");
WriteLiteralToTempFile(actual, "actual");
WriteLiteralToTempFile(mismatches, "mismatches");
}
::testing::AssertionResult StatusToAssertion(const absl::Status& s) {
if (s.ok()) {
return ::testing::AssertionSuccess();
}
return ::testing::AssertionFailure() << s.message();
}
}
::testing::AssertionResult LiteralTestUtil::EqualShapes(
const Shape& expected, const Shape& actual) {
return StatusToAssertion(literal_comparison::EqualShapes(expected, actual));
}
::testing::AssertionResult LiteralTestUtil::EqualShapesAndLayouts(
const Shape& expected, const Shape& actual) {
if (expected.ShortDebugString() != actual.ShortDebugString()) {
return ::testing::AssertionFailure()
<< "want: " << expected.ShortDebugString()
<< " got: " << actual.ShortDebugString();
}
return ::testing::AssertionSuccess();
}
::testing::AssertionResult LiteralTestUtil::Equal(
const LiteralSlice& expected, const LiteralSlice& actual) {
return StatusToAssertion(literal_comparison::Equal(expected, actual));
}
::testing::AssertionResult LiteralTestUtil::Near(
const LiteralSlice& expected, const LiteralSlice& actual,
const ErrorSpec& error_spec, std::optional<bool> detailed_message) {
return StatusToAssertion(literal_comparison::Near(
expected, actual, error_spec, detailed_message, &OnMiscompare));
}
::testing::AssertionResult LiteralTestUtil::NearOrEqual(
const LiteralSlice& expected, const LiteralSlice& actual,
const std::optional<ErrorSpec>& error) {
if (error.has_value()) {
VLOG(1) << "Expects near";
return StatusToAssertion(literal_comparison::Near(
expected, actual, *error, std::nullopt,
&OnMiscompare));
}
VLOG(1) << "Expects equal";
return StatusToAssertion(literal_comparison::Equal(expected, actual));
}
} | #include "xla/tests/literal_test_util.h"
#include <vector>
#include "absl/strings/str_join.h"
#include "xla/literal.h"
#include "xla/test_helpers.h"
#include "tsl/platform/env.h"
#include "tsl/platform/logging.h"
#include "tsl/platform/path.h"
#include "tsl/platform/test.h"
namespace xla {
namespace {
TEST(LiteralTestUtilTest, ComparesEqualTuplesEqual) {
Literal literal = LiteralUtil::MakeTupleFromSlices({
LiteralUtil::CreateR0<int32_t>(42),
LiteralUtil::CreateR0<int32_t>(64),
});
EXPECT_TRUE(LiteralTestUtil::Equal(literal, literal));
}
TEST(LiteralTestUtilTest, ComparesEqualComplex64TuplesEqual) {
Literal literal = LiteralUtil::MakeTupleFromSlices({
LiteralUtil::CreateR0<complex64>({42.0, 64.0}),
LiteralUtil::CreateR0<complex64>({64.0, 42.0}),
});
EXPECT_TRUE(LiteralTestUtil::Equal(literal, literal));
}
TEST(LiteralTestUtilTest, ComparesEqualComplex128TuplesEqual) {
Literal literal = LiteralUtil::MakeTupleFromSlices({
LiteralUtil::CreateR0<complex128>({42.0, 64.0}),
LiteralUtil::CreateR0<complex128>({64.0, 42.0}),
});
EXPECT_TRUE(LiteralTestUtil::Equal(literal, literal));
}
TEST(LiteralTestUtilTest, ComparesUnequalComplex64TuplesUnequal) {
Literal literal0 = LiteralUtil::MakeTupleFromSlices({
LiteralUtil::CreateR0<complex64>({42.0, 64.0}),
LiteralUtil::CreateR0<complex64>({64.0, 42.0}),
});
Literal literal1 = LiteralUtil::MakeTupleFromSlices({
LiteralUtil::CreateR0<complex64>({64.0, 42.0}),
LiteralUtil::CreateR0<complex64>({42.0, 64.0}),
});
Literal literal2 = LiteralUtil::MakeTupleFromSlices({
LiteralUtil::CreateR0<complex64>({42.42, 64.0}),
LiteralUtil::CreateR0<complex64>({64.0, 42.0}),
});
Literal literal3 = LiteralUtil::MakeTupleFromSlices({
LiteralUtil::CreateR0<complex64>({42.0, 64.0}),
LiteralUtil::CreateR0<complex64>({64.0, 42.42}),
});
EXPECT_FALSE(LiteralTestUtil::Equal(literal0, literal1));
EXPECT_FALSE(LiteralTestUtil::Equal(literal0, literal2));
EXPECT_FALSE(LiteralTestUtil::Equal(literal0, literal3));
EXPECT_FALSE(LiteralTestUtil::Equal(literal2, literal3));
}
TEST(LiteralTestUtilTest, ComparesUnequalComplex128TuplesUnequal) {
Literal literal0 = LiteralUtil::MakeTupleFromSlices({
LiteralUtil::CreateR0<complex128>({42.0, 64.0}),
LiteralUtil::CreateR0<complex128>({64.0, 42.0}),
});
Literal literal1 = LiteralUtil::MakeTupleFromSlices({
LiteralUtil::CreateR0<complex128>({64.0, 42.0}),
LiteralUtil::CreateR0<complex128>({42.0, 64.0}),
});
Literal literal2 = LiteralUtil::MakeTupleFromSlices({
LiteralUtil::CreateR0<complex128>({42.42, 64.0}),
LiteralUtil::CreateR0<complex128>({64.0, 42.0}),
});
Literal literal3 = LiteralUtil::MakeTupleFromSlices({
LiteralUtil::CreateR0<complex128>({42.0, 64.0}),
LiteralUtil::CreateR0<complex128>({64.0, 42.42}),
});
EXPECT_FALSE(LiteralTestUtil::Equal(literal0, literal1));
EXPECT_FALSE(LiteralTestUtil::Equal(literal0, literal2));
EXPECT_FALSE(LiteralTestUtil::Equal(literal0, literal3));
EXPECT_FALSE(LiteralTestUtil::Equal(literal2, literal3));
}
TEST(LiteralTestUtilTest, ComparesUnequalTuplesUnequal) {
auto unequal_things_are_equal = [] {
Literal lhs = LiteralUtil::MakeTupleFromSlices({
LiteralUtil::CreateR0<int32_t>(42),
LiteralUtil::CreateR0<int32_t>(64),
});
Literal rhs = LiteralUtil::MakeTupleFromSlices({
LiteralUtil::CreateR0<int32_t>(64),
LiteralUtil::CreateR0<int32_t>(42),
});
CHECK(LiteralTestUtil::Equal(lhs, rhs)) << "LHS and RHS are unequal";
};
ASSERT_DEATH(unequal_things_are_equal(), "LHS and RHS are unequal");
}
TEST(LiteralTestUtilTest, ExpectNearFailurePlacesResultsInTemporaryDirectory) {
auto dummy_lambda = [] {
auto two = LiteralUtil::CreateR0<float>(2);
auto four = LiteralUtil::CreateR0<float>(4);
ErrorSpec error(0.001);
CHECK(LiteralTestUtil::Near(two, four, error)) << "two is not near four";
};
tsl::Env* env = tsl::Env::Default();
std::string outdir;
if (!tsl::io::GetTestUndeclaredOutputsDir(&outdir)) {
outdir = tsl::testing::TmpDir();
}
std::string pattern = tsl::io::JoinPath(outdir, "tempfile-*.pb");
std::vector<std::string> files;
TF_CHECK_OK(env->GetMatchingPaths(pattern, &files));
for (const auto& f : files) {
TF_CHECK_OK(env->DeleteFile(f)) << f;
}
ASSERT_DEATH(dummy_lambda(), "two is not near four");
std::vector<std::string> results;
TF_CHECK_OK(env->GetMatchingPaths(pattern, &results));
LOG(INFO) << "results: [" << absl::StrJoin(results, ", ") << "]";
EXPECT_EQ(3, results.size());
for (const std::string& result : results) {
LiteralProto literal_proto;
TF_CHECK_OK(
tsl::ReadBinaryProto(tsl::Env::Default(), result, &literal_proto));
Literal literal = Literal::CreateFromProto(literal_proto).value();
if (result.find("expected") != std::string::npos) {
EXPECT_EQ("f32[] 2", literal.ToString());
} else if (result.find("actual") != std::string::npos) {
EXPECT_EQ("f32[] 4", literal.ToString());
} else if (result.find("mismatches") != std::string::npos) {
EXPECT_EQ("pred[] true", literal.ToString());
} else {
FAIL() << "unknown file in temporary directory: " << result;
}
}
}
TEST(LiteralTestUtilTest, NotEqualHasValuesInMessage) {
auto expected = LiteralUtil::CreateR1<int32_t>({1, 2, 3});
auto actual = LiteralUtil::CreateR1<int32_t>({4, 5, 6});
::testing::AssertionResult result = LiteralTestUtil::Equal(expected, actual);
EXPECT_THAT(result.message(),
::testing::HasSubstr("Expected literal:\ns32[3] {1, 2, 3}"));
EXPECT_THAT(result.message(),
::testing::HasSubstr("Actual literal:\ns32[3] {4, 5, 6}"));
}
TEST(LiteralTestUtilTest, NearComparatorR1) {
auto a = LiteralUtil::CreateR1<float>(
{0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8});
auto b = LiteralUtil::CreateR1<float>(
{0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8});
EXPECT_TRUE(LiteralTestUtil::Near(a, b, ErrorSpec{0.0001}));
}
TEST(LiteralTestUtilTest, NearComparatorR1Complex64) {
auto a = LiteralUtil::CreateR1<complex64>({{0.0, 1.0},
{0.1, 1.1},
{0.2, 1.2},
{0.3, 1.3},
{0.4, 1.4},
{0.5, 1.5},
{0.6, 1.6},
{0.7, 1.7},
{0.8, 1.8}});
auto b = LiteralUtil::CreateR1<complex64>({{0.0, 1.0},
{0.1, 1.1},
{0.2, 1.2},
{0.3, 1.3},
{0.4, 1.4},
{0.5, 1.5},
{0.6, 1.6},
{0.7, 1.7},
{0.8, 1.8}});
auto c = LiteralUtil::CreateR1<complex64>({{0.0, 1.0},
{0.1, 1.1},
{0.2, 1.2},
{0.3, 1.3},
{0.4, 1.4},
{0.5, 1.5},
{0.6, 1.6},
{0.7, 1.7},
{0.9, 1.8}});
auto d = LiteralUtil::CreateR1<complex64>({{0.0, 1.0},
{0.1, 1.1},
{0.2, 1.2},
{0.3, 1.3},
{0.4, 1.4},
{0.5, 1.5},
{0.6, 1.6},
{0.7, 1.7},
{0.8, 1.9}});
EXPECT_TRUE(LiteralTestUtil::Near(a, b, ErrorSpec{0.0001}));
EXPECT_FALSE(LiteralTestUtil::Near(a, c, ErrorSpec{0.0001}));
EXPECT_FALSE(LiteralTestUtil::Near(a, d, ErrorSpec{0.0001}));
EXPECT_FALSE(LiteralTestUtil::Near(c, d, ErrorSpec{0.0001}));
}
TEST(LiteralTestUtilTest, NearComparatorR1Complex128) {
auto a = LiteralUtil::CreateR1<complex128>({{0.0, 1.0},
{0.1, 1.1},
{0.2, 1.2},
{0.3, 1.3},
{0.4, 1.4},
{0.5, 1.5},
{0.6, 1.6},
{0.7, 1.7},
{0.8, 1.8}});
auto b = LiteralUtil::CreateR1<complex128>({{0.0, 1.0},
{0.1, 1.1},
{0.2, 1.2},
{0.3, 1.3},
{0.4, 1.4},
{0.5, 1.5},
{0.6, 1.6},
{0.7, 1.7},
{0.8, 1.8}});
auto c = LiteralUtil::CreateR1<complex128>({{0.0, 1.0},
{0.1, 1.1},
{0.2, 1.2},
{0.3, 1.3},
{0.4, 1.4},
{0.5, 1.5},
{0.6, 1.6},
{0.7, 1.7},
{0.9, 1.8}});
auto d = LiteralUtil::CreateR1<complex128>({{0.0, 1.0},
{0.1, 1.1},
{0.2, 1.2},
{0.3, 1.3},
{0.4, 1.4},
{0.5, 1.5},
{0.6, 1.6},
{0.7, 1.7},
{0.8, 1.9}});
EXPECT_TRUE(LiteralTestUtil::Near(a, b, ErrorSpec{0.0001}));
EXPECT_FALSE(LiteralTestUtil::Near(a, c, ErrorSpec{0.0001}));
EXPECT_FALSE(LiteralTestUtil::Near(a, d, ErrorSpec{0.0001}));
EXPECT_FALSE(LiteralTestUtil::Near(c, d, ErrorSpec{0.0001}));
}
TEST(LiteralTestUtilTest, NearComparatorR1Nan) {
auto a = LiteralUtil::CreateR1<float>(
{0.0, 0.1, 0.2, 0.3, NAN, 0.5, 0.6, 0.7, 0.8});
auto b = LiteralUtil::CreateR1<float>(
{0.0, 0.1, 0.2, 0.3, NAN, 0.5, 0.6, 0.7, 0.8});
EXPECT_TRUE(LiteralTestUtil::Near(a, b, ErrorSpec{0.0001}));
}
TEST(LiteralTestUtil, NearComparatorDifferentLengths) {
auto a = LiteralUtil::CreateR1<float>(
{0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8});
auto b =
LiteralUtil::CreateR1<float>({0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7});
EXPECT_FALSE(LiteralTestUtil::Near(a, b, ErrorSpec{0.0001}));
EXPECT_FALSE(LiteralTestUtil::Near(b, a, ErrorSpec{0.0001}));
}
TEST(LiteralTestUtilTest, ExpectNearDoubleOutsideFloatValueRange) {
auto two_times_float_max =
LiteralUtil::CreateR0<double>(2.0 * std::numeric_limits<float>::max());
ErrorSpec error(0.001);
EXPECT_TRUE(
LiteralTestUtil::Near(two_times_float_max, two_times_float_max, error));
}
TEST(LiteralTestUtilTest, DynamicEqualityR1) {
auto literal1 = Literal(ShapeUtil::MakeShape(U32, {10}));
literal1.PopulateR1<uint32_t>({1, 2, 3, 4, 5, 6, 7, 8, 9, 10});
literal1.SetDynamicSize(0, 5);
auto literal2 = Literal(ShapeUtil::MakeShape(U32, {10}));
literal2.PopulateR1<uint32_t>({1, 2, 3, 4, 5, 99, 99, 99, 99, 99});
literal2.SetDynamicSize(0, 5);
EXPECT_TRUE(LiteralTestUtil::Equal(literal1, literal2));
}
TEST(LiteralTestUtilTest, DynamicEqualityR2Dim) {
auto literal1 = Literal(ShapeUtil::MakeShape(U32, {3, 3}));
literal1.PopulateR2<uint32_t>({{1, 2, 3}, {4, 5, 6}, {7, 8, 9}});
literal1.SetDynamicSize(0, 2);
auto literal2 = Literal(ShapeUtil::MakeShape(U32, {3, 3}));
literal2.PopulateR2<uint32_t>({{1, 2, 3}, {4, 5, 6}, {99, 99, 99}});
literal2.SetDynamicSize(0, 2);
EXPECT_TRUE(LiteralTestUtil::Equal(literal1, literal2));
}
TEST(LiteralTestUtilTest, DynamicEqualityR2Dim1) {
auto literal1 = Literal(ShapeUtil::MakeShape(U32, {3, 3}));
literal1.PopulateR2<uint32_t>({{1, 2, 3}, {4, 5, 6}, {7, 8, 9}});
literal1.SetDynamicSize(1, 2);
auto literal2 = Literal(ShapeUtil::MakeShape(U32, {3, 3}));
literal2.PopulateR2<uint32_t>({{1, 2, 99}, {4, 5, 99}, {7, 8, 99}});
literal2.SetDynamicSize(1, 2);
EXPECT_TRUE(LiteralTestUtil::Equal(literal1, literal2));
}
TEST(LiteralTestUtilTest, DynamicNearEqualityR1) {
auto literal1 = Literal(ShapeUtil::MakeShape(F32, {10}));
literal1.PopulateR1<float>({1, 2, 3, 4, 5, 6, 7, 8, 9, 10});
literal1.SetDynamicSize(0, 5);
auto literal2 = Literal(ShapeUtil::MakeShape(F32, {10}));
literal2.PopulateR1<float>({1, 2, 3, 4, 5, 99, 99, 99, 99, 99});
literal2.SetDynamicSize(0, 5);
ErrorSpec error(0.001);
EXPECT_TRUE(LiteralTestUtil::Near(literal1, literal2, error));
}
TEST(LiteralTestUtilTest, DynamicNearEqualityR2Dim) {
auto literal1 = Literal(ShapeUtil::MakeShape(F32, {3, 3}));
literal1.PopulateR2<float>({{1, 2, 3}, {4, 5, 6}, {7, 8, 9}});
literal1.SetDynamicSize(0, 2);
auto literal2 = Literal(ShapeUtil::MakeShape(F32, {3, 3}));
literal2.PopulateR2<float>({{1, 2, 3}, {4, 5, 6}, {99, 99, 99}});
literal2.SetDynamicSize(0, 2);
ErrorSpec error(0.001);
EXPECT_TRUE(LiteralTestUtil::Near(literal1, literal2, error));
}
TEST(LiteralTestUtilTest, DynamicNearEqualityR2Dim1) {
auto literal1 = Literal(ShapeUtil::MakeShape(F32, {3, 3}));
literal1.PopulateR2<float>({{1, 2, 3}, {4, 5, 6}, {7, 8, 9}});
literal1.SetDynamicSize(1, 2);
auto literal2 = Literal(ShapeUtil::MakeShape(F32, {3, 3}));
literal2.PopulateR2<float>({{1, 2, 99}, {4, 5, 99}, {7, 8, 99}});
literal2.SetDynamicSize(1, 2);
ErrorSpec error(0.001);
EXPECT_TRUE(LiteralTestUtil::Near(literal1, literal2, error));
}
TEST(LiteralTestUtilTest, UnequalDynamicDimensionsR1) {
auto literal1 = Literal(ShapeUtil::MakeShape(U32, {10}));
literal1.PopulateR1<uint32_t>({1, 2, 3, 4, 5, 6, 7, 8, 9, 10});
literal1.SetDynamicSize(0, 5);
auto literal2 = Literal(ShapeUtil::MakeShape(U32, {10}));
literal2.PopulateR1<uint32_t>({1, 2, 3, 4, 5, 6, 7, 8, 9, 10});
literal2.SetDynamicSize(0, 6);
EXPECT_FALSE(LiteralTestUtil::Equal(literal1, literal2));
}
TEST(LiteralTestUtilTest, UnequalDynamicDimensionsR1_F32) {
auto literal1 = Literal(ShapeUtil::MakeShape(F32, {10}));
literal1.PopulateR1<float>({1, 2, 3, 4, 5, 6, 7, 8, 9, 10});
literal1.SetDynamicSize(0, 5);
auto literal2 = Literal(ShapeUtil::MakeShape(F32, {10}));
literal2.PopulateR1<float>({1, 2, 3, 4, 5, 6, 7, 8, 9, 10});
literal2.SetDynamicSize(0, 6);
EXPECT_FALSE(LiteralTestUtil::Near(literal1, literal2, ErrorSpec{0.0001}));
}
TEST(LiteralTestUtilTest, ExpectedIsDynamicActualIsNotR1) {
auto literal1 = Literal(ShapeUtil::MakeShape(U32, {10}));
literal1.PopulateR1<uint32_t>({1, 2, 3, 4, 5, 6, 7, 8, 9, 10});
literal1.SetDynamicSize(0, 5);
auto literal2 = Literal(ShapeUtil::MakeShape(U32, {10}));
literal2.PopulateR1<uint32_t>({1, 2, 3, 4, 5, 6, 7, 8, 9, 10});
EXPECT_FALSE(LiteralTestUtil::Equal(literal1, literal2));
}
TEST(LiteralTestUtilTest, ExpectedIsDynamicActualIsNotR1_F32) {
auto literal1 = Literal(ShapeUtil::MakeShape(F32, {10}));
literal1.PopulateR1<float>({1, 2, 3, 4, 5, 6, 7, 8, 9, 10});
literal1.SetDynamicSize(0, 5);
auto literal2 = Literal(ShapeUtil::MakeShape(F32, {10}));
literal2.PopulateR1<float>({1, 2, 3, 4, 5, 6, 7, 8, 9, 10});
EXPECT_FALSE(LiteralTestUtil::Near(literal1, literal2, ErrorSpec{0.0001}));
}
TEST(LiteralTestUtilTest, ActualIsDynamicExpectedIsNotR1) {
auto literal1 = Literal(ShapeUtil::MakeShape(U32, {10}));
literal1.PopulateR1<uint32_t>({1, 2, 3, 4, 5, 6, 7, 8, 9, 10});
auto literal2 = Literal(ShapeUtil::MakeShape(U32, {10}));
literal2.PopulateR1<uint32_t>({1, 2, 3, 4, 5, 6, 7, 8, 9, 10});
literal2.SetDynamicSize(0, 5);
EXPECT_FALSE(LiteralTestUtil::Equal(literal1, literal2));
}
TEST(LiteralTestUtilTest, ActualIsDynamicExpectedIsNotR1_F32) {
auto literal1 = Literal(ShapeUtil::MakeShape(F32, {10}));
literal1.PopulateR1<float>({1, 2, 3, 4, 5, 6, 7, 8, 9, 10});
auto literal2 = Literal(ShapeUtil::MakeShape(F32, {10}));
literal2.PopulateR1<float>({1, 2, 3, 4, 5, 6, 7, 8, 9, 10});
literal2.SetDynamicSize(0, 5);
EXPECT_FALSE(LiteralTestUtil::Near(literal1, literal2, ErrorSpec{0.0001}));
}
TEST(LiteralTestUtilTest, UnequalDynamicDimensionsR2Dim0) {
auto literal1 = Literal(ShapeUtil::MakeShape(U32, {3, 3}));
literal1.PopulateR2<uint32_t>({{1, 2, 3}, {4, 5, 6}, {7, 8, 9}});
literal1.SetDynamicSize(0, 2);
auto literal2 = Literal(ShapeUtil::MakeShape(U32, {3, 3}));
literal2.PopulateR2<uint32_t>({{1, 2, 3}, {4, 5, 6}, {7, 8, 9}});
literal2.SetDynamicSize(0, 3);
EXPECT_FALSE(LiteralTestUtil::Equal(literal1, literal2));
}
TEST(LiteralTestUtilTest, UnequalDynamicDimensionsR2Dim0_F32) {
auto literal1 = Literal(ShapeUtil::MakeShape(F32, {3, 3}));
literal1.PopulateR2<float>({{1, 2, 3}, {4, 5, 6}, {7, 8, 9}});
literal1.SetDynamicSize(0, 2);
auto literal2 = Literal(ShapeUtil::MakeShape(F32, {3, 3}));
literal2.PopulateR2<float>({{1, 2, 3}, {4, 5, 6}, {7, 8, 9}});
literal2.SetDynamicSize(0, 3);
EXPECT_FALSE(LiteralTestUtil::Near(literal1, literal2, ErrorSpec{0.0001}));
}
TEST(LiteralTestUtilTest, UnequalDynamicDimensionsR2Dim1) {
auto literal1 = Literal(ShapeUtil::MakeShape(U32, {3, 3}));
literal1.PopulateR2<uint32_t>({{1, 2, 3}, {4, 5, 6}, {7, 8, 9}});
literal1.SetDynamicSize(1, 2);
auto literal2 = Literal(ShapeUtil::MakeShape(U32, {3, 3}));
literal2.PopulateR2<uint32_t>({{1, 2, 3}, {4, 5, 6}, {7, 8, 9}});
literal2.SetDynamicSize(1, 3);
EXPECT_FALSE(LiteralTestUtil::Equal(literal1, literal2));
}
TEST(LiteralTestUtilTest, UnequalDynamicDimensionsR2Dim1_F32) {
auto literal1 = Literal(ShapeUtil::MakeShape(F32, {3, 3}));
literal1.PopulateR2<float>({{1, 2, 3}, {4, 5, 6}, {7, 8, 9}});
literal1.SetDynamicSize(1, 2);
auto literal2 = Literal(ShapeUtil::MakeShape(F32, {3, 3}));
literal2.PopulateR2<float>({{1, 2, 3}, {4, 5, 6}, {7, 8, 9}});
literal2.SetDynamicSize(1, 3);
EXPECT_FALSE(LiteralTestUtil::Near(literal1, literal2, ErrorSpec{0.0001}));
}
TEST(LiteralTestUtilTest, UnequalDynamicDimensionsR2DifferentDimensions) {
auto literal1 = Literal(ShapeUtil::MakeShape(U32, {3, 3}));
literal1.PopulateR2<uint32_t>({{1, 2, 3}, {4, 5, 6}, {7, 8, 9}});
literal1.SetDynamicSize(1, 2);
auto literal2 = Literal(ShapeUtil::MakeShape(U32, {3, 3}));
literal2.PopulateR2<uint32_t>({{1, 2, 3}, {4, 5, 6}, {7, 8, 9}});
literal2.SetDynamicSize(0, 2);
EXPECT_FALSE(LiteralTestUtil::Equal(literal1, literal2));
}
TEST(LiteralTestUtilTest, UnequalDynamicDimensionsR2DifferentDimensions_F32) {
auto literal1 = Literal(ShapeUtil::MakeShape(F32, {3, 3}));
literal1.PopulateR2<float>({{1, 2, 3}, {4, 5, 6}, {7, 8, 9}});
literal1.SetDynamicSize(1, 2);
auto literal2 = Literal(ShapeUtil::MakeShape(F32, {3, 3}));
literal2.PopulateR2<float>({{1, 2, 3}, {4, 5, 6}, {7, 8, 9}});
literal2.SetDynamicSize(0, 2);
EXPECT_FALSE(LiteralTestUtil::Near(literal1, literal2, ErrorSpec{0.0001}));
}
TEST(LiteralTestUtilTest, DynamicTuplesAreEqual) {
auto literal1 = Literal(ShapeUtil::MakeTupleShape(
{ShapeUtil::MakeShape(U32, {5}), ShapeUtil::MakeShape(U32, {5})}));
auto literal2 = Literal(ShapeUtil::MakeTupleShape(
{ShapeUtil::MakeShape(U32, {5}), ShapeUtil::MakeShape(U32, {5})}));
MutableBorrowingLiteral(&literal1, {0})
.PopulateR1<uint32_t>({1, 2, 3, 4, 5});
MutableBorrowingLiteral(&literal1, {1})
.PopulateR1<uint32_t>({1, 2, 3, 4, 5});
literal1.SetDynamicSize(0, {0}, 5);
MutableBorrowingLiteral(&literal2, {0})
.PopulateR1<uint32_t>({1, 2, 3, 4, 5});
MutableBorrowingLiteral(&literal2, {1})
.PopulateR1<uint32_t>({1, 2, 3, 4, 5});
literal2.SetDynamicSize(0, {0}, 5);
EXPECT_TRUE(LiteralTestUtil::Equal(literal1, literal2));
}
TEST(LiteralTestUtilTest, DynamicTuplesAreNear) {
auto literal1 = Literal(ShapeUtil::MakeTupleShape(
{ShapeUtil::MakeShape(F32, {5}), ShapeUtil::MakeShape(F32, {5})}));
auto literal2 = Literal(ShapeUtil::MakeTupleShape(
{ShapeUtil::MakeShape(F32, {5}), ShapeUtil::MakeShape(F32, {5})}));
MutableBorrowingLiteral(&literal1, {0})
.PopulateR1<float>({1, 2, 3, 4, 5});
MutableBorrowingLiteral(&literal1, {1})
.PopulateR1<float>({1, 2, 3, 4, 5});
literal1.SetDynamicSize(0, {0}, 5);
MutableBorrowingLiteral(&literal2, {0})
.PopulateR1<float>({1, 2, 3, 4, 5});
MutableBorrowingLiteral(&literal2, {1})
.PopulateR1<float>({1, 2, 3, 4, 5});
literal2.SetDynamicSize(0, {0}, 5);
EXPECT_TRUE(LiteralTestUtil::Near(literal1, literal2, ErrorSpec{0.0001}));
}
TEST(LiteralTestUtilTest, DynamicTuplesAreEqualWithinDynamicBounds) {
auto literal1 = Literal(ShapeUtil::MakeTupleShape(
{ShapeUtil::MakeShape(U32, {5}), ShapeUtil::MakeShape(U32, {5})}));
auto literal2 = Literal(ShapeUtil::MakeTupleShape(
{ShapeUtil::MakeShape(U32, {5}), ShapeUtil::MakeShape(U32, {5})}));
MutableBorrowingLiteral(&literal1, {0})
.PopulateR1<uint32_t>({1, 2, 3, 4, 5});
MutableBorrowingLiteral(&literal1, {1})
.PopulateR1<uint32_t>({1, 2, 3, 4, 5});
literal1.SetDynamicSize(0, {0}, 3);
MutableBorrowingLiteral(&literal2, {0})
.PopulateR1<uint32_t>({1, 2, 3, 99, 99});
MutableBorrowingLiteral(&literal2, {1})
.PopulateR1<uint32_t>({1, 2, 3, 4, 5});
literal2.SetDynamicSize(0, {0}, 3);
EXPECT_TRUE(LiteralTestUtil::Equal(literal1, literal2));
}
TEST(LiteralTestUtilTest, DynamicTuplesAreNearWithinDynamicBounds) {
auto literal1 = Literal(ShapeUtil::MakeTupleShape(
{ShapeUtil::MakeShape(F32, {5}), ShapeUtil::MakeShape(F32, {5})}));
auto literal2 = Literal(ShapeUtil::MakeTupleShape(
{ShapeUtil::MakeShape(F32, {5}), ShapeUtil::MakeShape(F32, {5})}));
MutableBorrowingLiteral(&literal1, {0})
.PopulateR1<float>({1, 2, 3, 4, 5});
MutableBorrowingLiteral(&literal1, {1})
.PopulateR1<float>({1, 2, 3, 4, 5});
literal1.SetDynamicSize(0, {0}, 3);
MutableBorrowingLiteral(&literal2, {0})
.PopulateR1<float>({1, 2, 3, 99, 99});
MutableBorrowingLiteral(&literal2, {1})
.PopulateR1<float>({1, 2, 3, 4, 5});
literal2.SetDynamicSize(0, {0}, 3);
EXPECT_TRUE(LiteralTestUtil::Near(literal1, literal2, ErrorSpec{0.0001}));
}
TEST(LiteralTestUtilTest, DynamicTuplesHaveDifferentDynamicSizes) {
auto literal1 = Literal(ShapeUtil::MakeTupleShape(
{ShapeUtil::MakeShape(U32, {5}), ShapeUtil::MakeShape(U32, {5})}));
auto literal2 = Literal(ShapeUtil::MakeTupleShape(
{ShapeUtil::MakeShape(U32, {5}), ShapeUtil::MakeShape(U32, {5})}));
MutableBorrowingLiteral(&literal1, {0})
.PopulateR1<uint32_t>({1, 2, 3, 4, 5});
MutableBorrowingLiteral(&literal1, {1})
.PopulateR1<uint32_t>({1, 2, 3, 4, 5});
literal1.SetDynamicSize(0, {0}, 5);
MutableBorrowingLiteral(&literal2, {0})
.PopulateR1<uint32_t>({1, 2, 3, 4, 5});
MutableBorrowingLiteral(&literal2, {1})
.PopulateR1<uint32_t>({1, 2, 3, 4, 5});
literal2.SetDynamicSize(0, {0}, 4);
EXPECT_FALSE(LiteralTestUtil::Equal(literal1, literal2));
}
TEST(LiteralTestUtilTest, DynamicTuplesHaveDifferentDynamicSizes_F32) {
auto literal1 = Literal(ShapeUtil::MakeTupleShape(
{ShapeUtil::MakeShape(F32, {5}), ShapeUtil::MakeShape(F32, {5})}));
auto literal2 = Literal(ShapeUtil::MakeTupleShape(
{ShapeUtil::MakeShape(F32, {5}), ShapeUtil::MakeShape(F32, {5})}));
MutableBorrowingLiteral(&literal1, {0})
.PopulateR1<float>({1, 2, 3, 4, 5});
MutableBorrowingLiteral(&literal1, {1})
.PopulateR1<float>({1, 2, 3, 4, 5});
literal1.SetDynamicSize(0, {0}, 5);
MutableBorrowingLiteral(&literal2, {0})
.PopulateR1<float>({1, 2, 3, 4, 5});
MutableBorrowingLiteral(&literal2, {1})
.PopulateR1<float>({1, 2, 3, 4, 5});
literal2.SetDynamicSize(0, {0}, 4);
EXPECT_FALSE(LiteralTestUtil::Near(literal1, literal2, ErrorSpec{0.0001}));
}
TEST(LiteralTestUtilTest, OneTupleDynamicOneIsNot) {
auto literal1 = Literal(ShapeUtil::MakeTupleShape(
{ShapeUtil::MakeShape(U32, {5}), ShapeUtil::MakeShape(U32, {5})}));
auto literal2 = Literal(ShapeUtil::MakeTupleShape(
{ShapeUtil::MakeShape(U32, {5}), ShapeUtil::MakeShape(U32, {5})}));
MutableBorrowingLiteral(&literal1, {0})
.PopulateR1<uint32_t>({1, 2, 3, 4, 5});
MutableBorrowingLiteral(&literal1, {1})
.PopulateR1<uint32_t>({1, 2, 3, 4, 5});
literal1.SetDynamicSize(0, {0}, 5);
MutableBorrowingLiteral(&literal2, {0})
.PopulateR1<uint32_t>({1, 2, 3, 4, 5});
MutableBorrowingLiteral(&literal2, {1})
.PopulateR1<uint32_t>({1, 2, 3, 4, 5});
EXPECT_FALSE(LiteralTestUtil::Equal(literal1, literal2));
}
TEST(LiteralTestUtilTest, OneTupleDynamicOneIsNot_F32) {
auto literal1 = Literal(ShapeUtil::MakeTupleShape(
{ShapeUtil::MakeShape(F32, {5}), ShapeUtil::MakeShape(F32, {5})}));
auto literal2 = Literal(ShapeUtil::MakeTupleShape(
{ShapeUtil::MakeShape(F32, {5}), ShapeUtil::MakeShape(F32, {5})}));
MutableBorrowingLiteral(&literal1, {0})
.PopulateR1<float>({1, 2, 3, 4, 5});
MutableBorrowingLiteral(&literal1, {1})
.PopulateR1<float>({1, 2, 3, 4, 5});
literal1.SetDynamicSize(0, {0}, 5);
MutableBorrowingLiteral(&literal2, {0})
.PopulateR1<float>({1, 2, 3, 4, 5});
MutableBorrowingLiteral(&literal2, {1})
.PopulateR1<float>({1, 2, 3, 4, 5});
EXPECT_FALSE(LiteralTestUtil::Near(literal1, literal2, ErrorSpec{0.0001}));
}
}
} | 2,198 |
#ifndef XLA_BACKENDS_PROFILER_CPU_HOST_TRACER_H_
#define XLA_BACKENDS_PROFILER_CPU_HOST_TRACER_H_
#include <memory>
#include "tsl/profiler/lib/profiler_interface.h"
namespace xla {
namespace profiler {
struct HostTracerOptions {
int trace_level = 2;
};
std::unique_ptr<tsl::profiler::ProfilerInterface> CreateHostTracer(
const HostTracerOptions& options);
}
}
#endif
#include "xla/backends/profiler/cpu/host_tracer.h"
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "absl/log/log.h"
#include "absl/status/status.h"
#include "tsl/platform/errors.h"
#include "tsl/profiler/backends/cpu/host_tracer_utils.h"
#include "tsl/profiler/backends/cpu/threadpool_listener.h"
#include "tsl/profiler/backends/cpu/traceme_recorder.h"
#include "tsl/profiler/lib/profiler_collection.h"
#include "tsl/profiler/lib/profiler_interface.h"
#include "tsl/profiler/protobuf/xplane.pb.h"
#include "tsl/profiler/utils/time_utils.h"
#include "tsl/profiler/utils/xplane_schema.h"
#include "tsl/profiler/utils/xplane_utils.h"
namespace xla {
namespace profiler {
namespace {
class HostTracer : public tsl::profiler::ProfilerInterface {
public:
explicit HostTracer(int host_trace_level);
~HostTracer() override;
absl::Status Start() override;
absl::Status Stop() override;
absl::Status CollectData(
tensorflow::profiler::XSpace* space) override;
private:
const int host_trace_level_;
bool recording_ = false;
uint64_t start_timestamp_ns_ = 0;
tsl::profiler::TraceMeRecorder::Events events_;
};
HostTracer::HostTracer(int host_trace_level)
: host_trace_level_(host_trace_level) {}
HostTracer::~HostTracer() { Stop().IgnoreError(); }
absl::Status HostTracer::Start() {
if (recording_) {
return tsl::errors::Internal("TraceMeRecorder already started");
}
start_timestamp_ns_ = tsl::profiler::GetCurrentTimeNanos();
recording_ = tsl::profiler::TraceMeRecorder::Start(host_trace_level_);
if (!recording_) {
return tsl::errors::Internal("Failed to start TraceMeRecorder");
}
return absl::OkStatus();
}
absl::Status HostTracer::Stop() {
if (!recording_) {
return tsl::errors::Internal("TraceMeRecorder not started");
}
events_ = tsl::profiler::TraceMeRecorder::Stop();
recording_ = false;
return absl::OkStatus();
}
absl::Status HostTracer::CollectData(
tensorflow::profiler::XSpace* space) {
VLOG(2) << "Collecting data to XSpace from HostTracer.";
if (recording_) {
return tsl::errors::Internal("TraceMeRecorder not stopped");
}
if (events_.empty()) {
return absl::OkStatus();
}
tensorflow::profiler::XPlane* plane =
tsl::profiler::FindOrAddMutablePlaneWithName(
space, tsl::profiler::kHostThreadsPlaneName);
ConvertCompleteEventsToXPlane(start_timestamp_ns_, std::exchange(events_, {}),
plane);
return absl::OkStatus();
}
}
std::unique_ptr<tsl::profiler::ProfilerInterface> CreateHostTracer(
const HostTracerOptions& options) {
if (options.trace_level == 0) return nullptr;
std::vector<std::unique_ptr<tsl::profiler::ProfilerInterface>> profilers;
profilers.push_back(std::make_unique<HostTracer>(options.trace_level));
profilers.push_back(
std::make_unique<tsl::profiler::ThreadpoolProfilerInterface>());
return std::make_unique<tsl::profiler::ProfilerCollection>(
std::move(profilers));
}
}
} | #include "xla/backends/profiler/cpu/host_tracer.h"
#include <cstdint>
#include <memory>
#include <optional>
#include <ostream>
#include <string>
#include <gtest/gtest.h>
#include "absl/types/optional.h"
#include "tsl/lib/core/status_test_util.h"
#include "tsl/platform/blocking_counter.h"
#include "tsl/platform/env.h"
#include "tsl/platform/test.h"
#include "tsl/platform/threadpool.h"
#include "tsl/platform/types.h"
#include "tsl/profiler/lib/profiler_interface.h"
#include "tsl/profiler/lib/traceme.h"
#include "tsl/profiler/protobuf/xplane.pb.h"
#include "tsl/profiler/utils/tf_xplane_visitor.h"
#include "tsl/profiler/utils/timespan.h"
#include "tsl/profiler/utils/xplane_schema.h"
#include "tsl/profiler/utils/xplane_visitor.h"
namespace xla {
namespace profiler {
namespace {
using ::tsl::Env;
using ::tsl::Thread;
using ::tsl::ThreadOptions;
using ::tsl::profiler::StatType;
using ::tsl::profiler::Timespan;
using ::tsl::profiler::TraceMe;
using ::tsl::profiler::XEventVisitor;
using ::tsl::profiler::XLineVisitor;
using ::tsl::profiler::XPlaneVisitor;
using ::tsl::profiler::XStatVisitor;
TEST(HostTracerTest, CollectsTraceMeEventsAsXSpace) {
tsl::uint32 thread_id;
std::string thread_name = "MyThreadName";
tensorflow::profiler::XSpace space;
std::unique_ptr<Thread> traced_thread(
Env::Default()->StartThread(ThreadOptions(), thread_name, [&] {
ASSERT_TRUE(Env::Default()->GetCurrentThreadName(&thread_name));
thread_id = Env::Default()->GetCurrentThreadId();
auto tracer = CreateHostTracer({});
TF_ASSERT_OK(tracer->Start());
{ TraceMe traceme("hello"); }
{ TraceMe traceme("world"); }
{ TraceMe traceme("contains#inside"); }
{ TraceMe traceme("good#key1=value1#"); }
{ TraceMe traceme("morning#key1=value1,key2=value2#"); }
{ TraceMe traceme("incomplete#key1=value1,key2#"); }
{ TraceMe traceme("Iterator::XXX::YYY::ParallelMap"); }
TF_ASSERT_OK(tracer->Stop());
TF_ASSERT_OK(tracer->CollectData(&space));
}));
traced_thread.reset();
ASSERT_NO_FATAL_FAILURE();
ASSERT_EQ(space.planes_size(), 1);
const auto& plane = space.planes(0);
XPlaneVisitor xplane(&plane);
ASSERT_EQ(plane.name(), ::tsl::profiler::kHostThreadsPlaneName);
ASSERT_EQ(plane.lines_size(), 1);
ASSERT_EQ(plane.event_metadata_size(), 7);
ASSERT_EQ(plane.stat_metadata_size(), 4);
const auto& line = plane.lines(0);
EXPECT_EQ(line.id(), thread_id);
EXPECT_EQ(line.name(), thread_name);
ASSERT_EQ(line.events_size(), 7);
const auto& events = line.events();
XEventVisitor e0(&xplane, &line, &events[0]);
EXPECT_EQ(e0.Name(), "hello");
ASSERT_EQ(events[0].stats_size(), 0);
XEventVisitor e1(&xplane, &line, &events[1]);
EXPECT_EQ(e1.Name(), "world");
ASSERT_EQ(events[1].stats_size(), 0);
XEventVisitor e2(&xplane, &line, &events[2]);
EXPECT_EQ(e2.Name(), "contains#inside");
ASSERT_EQ(events[2].stats_size(), 0);
XEventVisitor e3(&xplane, &line, &events[3]);
EXPECT_EQ(e3.Name(), "good");
ASSERT_EQ(events[3].stats_size(), 1);
{
std::optional<std::string> value;
e3.ForEachStat([&](const XStatVisitor& stat) {
if (stat.Name() == "key1") value = stat.ToString();
});
ASSERT_TRUE(value);
EXPECT_EQ(*value, "value1");
}
XEventVisitor e4(&xplane, &line, &events[4]);
EXPECT_EQ(e4.Name(), "morning");
ASSERT_EQ(events[4].stats_size(), 2);
{
std::optional<std::string> value1, value2;
e4.ForEachStat([&](const XStatVisitor& stat) {
if (stat.Name() == "key1") {
value1 = stat.ToString();
} else if (stat.Name() == "key2") {
value2 = stat.ToString();
}
});
ASSERT_TRUE(value1 && value2);
EXPECT_EQ(*value1, "value1");
EXPECT_EQ(*value2, "value2");
}
XEventVisitor e5(&xplane, &line, &events[5]);
EXPECT_EQ(e5.Name(), "incomplete");
ASSERT_EQ(events[5].stats_size(), 1);
{
std::optional<std::string> value1, value2;
e5.ForEachStat([&](const XStatVisitor& stat) {
if (stat.Name() == "key1") {
value1 = stat.ToString();
} else if (stat.Name() == "key2") {
value2 = stat.ToString();
}
});
ASSERT_TRUE(value1 && !value2);
EXPECT_EQ(*value1, "value1");
}
XEventVisitor e6(&xplane, &line, &events[6]);
EXPECT_EQ(e6.Name(), "Iterator::XXX::YYY::ParallelMap");
EXPECT_EQ(e6.DisplayName(), "Iterator::ParallelMap");
}
TEST(HostTracerTest, CollectEventsFromThreadPool) {
auto thread_pool =
std::make_unique<tsl::thread::ThreadPool>(Env::Default(),
"HostTracerTest",
1);
tsl::BlockingCounter counter(1);
auto tracer = CreateHostTracer({});
TF_EXPECT_OK(tracer->Start());
thread_pool->Schedule([&counter] {
TraceMe traceme("hello");
counter.DecrementCount();
});
counter.Wait();
thread_pool.reset();
TF_EXPECT_OK(tracer->Stop());
tensorflow::profiler::XSpace space;
TF_EXPECT_OK(tracer->CollectData(&space));
EXPECT_THAT(space.planes(), testing::SizeIs(1));
XPlaneVisitor xplane = tsl::profiler::CreateTfXPlaneVisitor(&space.planes(0));
bool has_record_event = false;
bool has_start_region_event = false;
bool has_end_region_event = false;
int64_t record_region_id = 0;
int64_t start_region_id = 0;
Timespan region_timespan;
Timespan traceme_timespan;
xplane.ForEachLine([&](const XLineVisitor& line) {
line.ForEachEvent([&](const XEventVisitor& event) {
if (event.Name() == tsl::profiler::kThreadpoolListenerRecord) {
has_record_event = true;
const auto& stat = event.GetStat(StatType::kProducerId);
EXPECT_TRUE(stat.has_value());
record_region_id = stat->IntOrUintValue();
} else if (event.Name() ==
tsl::profiler::kThreadpoolListenerStartRegion) {
has_start_region_event = true;
const auto& stat = event.GetStat(StatType::kConsumerId);
EXPECT_TRUE(stat.has_value());
start_region_id = stat->IntOrUintValue();
region_timespan = event.GetTimespan();
} else if (event.Name() == tsl::profiler::kThreadpoolListenerStopRegion) {
has_end_region_event = true;
region_timespan = Timespan::FromEndPoints(region_timespan.begin_ps(),
event.GetTimespan().end_ps());
} else if (event.Name() == "hello") {
traceme_timespan = event.GetTimespan();
}
});
});
EXPECT_TRUE(has_record_event);
EXPECT_TRUE(has_start_region_event);
EXPECT_TRUE(has_end_region_event);
EXPECT_EQ(record_region_id, start_region_id);
EXPECT_TRUE(region_timespan.Includes(traceme_timespan));
}
}
}
} | 2,199 |
#ifndef XLA_BACKENDS_PROFILER_PLUGIN_PLUGIN_TRACER_IMPL_H_
#define XLA_BACKENDS_PROFILER_PLUGIN_PLUGIN_TRACER_IMPL_H_
#include <cstddef>
#include <cstdint>
#include <memory>
#include <optional>
#include <vector>
#include "xla/backends/profiler/plugin/profiler_c_api.h"
#include "tsl/profiler/lib/profiler_interface.h"
#include "tsl/profiler/protobuf/xplane.pb.h"
struct PLUGIN_Profiler {
std::optional<tensorflow::profiler::XSpace> space;
std::unique_ptr<std::vector<uint8_t>> buffer;
size_t byte_size;
std::unique_ptr<tsl::profiler::ProfilerInterface> impl;
bool stopped;
};
namespace xla {
namespace profiler {
PLUGIN_Profiler_Error* PLUGIN_Profiler_Create(
PLUGIN_Profiler_Create_Args* args);
PLUGIN_Profiler_Error* PLUGIN_Profiler_Destroy(
PLUGIN_Profiler_Destroy_Args* args);
PLUGIN_Profiler_Error* PLUGIN_Profiler_Start(PLUGIN_Profiler_Start_Args* args);
PLUGIN_Profiler_Error* PLUGIN_Profiler_Stop(PLUGIN_Profiler_Stop_Args* args);
PLUGIN_Profiler_Error* PLUGIN_Profiler_CollectData(
PLUGIN_Profiler_CollectData_Args* args);
}
}
#endif
#include "xla/backends/profiler/plugin/plugin_tracer_impl.h"
#include <cstddef>
#include <cstdint>
#include <memory>
#include <vector>
#include "xla/backends/profiler/plugin/profiler_c_api.h"
#include "xla/backends/profiler/plugin/profiler_error.h"
#include "tsl/platform/logging.h"
#include "tsl/profiler/lib/profiler_collection.h"
#include "tsl/profiler/lib/profiler_factory.h"
#include "tsl/profiler/protobuf/profiler_options.pb.h"
#include "tsl/profiler/protobuf/xplane.pb.h"
namespace xla {
namespace profiler {
PLUGIN_Profiler_Error* PLUGIN_Profiler_Create(
PLUGIN_Profiler_Create_Args* args) {
VLOG(1) << "Creating plugin profiler";
auto profiler = std::make_unique<PLUGIN_Profiler>();
profiler->stopped = true;
tensorflow::ProfileOptions options;
options.ParseFromArray(args->options, args->options_size);
profiler->impl = std::make_unique<tsl::profiler::ProfilerCollection>(
tsl::profiler::CreateProfilers(options));
args->profiler = profiler.release();
return nullptr;
}
PLUGIN_Profiler_Error* PLUGIN_Profiler_Destroy(
PLUGIN_Profiler_Destroy_Args* args) {
VLOG(1) << "Destroying plugin profiler";
if (args->profiler != nullptr) {
delete args->profiler;
}
return nullptr;
}
PLUGIN_Profiler_Error* PLUGIN_Profiler_Start(PLUGIN_Profiler_Start_Args* args) {
VLOG(1) << "Starting profiler";
if (!args->profiler->stopped) {
VLOG(1) << "Profiler is already started";
return nullptr;
}
args->profiler->byte_size = 0;
PLUGIN_PROFILER_RETURN_IF_ERROR(args->profiler->impl->Start());
args->profiler->stopped = false;
return nullptr;
}
PLUGIN_Profiler_Error* PLUGIN_Profiler_Stop(PLUGIN_Profiler_Stop_Args* args) {
VLOG(1) << "Stopping profiler";
if (args->profiler->stopped) {
VLOG(1) << "Profiler is already stopped";
return nullptr;
}
PLUGIN_PROFILER_RETURN_IF_ERROR(args->profiler->impl->Stop());
args->profiler->stopped = false;
return nullptr;
}
PLUGIN_Profiler_Error* PLUGIN_Profiler_CollectData(
PLUGIN_Profiler_CollectData_Args* args) {
VLOG(1) << "Collecting data from profiler";
tensorflow::profiler::XSpace space;
if (!args->profiler->space) {
VLOG(1) << "TpuProfiler CollectData";
PLUGIN_PROFILER_RETURN_IF_ERROR(args->profiler->impl->CollectData(&space));
args->profiler->byte_size = space.ByteSizeLong();
VLOG(2) << "TpuProfiler CollectData: Number of XPlanes: "
<< space.planes_size();
}
const size_t profiler_data_size = space.ByteSizeLong();
if (args->buffer == nullptr) {
args->profiler->buffer =
std::make_unique<std::vector<uint8_t>>(profiler_data_size + 1);
space.SerializeToArray(args->profiler->buffer->data(), profiler_data_size);
args->buffer_size_in_bytes = args->profiler->buffer->size();
args->buffer = args->profiler->buffer->data();
return nullptr;
}
return nullptr;
}
}
} | #include "xla/backends/profiler/plugin/plugin_tracer_impl.h"
#include <cstdint>
#include <memory>
#include <optional>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "absl/status/status.h"
#include "xla/backends/profiler/plugin/plugin_tracer.h"
#include "xla/backends/profiler/plugin/profiler_c_api.h"
#include "xla/backends/profiler/plugin/profiler_error.h"
#include "tsl/platform/logging.h"
#include "tsl/profiler/lib/profiler_factory.h"
#include "tsl/profiler/lib/profiler_interface.h"
#include "tsl/profiler/protobuf/profiler_options.pb.h"
#include "tsl/profiler/protobuf/xplane.pb.h"
#include "tsl/profiler/utils/xplane_builder.h"
#include "tsl/profiler/utils/xplane_visitor.h"
namespace xla {
namespace profiler {
using tensorflow::ProfileOptions;
using tsl::profiler::ProfilerInterface;
using tsl::profiler::XPlaneBuilder;
class PluginTracerImpl : public ProfilerInterface {
public:
explicit PluginTracerImpl(const ProfileOptions& options)
: options_(options) {}
absl::Status Start() override {
LOG(INFO) << "Starting Tracer";
return absl::OkStatus();
}
absl::Status Stop() override {
LOG(INFO) << "Stopping Tracer";
return absl::OkStatus();
}
absl::Status CollectData(tensorflow::profiler::XSpace* space) override {
LOG(INFO) << "Collecting data";
tensorflow::profiler::XPlane* plane = space->add_planes();
XPlaneBuilder builder(plane);
builder.SetName("GpuBackendTracer");
tensorflow::profiler::XStatMetadata* metadata =
builder.GetOrCreateStatMetadata((int64_t)0);
metadata->set_name("ProfileOptions");
builder.AddStatValue(*metadata, options_.SerializeAsString());
return absl::OkStatus();
}
private:
ProfileOptions options_;
};
std::unique_ptr<ProfilerInterface> CreatePluginTracer(
const ProfileOptions& options) {
return std::make_unique<PluginTracerImpl>(options);
}
static auto register_test_tracer = [] {
RegisterProfilerFactory(&CreatePluginTracer);
return 0;
}();
TEST(PluginTracerTest, TestPluginWithPluginTracer) {
PLUGIN_Profiler_Api api;
api.create = &PLUGIN_Profiler_Create;
api.start = &PLUGIN_Profiler_Start;
api.stop = &PLUGIN_Profiler_Stop;
api.collect_data = &PLUGIN_Profiler_CollectData;
api.destroy = &PLUGIN_Profiler_Destroy;
api.error_destroy = &PLUGIN_Profiler_Error_Destroy;
api.error_message = &PLUGIN_Profiler_Error_Message;
api.error_get_code = &PLUGIN_Profiler_Error_GetCode;
api.struct_size = PLUGIN_Profiler_Api_STRUCT_SIZE;
ProfileOptions options;
options.set_repository_path("TestRepositoryPath");
options.set_device_tracer_level(2);
PluginTracer tracer(&api, options);
tensorflow::profiler::XSpace xspace;
EXPECT_TRUE(tracer.Start().ok());
EXPECT_TRUE(tracer.Stop().ok());
EXPECT_TRUE(tracer.CollectData(&xspace).ok());
ASSERT_THAT(xspace.planes(), testing::SizeIs(1));
ASSERT_THAT(xspace.planes(0).stats(), testing::SizeIs(1));
tsl::profiler::XPlaneVisitor visitor(&xspace.planes(0));
std::optional<tsl::profiler::XStatVisitor> stat =
visitor.GetStat(0, *visitor.GetStatMetadata(0));
ASSERT_TRUE(stat.has_value());
EXPECT_EQ(stat->Name(), "ProfileOptions");
EXPECT_EQ(stat->StrOrRefValue(), options.SerializeAsString());
}
}
} | 2,200 |
#ifndef XLA_BACKENDS_PROFILER_GPU_CUPTI_ERROR_MANAGER_H_
#define XLA_BACKENDS_PROFILER_GPU_CUPTI_ERROR_MANAGER_H_
#include <stddef.h>
#include <stdint.h>
#include <atomic>
#include <functional>
#include <memory>
#include <string>
#include <vector>
#include "xla/backends/profiler/gpu/cupti_interface.h"
#include "tsl/platform/mutex.h"
#include "tsl/platform/thread_annotations.h"
namespace xla {
namespace profiler {
class CuptiErrorManager : public xla::profiler::CuptiInterface {
public:
explicit CuptiErrorManager(std::unique_ptr<CuptiInterface> interface);
bool Disabled() const override { return disabled_.load(); }
CUptiResult ActivityDisable(CUpti_ActivityKind kind) override;
CUptiResult ActivityEnable(CUpti_ActivityKind kind) override;
CUptiResult ActivityFlushAll(uint32_t flag) override;
CUptiResult ActivityGetNextRecord(uint8_t* buffer,
size_t valid_buffer_size_bytes,
CUpti_Activity** record) override;
CUptiResult ActivityGetNumDroppedRecords(CUcontext context,
uint32_t stream_id,
size_t* dropped) override;
CUptiResult ActivityConfigureUnifiedMemoryCounter(
CUpti_ActivityUnifiedMemoryCounterConfig* config,
uint32_t count) override;
CUptiResult ActivityRegisterCallbacks(
CUpti_BuffersCallbackRequestFunc func_buffer_requested,
CUpti_BuffersCallbackCompleteFunc func_buffer_completed) override;
CUptiResult ActivityUsePerThreadBuffer() override;
CUptiResult GetDeviceId(CUcontext context, uint32_t* device_id) override;
CUptiResult GetTimestamp(uint64_t* timestamp) override;
CUptiResult Finalize() override;
CUptiResult EnableCallback(uint32_t enable, CUpti_SubscriberHandle subscriber,
CUpti_CallbackDomain domain,
CUpti_CallbackId callback_id) override;
CUptiResult EnableDomain(uint32_t enable, CUpti_SubscriberHandle subscriber,
CUpti_CallbackDomain domain) override;
CUptiResult Subscribe(CUpti_SubscriberHandle* subscriber,
CUpti_CallbackFunc callback, void* userdata) override;
CUptiResult Unsubscribe(CUpti_SubscriberHandle subscriber) override;
CUptiResult GetResultString(CUptiResult result, const char** str) override;
CUptiResult GetContextId(CUcontext context, uint32_t* context_id) override;
CUptiResult GetStreamIdEx(CUcontext context, CUstream stream,
uint8_t per_thread_stream,
uint32_t* stream_id) override;
void CleanUp() override;
private:
typedef std::function<CUptiResult()> UndoFunction;
void RegisterUndoFunction(const UndoFunction& func);
void UndoAndDisable();
std::string ResultString(CUptiResult result) const;
std::unique_ptr<CuptiInterface> interface_;
std::vector<UndoFunction> undo_stack_ TF_GUARDED_BY(undo_stack_mu_);
tsl::mutex undo_stack_mu_;
std::atomic<int> disabled_;
bool undo_disabled_;
CuptiErrorManager(const CuptiErrorManager&) = delete;
void operator=(const CuptiErrorManager&) = delete;
};
}
}
#endif
#include "xla/backends/profiler/gpu/cupti_error_manager.h"
#include <utility>
#include "absl/debugging/leak_check.h"
#include "tsl/platform/logging.h"
namespace xla {
namespace profiler {
using tsl::mutex_lock;
CuptiErrorManager::CuptiErrorManager(std::unique_ptr<CuptiInterface> interface)
: interface_(std::move(interface)), disabled_(0), undo_disabled_(false) {}
#define IGNORE_CALL_IF_DISABLED \
if (disabled_) { \
LOG(ERROR) << "cupti" << __func__ << ": ignored due to a previous error."; \
return CUPTI_ERROR_DISABLED; \
} \
VLOG(1) << "cupti" << __func__;
#define ALLOW_ERROR(e, ERROR) \
if (e == ERROR) { \
VLOG(1) << "cupti" << __func__ << ": error " << static_cast<int>(e) \
<< ": " << ResultString(e) << " (allowed)"; \
return e; \
}
#define LOG_AND_DISABLE_IF_ERROR(e) \
if (e != CUPTI_SUCCESS) { \
LOG(ERROR) << "cupti" << __func__ << ": error " << static_cast<int>(e) \
<< ": " << ResultString(e); \
UndoAndDisable(); \
}
void CuptiErrorManager::RegisterUndoFunction(
const CuptiErrorManager::UndoFunction& func) {
mutex_lock lock(undo_stack_mu_);
undo_stack_.push_back(func);
}
CUptiResult CuptiErrorManager::ActivityDisable(CUpti_ActivityKind kind) {
IGNORE_CALL_IF_DISABLED;
CUptiResult error = interface_->ActivityDisable(kind);
LOG_AND_DISABLE_IF_ERROR(error);
return error;
}
CUptiResult CuptiErrorManager::ActivityEnable(CUpti_ActivityKind kind) {
IGNORE_CALL_IF_DISABLED;
CUptiResult error = interface_->ActivityEnable(kind);
if (error == CUPTI_SUCCESS) {
auto f = std::bind(&CuptiErrorManager::ActivityDisable, this, kind);
RegisterUndoFunction(f);
}
LOG_AND_DISABLE_IF_ERROR(error);
return error;
}
CUptiResult CuptiErrorManager::ActivityFlushAll(uint32_t flag) {
CUptiResult error = interface_->ActivityFlushAll(flag);
LOG_AND_DISABLE_IF_ERROR(error);
return error;
}
CUptiResult CuptiErrorManager::ActivityGetNextRecord(
uint8_t* buffer, size_t valid_buffer_size_bytes, CUpti_Activity** record) {
IGNORE_CALL_IF_DISABLED;
CUptiResult error = interface_->ActivityGetNextRecord(
buffer, valid_buffer_size_bytes, record);
ALLOW_ERROR(error, CUPTI_ERROR_MAX_LIMIT_REACHED);
LOG_AND_DISABLE_IF_ERROR(error);
return error;
}
CUptiResult CuptiErrorManager::ActivityGetNumDroppedRecords(CUcontext context,
uint32_t stream_id,
size_t* dropped) {
IGNORE_CALL_IF_DISABLED;
CUptiResult error =
interface_->ActivityGetNumDroppedRecords(context, stream_id, dropped);
LOG_AND_DISABLE_IF_ERROR(error);
return error;
}
CUptiResult CuptiErrorManager::ActivityConfigureUnifiedMemoryCounter(
CUpti_ActivityUnifiedMemoryCounterConfig* config, uint32_t count) {
IGNORE_CALL_IF_DISABLED;
CUptiResult error =
interface_->ActivityConfigureUnifiedMemoryCounter(config, count);
return error;
}
CUptiResult CuptiErrorManager::ActivityRegisterCallbacks(
CUpti_BuffersCallbackRequestFunc func_buffer_requested,
CUpti_BuffersCallbackCompleteFunc func_buffer_completed) {
IGNORE_CALL_IF_DISABLED;
absl::LeakCheckDisabler disabler;
CUptiResult error = interface_->ActivityRegisterCallbacks(
func_buffer_requested, func_buffer_completed);
LOG_AND_DISABLE_IF_ERROR(error);
return error;
}
CUptiResult CuptiErrorManager::ActivityUsePerThreadBuffer() {
IGNORE_CALL_IF_DISABLED;
CUptiResult error = interface_->ActivityUsePerThreadBuffer();
return error;
}
CUptiResult CuptiErrorManager::GetDeviceId(CUcontext context,
uint32_t* device_id) {
IGNORE_CALL_IF_DISABLED;
CUptiResult error = interface_->GetDeviceId(context, device_id);
LOG_AND_DISABLE_IF_ERROR(error);
return error;
}
CUptiResult CuptiErrorManager::GetTimestamp(uint64_t* timestamp) {
IGNORE_CALL_IF_DISABLED;
CUptiResult error = interface_->GetTimestamp(timestamp);
LOG_AND_DISABLE_IF_ERROR(error);
return error;
}
CUptiResult CuptiErrorManager::Finalize() {
IGNORE_CALL_IF_DISABLED;
CUptiResult error = interface_->Finalize();
ALLOW_ERROR(error, CUPTI_ERROR_API_NOT_IMPLEMENTED);
LOG_AND_DISABLE_IF_ERROR(error);
return error;
}
CUptiResult CuptiErrorManager::EnableCallback(uint32_t enable,
CUpti_SubscriberHandle subscriber,
CUpti_CallbackDomain domain,
CUpti_CallbackId callback_id) {
IGNORE_CALL_IF_DISABLED;
CUptiResult error =
interface_->EnableCallback(enable, subscriber, domain, callback_id);
if (error == CUPTI_SUCCESS) {
if (enable == 1) {
auto f = std::bind(&CuptiErrorManager::EnableCallback, this,
0 , subscriber, domain, callback_id);
RegisterUndoFunction(f);
}
}
LOG_AND_DISABLE_IF_ERROR(error);
return error;
}
CUptiResult CuptiErrorManager::EnableDomain(uint32_t enable,
CUpti_SubscriberHandle subscriber,
CUpti_CallbackDomain domain) {
IGNORE_CALL_IF_DISABLED;
CUptiResult error = interface_->EnableDomain(enable, subscriber, domain);
if (error == CUPTI_SUCCESS) {
if (enable == 1) {
auto f = std::bind(&CuptiErrorManager::EnableDomain, this,
0 , subscriber, domain);
RegisterUndoFunction(f);
}
}
LOG_AND_DISABLE_IF_ERROR(error);
return error;
}
CUptiResult CuptiErrorManager::Subscribe(CUpti_SubscriberHandle* subscriber,
CUpti_CallbackFunc callback,
void* userdata) {
IGNORE_CALL_IF_DISABLED;
absl::LeakCheckDisabler disabler;
CUptiResult error = interface_->Subscribe(subscriber, callback, userdata);
if (error == CUPTI_SUCCESS) {
auto f = std::bind(&CuptiErrorManager::Unsubscribe, this, *subscriber);
RegisterUndoFunction(f);
}
LOG_AND_DISABLE_IF_ERROR(error);
return error;
}
CUptiResult CuptiErrorManager::Unsubscribe(CUpti_SubscriberHandle subscriber) {
IGNORE_CALL_IF_DISABLED;
CUptiResult error = interface_->Unsubscribe(subscriber);
LOG_AND_DISABLE_IF_ERROR(error);
return error;
}
void CuptiErrorManager::UndoAndDisable() {
if (undo_disabled_) {
return;
}
mutex_lock lock(undo_stack_mu_);
undo_disabled_ = true;
while (!undo_stack_.empty()) {
LOG(ERROR) << "CuptiErrorManager is disabling profiling automatically.";
undo_stack_.back()();
undo_stack_.pop_back();
}
undo_disabled_ = false;
disabled_ = 1;
}
CUptiResult CuptiErrorManager::GetResultString(CUptiResult result,
const char** str) {
IGNORE_CALL_IF_DISABLED;
CUptiResult error = interface_->GetResultString(result, str);
LOG_AND_DISABLE_IF_ERROR(error);
return error;
}
CUptiResult CuptiErrorManager::GetContextId(CUcontext context,
uint32_t* context_id) {
IGNORE_CALL_IF_DISABLED;
CUptiResult error = interface_->GetContextId(context, context_id);
LOG_AND_DISABLE_IF_ERROR(error);
return error;
}
CUptiResult CuptiErrorManager::GetStreamIdEx(CUcontext context, CUstream stream,
uint8_t per_thread_stream,
uint32_t* stream_id) {
IGNORE_CALL_IF_DISABLED;
CUptiResult error =
interface_->GetStreamIdEx(context, stream, per_thread_stream, stream_id);
LOG_AND_DISABLE_IF_ERROR(error);
return error;
}
void CuptiErrorManager::CleanUp() {
if (undo_disabled_) {
return;
}
mutex_lock lock(undo_stack_mu_);
undo_disabled_ = true;
while (!undo_stack_.empty()) {
undo_stack_.pop_back();
}
undo_disabled_ = false;
}
std::string CuptiErrorManager::ResultString(CUptiResult error) const {
const char* error_message = nullptr;
if (interface_->GetResultString(error, &error_message) == CUPTI_SUCCESS &&
error_message != nullptr) {
return error_message;
}
return "";
}
}
} | #if GOOGLE_CUDA
#include "xla/backends/profiler/gpu/cupti_error_manager.h"
#include <cstdint>
#include <memory>
#include <utility>
#include "absl/memory/memory.h"
#include "xla/backends/profiler/gpu/cuda_test.h"
#include "xla/backends/profiler/gpu/cupti_interface.h"
#include "xla/backends/profiler/gpu/cupti_tracer.h"
#include "xla/backends/profiler/gpu/cupti_wrapper.h"
#include "xla/backends/profiler/gpu/mock_cupti.h"
#include "tsl/platform/test.h"
#include "tsl/profiler/utils/time_utils.h"
namespace xla {
namespace profiler {
namespace test {
using xla::profiler::CuptiInterface;
using xla::profiler::CuptiTracer;
using xla::profiler::CuptiTracerCollectorOptions;
using xla::profiler::CuptiTracerOptions;
using xla::profiler::CuptiWrapper;
using ::testing::_;
using ::testing::Invoke;
using ::testing::Return;
using ::testing::Sequence;
using ::testing::StrictMock;
class TestableCuptiTracer : public CuptiTracer {
public:
explicit TestableCuptiTracer(CuptiInterface* cupti_interface)
: CuptiTracer(cupti_interface) {}
};
class CuptiErrorManagerTest : public ::testing::Test {
protected:
CuptiErrorManagerTest() {}
void SetUp() override {
ASSERT_GT(CuptiTracer::NumGpus(), 0) << "No devices found";
auto mock_cupti = std::make_unique<StrictMock<MockCupti>>();
mock_ = mock_cupti.get();
cupti_error_manager_ =
std::make_unique<CuptiErrorManager>(std::move(mock_cupti));
cupti_tracer_ =
std::make_unique<TestableCuptiTracer>(cupti_error_manager_.get());
cupti_wrapper_ = std::make_unique<CuptiWrapper>();
CuptiTracerCollectorOptions collector_options;
collector_options.num_gpus = CuptiTracer::NumGpus();
uint64_t start_gputime_ns = CuptiTracer::GetTimestamp();
uint64_t start_walltime_ns = tsl::profiler::GetCurrentTimeNanos();
cupti_collector_ = CreateCuptiCollector(
collector_options, start_walltime_ns, start_gputime_ns);
}
void EnableProfiling(const CuptiTracerOptions& option) {
cupti_tracer_->Enable(option, cupti_collector_.get());
}
void DisableProfiling() { cupti_tracer_->Disable(); }
bool CuptiDisabled() const { return cupti_error_manager_->Disabled(); }
void RunGpuApp() {
MemCopyH2D();
PrintfKernel(10);
Synchronize();
MemCopyD2H();
}
StrictMock<MockCupti>* mock_;
std::unique_ptr<TestableCuptiTracer> cupti_tracer_ = nullptr;
std::unique_ptr<CuptiInterface> cupti_error_manager_;
std::unique_ptr<CuptiWrapper> cupti_wrapper_;
std::unique_ptr<xla::profiler::CuptiTraceCollector> cupti_collector_;
};
TEST_F(CuptiErrorManagerTest, GpuTraceActivityEnableTest) {
Sequence s1;
EXPECT_CALL(*mock_, Subscribe(_, _, _))
.InSequence(s1)
.WillOnce(Invoke(cupti_wrapper_.get(), &CuptiWrapper::Subscribe));
EXPECT_CALL(*mock_, EnableCallback(1, _, _, _))
.InSequence(s1)
.WillOnce(Invoke(cupti_wrapper_.get(), &CuptiWrapper::EnableCallback));
EXPECT_CALL(*mock_, ActivityUsePerThreadBuffer())
.InSequence(s1)
.WillOnce(Invoke(cupti_wrapper_.get(),
&CuptiWrapper::ActivityUsePerThreadBuffer));
EXPECT_CALL(*mock_, ActivityRegisterCallbacks(_, _))
.InSequence(s1)
.WillOnce(Invoke(cupti_wrapper_.get(),
&CuptiWrapper::ActivityRegisterCallbacks));
EXPECT_CALL(*mock_, ActivityEnable(CUPTI_ACTIVITY_KIND_KERNEL))
.InSequence(s1)
.WillOnce(Return(CUPTI_ERROR_UNKNOWN));
EXPECT_CALL(*mock_, GetResultString(CUPTI_ERROR_UNKNOWN, _))
.InSequence(s1)
.WillOnce(Invoke(cupti_wrapper_.get(), &CuptiWrapper::GetResultString));
EXPECT_CALL(*mock_, EnableCallback(0, _, _, _))
.InSequence(s1)
.WillOnce(Invoke(cupti_wrapper_.get(), &CuptiWrapper::EnableCallback));
EXPECT_CALL(*mock_, Unsubscribe(_))
.InSequence(s1)
.WillOnce(Invoke(cupti_wrapper_.get(), &CuptiWrapper::Unsubscribe));
EXPECT_FALSE(CuptiDisabled());
CuptiTracerOptions options;
options.activities_selected.push_back(CUPTI_ACTIVITY_KIND_KERNEL);
options.cbids_selected.push_back(CUPTI_DRIVER_TRACE_CBID_cuLaunchKernel);
EnableProfiling(options);
EXPECT_TRUE(CuptiDisabled());
RunGpuApp();
EXPECT_TRUE(CuptiDisabled());
DisableProfiling();
EXPECT_TRUE(CuptiDisabled());
}
TEST_F(CuptiErrorManagerTest, GpuTraceAutoEnableTest) {
EXPECT_FALSE(CuptiDisabled());
Sequence s1;
EXPECT_CALL(*mock_, Subscribe(_, _, _))
.InSequence(s1)
.WillOnce(Invoke(cupti_wrapper_.get(), &CuptiWrapper::Subscribe));
EXPECT_CALL(*mock_, EnableDomain(1, _, _))
.InSequence(s1)
.WillOnce(Invoke(cupti_wrapper_.get(), &CuptiWrapper::EnableDomain));
EXPECT_CALL(*mock_, ActivityUsePerThreadBuffer())
.InSequence(s1)
.WillOnce(Invoke(cupti_wrapper_.get(),
&CuptiWrapper::ActivityUsePerThreadBuffer));
EXPECT_CALL(*mock_, ActivityRegisterCallbacks(_, _))
.InSequence(s1)
.WillOnce(Invoke(cupti_wrapper_.get(),
&CuptiWrapper::ActivityRegisterCallbacks));
EXPECT_CALL(*mock_, ActivityEnable(CUPTI_ACTIVITY_KIND_MEMCPY))
.InSequence(s1)
.WillOnce(Invoke(cupti_wrapper_.get(), &CuptiWrapper::ActivityEnable));
EXPECT_CALL(*mock_, ActivityEnable(CUPTI_ACTIVITY_KIND_MEMCPY2))
.InSequence(s1)
.WillOnce(Return(CUPTI_ERROR_UNKNOWN));
EXPECT_CALL(*mock_, GetResultString(CUPTI_ERROR_UNKNOWN, _))
.InSequence(s1)
.WillOnce(Invoke(cupti_wrapper_.get(), &CuptiWrapper::GetResultString));
EXPECT_CALL(*mock_, ActivityDisable(CUPTI_ACTIVITY_KIND_MEMCPY))
.InSequence(s1)
.WillOnce(Invoke(cupti_wrapper_.get(), &CuptiWrapper::ActivityDisable));
EXPECT_CALL(*mock_, EnableDomain(0, _, _))
.InSequence(s1)
.WillOnce(Invoke(cupti_wrapper_.get(), &CuptiWrapper::EnableDomain));
EXPECT_CALL(*mock_, Unsubscribe(_))
.InSequence(s1)
.WillOnce(Invoke(cupti_wrapper_.get(), &CuptiWrapper::Unsubscribe));
EXPECT_FALSE(CuptiDisabled());
CuptiTracerOptions options;
options.activities_selected.push_back(CUPTI_ACTIVITY_KIND_MEMCPY);
options.activities_selected.push_back(CUPTI_ACTIVITY_KIND_MEMCPY2);
options.activities_selected.push_back(CUPTI_ACTIVITY_KIND_KERNEL);
EnableProfiling(options);
EXPECT_TRUE(CuptiDisabled());
RunGpuApp();
EXPECT_TRUE(CuptiDisabled());
DisableProfiling();
EXPECT_TRUE(CuptiDisabled());
}
}
}
}
#endif | 2,201 |
#ifndef XLA_PJRT_SEMAPHORE_H_
#define XLA_PJRT_SEMAPHORE_H_
#include "absl/synchronization/mutex.h"
#include "xla/types.h"
namespace xla {
class Semaphore {
public:
explicit Semaphore(int64_t capacity);
void Acquire(int64_t amount);
void Release(int64_t amount);
class ScopedReservation {
public:
ScopedReservation(Semaphore* semaphore, int64_t amount)
: semaphore_(semaphore), amount_(amount) {}
~ScopedReservation();
ScopedReservation(const ScopedReservation&) = delete;
ScopedReservation(ScopedReservation&& other) noexcept;
ScopedReservation& operator=(const ScopedReservation&) = delete;
ScopedReservation& operator=(ScopedReservation&& other) noexcept;
int64_t amount() const { return amount_; }
private:
Semaphore* semaphore_;
int64_t amount_;
};
ScopedReservation ScopedAcquire(int64_t amount);
private:
struct CanAcquireArgs {
Semaphore* semaphore;
int64_t amount;
};
static bool CanAcquire(CanAcquireArgs* args)
ABSL_EXCLUSIVE_LOCKS_REQUIRED(args->semaphore->mu_);
absl::Mutex mu_;
int64_t value_ ABSL_GUARDED_BY(mu_);
};
}
#endif
#include "xla/pjrt/semaphore.h"
#include "tsl/platform/logging.h"
namespace xla {
Semaphore::Semaphore(int64_t capacity) : value_(capacity) {
CHECK_GE(capacity, 0);
}
bool Semaphore::CanAcquire(CanAcquireArgs* args) {
return args->semaphore->value_ >= args->amount;
}
void Semaphore::Acquire(int64_t amount) {
CHECK_GE(amount, 0);
CanAcquireArgs args;
args.semaphore = this;
args.amount = amount;
mu_.LockWhen(absl::Condition(&CanAcquire, &args));
value_ -= amount;
mu_.Unlock();
}
void Semaphore::Release(int64_t amount) {
CHECK_GE(amount, 0);
absl::MutexLock lock(&mu_);
value_ += amount;
}
Semaphore::ScopedReservation::~ScopedReservation() {
if (semaphore_) {
semaphore_->Release(amount_);
}
}
Semaphore::ScopedReservation::ScopedReservation(
ScopedReservation&& other) noexcept {
semaphore_ = other.semaphore_;
amount_ = other.amount_;
other.semaphore_ = nullptr;
}
Semaphore::ScopedReservation& Semaphore::ScopedReservation::operator=(
ScopedReservation&& other) noexcept {
semaphore_ = other.semaphore_;
amount_ = other.amount_;
other.semaphore_ = nullptr;
return *this;
}
Semaphore::ScopedReservation Semaphore::ScopedAcquire(int64_t amount) {
Acquire(amount);
return ScopedReservation(this, amount);
}
} | #include "xla/pjrt/semaphore.h"
#include "absl/synchronization/notification.h"
#include "xla/test.h"
#include "tsl/platform/env.h"
#include "tsl/platform/threadpool.h"
namespace xla {
namespace {
TEST(SemaphoreTest, UnthreadedTests) {
Semaphore semaphore(2);
semaphore.Acquire(1);
semaphore.Release(1);
semaphore.Acquire(2);
semaphore.Release(2);
semaphore.Acquire(1);
semaphore.Acquire(1);
semaphore.Release(1);
semaphore.Acquire(1);
semaphore.Release(1);
semaphore.Acquire(1);
semaphore.Release(2);
{
auto a = semaphore.ScopedAcquire(1);
EXPECT_EQ(a.amount(), 1);
{ auto b = semaphore.ScopedAcquire(1); }
{ auto c = semaphore.ScopedAcquire(1); }
}
{
auto d = semaphore.ScopedAcquire(2);
EXPECT_EQ(d.amount(), 2);
}
}
TEST(SemaphoreTest, ConcurrentTest) {
tsl::thread::ThreadPool pool(tsl::Env::Default(), "test", 2);
Semaphore semaphore(2);
semaphore.Acquire(1);
absl::Notification a_done;
pool.Schedule([&]() {
semaphore.Acquire(2);
semaphore.Release(2);
a_done.Notify();
});
absl::Notification b_done;
pool.Schedule([&]() {
semaphore.Acquire(1);
semaphore.Release(1);
b_done.Notify();
});
b_done.WaitForNotification();
EXPECT_FALSE(a_done.HasBeenNotified());
semaphore.Release(1);
a_done.WaitForNotification();
}
}
} | 2,202 |
#ifndef XLA_PJRT_MLIR_TO_HLO_H_
#define XLA_PJRT_MLIR_TO_HLO_H_
#include "absl/status/status.h"
#include "absl/strings/string_view.h"
#include "mlir/IR/BuiltinOps.h"
#include "xla/client/xla_computation.h"
namespace xla {
absl::StatusOr<mlir::OwningOpRef<mlir::ModuleOp>> ParseMlirModuleString(
absl::string_view mlir_module_str, mlir::MLIRContext& context);
absl::Status MlirToXlaComputation(mlir::ModuleOp module,
XlaComputation& xla_computation,
bool use_tuple_args, bool return_tuple);
absl::Status ParseMlirModuleStringAndConvertToXlaComputation(
absl::string_view mlir_module_str, XlaComputation& xla_computation,
bool use_tuple_args, bool return_tuple);
std::string GetDefaultStablehloVersion();
absl::StatusOr<std::string> Serialize(mlir::ModuleOp mlir_module,
std::optional<int64_t> plugin_version,
absl::string_view target,
bool inplace = false);
absl::StatusOr<std::string> SerializeUsingVersionedStablehlo(
mlir::ModuleOp mlir_module, absl::string_view target, bool inplace = false);
absl::Status UpgradeVersionedStablehlo(mlir::ModuleOp mlir_module);
}
#endif
#include "xla/pjrt/mlir_to_hlo.h"
#include <cstdint>
#include <memory>
#include <optional>
#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 "llvm/ADT/STLFunctionalExtras.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/TypeSwitch.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/raw_ostream.h"
#include "mlir/Bytecode/BytecodeWriter.h"
#include "mlir/Conversion/ReconcileUnrealizedCasts/ReconcileUnrealizedCasts.h"
#include "mlir/Dialect/Arith/IR/Arith.h"
#include "mlir/Dialect/Func/Extensions/AllExtensions.h"
#include "mlir/Dialect/Func/IR/FuncOps.h"
#include "mlir/Dialect/MLProgram/IR/MLProgram.h"
#include "mlir/IR/Attributes.h"
#include "mlir/IR/Builders.h"
#include "mlir/IR/BuiltinAttributes.h"
#include "mlir/IR/BuiltinOps.h"
#include "mlir/IR/BuiltinTypes.h"
#include "mlir/IR/MLIRContext.h"
#include "mlir/IR/OwningOpRef.h"
#include "mlir/IR/Visitors.h"
#include "mlir/Parser/Parser.h"
#include "mlir/Pass/PassManager.h"
#include "mlir/Support/LLVM.h"
#include "mlir/Support/LogicalResult.h"
#include "mlir/Transforms/Passes.h"
#include "stablehlo/dialect/ChloOps.h"
#include "stablehlo/dialect/Register.h"
#include "stablehlo/dialect/Serialization.h"
#include "stablehlo/dialect/StablehloOps.h"
#include "stablehlo/transforms/Passes.h"
#include "xla/debug_options_flags.h"
#include "xla/mlir/utils/error_util.h"
#include "xla/mlir_hlo/mhlo/IR/register.h"
#include "xla/mlir_hlo/mhlo/transforms/passes.h"
#include "xla/service/spmd/shardonnay/constants.h"
#include "xla/service/spmd/shardonnay/utils.h"
#include "xla/translate/mhlo_to_hlo/mlir_hlo_to_hlo.h"
#include "xla/util.h"
#include "tsl/platform/statusor.h"
namespace xla {
namespace {
static mlir::Attribute ArrayToElements(mlir::Attribute attr) {
if (auto array = mlir::dyn_cast<mlir::DenseI64ArrayAttr>(attr)) {
return mlir::DenseIntElementsAttr::get(
mlir::RankedTensorType::get(array.size(), array.getElementType()),
array.asArrayRef());
}
if (auto array = mlir::dyn_cast<mlir::DenseBoolArrayAttr>(attr)) {
return mlir::DenseIntElementsAttr::get(
mlir::RankedTensorType::get(array.size(), array.getElementType()),
array.asArrayRef());
}
return attr;
}
static mlir::Attribute ElementsToArray(mlir::Attribute attr) {
if (auto elements = llvm::dyn_cast<mlir::DenseIntElementsAttr>(attr)) {
if (elements.getElementType().isInteger(64)) {
return mlir::DenseI64ArrayAttr::get(
attr.getContext(), llvm::to_vector(elements.getValues<int64_t>()));
}
return mlir::DenseBoolArrayAttr::get(
attr.getContext(), llvm::to_vector(elements.getValues<bool>()));
}
return attr;
}
static void ConvertAttr(
mlir::Operation* op, llvm::StringRef attr_name,
llvm::function_ref<mlir::Attribute(mlir::Attribute)> convert) {
if (auto attr = op->getAttr(attr_name)) {
op->setAttr(attr_name, convert(attr));
}
}
void ConvertStablehloDenseAttributes(
mlir::Operation* root_op,
llvm::function_ref<mlir::Attribute(mlir::Attribute)> convert,
std::optional<int64_t> plugin_version) {
llvm::TypeSwitch<mlir::Operation*>(root_op)
.Case([&](mlir::stablehlo::BroadcastInDimOp op) {
ConvertAttr(op, "broadcast_dimensions", convert);
})
.Case([&](mlir::stablehlo::ConvolutionOp op) {
ConvertAttr(op, "window_strides", convert);
ConvertAttr(op, "lhs_dilation", convert);
ConvertAttr(op, "rhs_dilation", convert);
ConvertAttr(op, "window_reversal", convert);
})
.Case([&](mlir::stablehlo::DynamicBroadcastInDimOp op) {
ConvertAttr(op, "broadcast_dimensions", convert);
ConvertAttr(op, "known_expanding_dimensions", convert);
ConvertAttr(op, "known_nonexpanding_dimensions", convert);
})
.Case([&](mlir::stablehlo::DynamicConvOp op) {
ConvertAttr(op, "window_strides", convert);
ConvertAttr(op, "lhs_dilation", convert);
ConvertAttr(op, "rhs_dilation", convert);
ConvertAttr(op, "window_reversal", convert);
})
.Case([&](mlir::stablehlo::GatherOp op) {
ConvertAttr(op, "slice_sizes", convert);
})
.Case([&](mlir::stablehlo::MapOp op) {
ConvertAttr(op, "dimensions", convert);
})
.Case([&](mlir::stablehlo::ReduceOp op) {
ConvertAttr(op, "dimensions", convert);
})
.Case([&](mlir::stablehlo::ReduceWindowOp op) {
ConvertAttr(op, "window_dimensions", convert);
ConvertAttr(op, "window_strides", convert);
ConvertAttr(op, "base_dilations", convert);
ConvertAttr(op, "window_dilations", convert);
})
.Case([&](mlir::stablehlo::SelectAndScatterOp op) {
ConvertAttr(op, "window_dimensions", convert);
ConvertAttr(op, "window_strides", convert);
});
if (!plugin_version.has_value() || plugin_version.value() < 40) {
llvm::TypeSwitch<mlir::Operation*>(root_op)
.Case([&](mlir::stablehlo::BroadcastOp op) {
ConvertAttr(op, "broadcast_sizes", convert);
})
.Case([&](mlir::stablehlo::DynamicSliceOp op) {
ConvertAttr(op, "slice_sizes", convert);
})
.Case([&](mlir::stablehlo::FftOp op) {
ConvertAttr(op, "fft_length", convert);
})
.Case([&](mlir::stablehlo::PadOp op) {
ConvertAttr(op, "edge_padding_low", convert);
ConvertAttr(op, "edge_padding_high", convert);
ConvertAttr(op, "interior_padding", convert);
})
.Case([&](mlir::stablehlo::ReverseOp op) {
ConvertAttr(op, "dimensions", convert);
})
.Case([&](mlir::stablehlo::SliceOp op) {
ConvertAttr(op, "start_indices", convert);
ConvertAttr(op, "limit_indices", convert);
ConvertAttr(op, "strides", convert);
})
.Case([&](mlir::stablehlo::TransposeOp op) {
ConvertAttr(op, "permutation", convert);
});
}
}
void DowngradeStablehlo(mlir::ModuleOp module,
std::optional<int64_t> plugin_version) {
module->walk([&](mlir::Operation* op) {
ConvertStablehloDenseAttributes(op, ArrayToElements, plugin_version);
});
}
void UpgradeStablehlo(mlir::ModuleOp module) {
module->walk([](mlir::Operation* op) {
ConvertStablehloDenseAttributes(op, ElementsToArray,
std::nullopt);
});
}
}
absl::Status MlirToXlaComputation(mlir::ModuleOp module,
XlaComputation& xla_computation,
bool use_tuple_args, bool return_tuple) {
mlir::MLIRContext* context = module->getContext();
mlir::BaseScopedDiagnosticHandler diagnostic_handler(context);
{
mlir::PassManager pm(context);
pm.addPass(mlir::mhlo::createStablehloLegalizeToHloPass());
pm.addNestedPass<mlir::func::FuncOp>(
mlir::mhlo::createChloLegalizeToHloPass());
pm.addNestedPass<mlir::func::FuncOp>(mlir::createCanonicalizerPass());
pm.addNestedPass<mlir::func::FuncOp>(
mlir::mhlo::createSinkConstantsToControlFlowPass());
if (failed(pm.run(module))) {
VLOG(1) << "MHLO->HLO lowering passes failed.";
module->dump();
return diagnostic_handler.ConsumeStatus();
}
VLOG(5) << "MHLO module after lowering, before HLO import ";
if (VLOG_IS_ON(5)) {
module->dump();
}
}
if (use_tuple_args && GetDebugOptionsFromFlags().xla_use_shardonnay()) {
sdy::addFrontendAttribute(module, sdy::kUseTupleArgs,
mlir::StringAttr::get(context, "t"));
use_tuple_args = false;
}
mlir::MlirToHloConversionOptions options;
options.use_tuple_args = use_tuple_args;
options.return_tuple = return_tuple;
TF_ASSIGN_OR_RETURN(std::unique_ptr<HloModule> hlo_module,
mlir::ConvertMlirHloToHloModule(module, options));
xla_computation = XlaComputation(hlo_module->ToProto());
return absl::OkStatus();
}
absl::StatusOr<mlir::OwningOpRef<mlir::ModuleOp>> ParseMlirModuleString(
absl::string_view mlir_module_str, mlir::MLIRContext& context) {
mlir::DialectRegistry registry;
registry.insert<mlir::arith::ArithDialect>();
registry.insert<mlir::func::FuncDialect>();
registry.insert<mlir::ml_program::MLProgramDialect>();
registry.insert<mlir::shape::ShapeDialect>();
mlir::func::registerAllExtensions(registry);
mlir::mhlo::registerAllMhloDialects(registry);
mlir::stablehlo::registerAllDialects(registry);
context.appendDialectRegistry(registry);
mlir::BaseScopedDiagnosticHandler diagnostic_handler(&context);
mlir::OwningOpRef<mlir::ModuleOp> module =
mlir::parseSourceString<mlir::ModuleOp>(
llvm::StringRef(mlir_module_str.data(), mlir_module_str.size()),
mlir::ParserConfig{&context, false});
if (!module) {
return diagnostic_handler.ConsumeStatus();
}
TF_RETURN_IF_ERROR(UpgradeVersionedStablehlo(*module));
if (failed(module->verifyInvariants())) {
VLOG(1) << "MLIR verification failed.";
module->dump();
return diagnostic_handler.ConsumeStatus();
}
return std::move(module);
}
absl::Status ParseMlirModuleStringAndConvertToXlaComputation(
absl::string_view mlir_module_str, XlaComputation& xla_computation,
bool use_tuple_args, bool return_tuple) {
mlir::MLIRContext context;
TF_ASSIGN_OR_RETURN(mlir::OwningOpRef<mlir::ModuleOp> module,
xla::ParseMlirModuleString(mlir_module_str, context));
return xla::MlirToXlaComputation(*module, xla_computation, use_tuple_args,
return_tuple);
}
absl::StatusOr<std::string> SerializeUsingNativeBytecode(
mlir::ModuleOp module, std::optional<int64_t> plugin_version) {
std::string bytecode;
llvm::raw_string_ostream os(bytecode);
mlir::BytecodeWriterConfig config;
config.setDesiredBytecodeVersion(1);
mlir::OwningOpRef<mlir::ModuleOp> cloned = module.clone();
DowngradeStablehlo(*cloned, plugin_version);
if (mlir::failed(mlir::writeBytecodeToFile(*cloned, os, config))) {
return absl::InvalidArgumentError("mlir::writeBytecodeToFile failed");
}
return bytecode;
}
absl::StatusOr<std::string> SerializeUsingVersionedStablehlo(
mlir::ModuleOp mlir_module, absl::string_view target, bool inplace) {
mlir::MLIRContext* context = mlir_module->getContext();
mlir::BaseScopedDiagnosticHandler diagnostic_handler(context);
mlir::PassManager pm(context);
pm.addNestedPass<mlir::func::FuncOp>(
mlir::mhlo::createChloLegalizeToHighLevelMhloPass());
pm.addNestedPass<mlir::func::FuncOp>(
mlir::stablehlo::createChloLegalizeToStablehloPass());
pm.addNestedPass<mlir::func::FuncOp>(
mlir::stablehlo::createShapeLegalizeToStablehloPass());
pm.addPass(mlir::createReconcileUnrealizedCastsPass());
pm.addPass(mlir::mhlo::createHloLegalizeToStablehloPass());
if (!mlir::succeeded(pm.run(mlir_module))) {
const absl::Status status = diagnostic_handler.ConsumeStatus();
return absl::InvalidArgumentError(
absl::StrCat("CHLO => [MHLO+Shape] => StableHLO failed;\n\nDetailed "
"error from MLIR: ",
status.message()));
}
mlir::OwningOpRef<mlir::ModuleOp> cloned;
if (!inplace) {
cloned = mlir_module.clone();
mlir_module = *cloned;
}
std::string buffer;
llvm::raw_string_ostream os(buffer);
if (failed(mlir::stablehlo::serializePortableArtifact(mlir_module, target,
os))) {
const absl::Status status = diagnostic_handler.ConsumeStatus();
return absl::InvalidArgumentError(absl::StrCat(
"Failed to serialize StableHLO;\n\nDetailed error from MLIR: ",
status.message()));
}
return buffer;
}
absl::Status UpgradeVersionedStablehlo(mlir::ModuleOp mlir_module) {
UpgradeStablehlo(mlir_module);
mlir::PassManager pm(mlir_module->getContext());
mlir::stablehlo::createStablehloDeserializePipeline(pm);
if (!mlir::succeeded(pm.run(mlir_module)))
return xla::InvalidArgument("Failed to upgrade versioned StableHLO.");
return absl::OkStatus();
}
std::string GetDefaultStablehloVersion() {
return "0.17.0";
}
absl::StatusOr<std::string> Serialize(mlir::ModuleOp module,
std::optional<int64_t> plugin_version,
absl::string_view target, bool inplace) {
bool all_stablehlo = true;
module->walk([&](mlir::Operation* op) {
if (!llvm::isa<mlir::ModuleOp>(op) &&
!llvm::isa<mlir::stablehlo::StablehloDialect, mlir::func::FuncDialect,
mlir::chlo::ChloDialect>(op->getDialect())) {
std::cout << op->getDialect()->getNamespace().str() << "\n";
all_stablehlo = false;
return mlir::WalkResult::interrupt();
}
return mlir::WalkResult::advance();
});
if (!all_stablehlo ||
(plugin_version.has_value() && plugin_version.value() < 47)) {
return SerializeUsingNativeBytecode(module, plugin_version);
}
return SerializeUsingVersionedStablehlo(module, target, inplace);
}
} | #include "xla/pjrt/mlir_to_hlo.h"
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "absl/status/status.h"
#include "absl/strings/str_cat.h"
#include "mlir/IR/MLIRContext.h"
#include "mlir/IR/OwningOpRef.h"
#include "xla/test.h"
#include "tsl/platform/statusor.h"
namespace xla {
namespace {
using ::testing::HasSubstr;
using ::testing::Not;
MATCHER_P(IsVhloArtifact, version, "") {
return ExplainMatchResult(HasSubstr(absl::StrCat("StableHLO_v", version)),
arg, result_listener);
}
TEST(MlirToHloTest, StablehloTest) {
constexpr char kProgram[] =
R"(
func.func @add(%arg0: tensor<1x2xf32>) -> tensor<1x2xf32> {
%cst = stablehlo.constant dense<1.0> : tensor<1x2xf32>
%0 = stablehlo.add %arg0, %cst : tensor<1x2xf32>
return %0 : tensor<1x2xf32>
}
)";
mlir::MLIRContext context;
TF_ASSERT_OK_AND_ASSIGN(mlir::OwningOpRef<mlir::ModuleOp> module,
ParseMlirModuleString(kProgram, context));
TF_ASSERT_OK_AND_ASSIGN(std::string blob, Serialize(*module, 47, "1.0.0"));
EXPECT_THAT(blob, IsVhloArtifact("1.0.0"));
}
TEST(MlirToHloTest, ChloTest) {
constexpr char kProgram[] =
R"(
func.func @add(%arg0: tensor<1x2xf32>) -> tensor<1x2xf32> {
%cst = stablehlo.constant dense<1.0> : tensor<1x2xf32>
%0 = chlo.broadcast_add %arg0, %cst : (tensor<1x2xf32>, tensor<1x2xf32>) -> tensor<1x2xf32>
return %0 : tensor<1x2xf32>
}
)";
mlir::MLIRContext context;
TF_ASSERT_OK_AND_ASSIGN(mlir::OwningOpRef<mlir::ModuleOp> module,
ParseMlirModuleString(kProgram, context));
TF_ASSERT_OK_AND_ASSIGN(std::string blob, Serialize(*module, 47, "1.0.0"));
EXPECT_THAT(blob, IsVhloArtifact("1.0.0"));
}
TEST(MlirToHloTest, MhloTest) {
constexpr char kProgram[] =
R"(
func.func @add(%arg0: tensor<1x2xf32>) -> tensor<1x2xf32> {
%cst = mhlo.constant dense<1.0> : tensor<1x2xf32>
%0 = mhlo.add %arg0, %cst : tensor<1x2xf32>
return %0 : tensor<1x2xf32>
}
)";
mlir::MLIRContext context;
TF_ASSERT_OK_AND_ASSIGN(mlir::OwningOpRef<mlir::ModuleOp> module,
ParseMlirModuleString(kProgram, context));
TF_ASSERT_OK_AND_ASSIGN(std::string blob, Serialize(*module, 47, "1.0.0"));
EXPECT_THAT(blob, Not(IsVhloArtifact("1.0.0")));
}
}
} | 2,203 |
#ifndef XLA_PJRT_TRACKED_DEVICE_BUFFER_H_
#define XLA_PJRT_TRACKED_DEVICE_BUFFER_H_
#include <atomic>
#include <cstdint>
#include <functional>
#include <memory>
#include <string>
#include "absl/base/thread_annotations.h"
#include "absl/container/flat_hash_map.h"
#include "absl/container/flat_hash_set.h"
#include "absl/functional/any_invocable.h"
#include "xla/pjrt/event_pool.h"
#include "xla/service/executable.h"
#include "xla/service/maybe_owning_device_memory.h"
#include "xla/service/shaped_buffer.h"
#include "xla/shape.h"
#include "xla/shape_tree.h"
#include "xla/stream_executor/device_memory.h"
#include "xla/stream_executor/device_memory_allocator.h"
#include "xla/tsl/concurrency/async_value_ref.h"
#include "tsl/platform/threadpool.h"
namespace xla {
class BufferSequencingEvent {
public:
explicit BufferSequencingEvent(tsl::thread::ThreadPool* thread_pool)
: thread_pool_(thread_pool),
defined_status_(tsl::MakeUnconstructedAsyncValueRef<absl::Status>()) {}
void SetSequencingEvent(EventPool::Handle event, se::Stream* stream);
void WaitForEventOnStream(se::Stream* stream);
absl::Status WaitForEventOnExternalStream(std::intptr_t stream);
bool DefinedOn(se::Stream* stream);
bool IsComplete();
inline bool operator<(const BufferSequencingEvent& rhs) const {
return sequence_number() < rhs.sequence_number();
}
inline bool operator>(const BufferSequencingEvent& rhs) const {
return rhs < *this;
}
inline bool operator<=(const BufferSequencingEvent& rhs) const {
return !(*this > rhs);
}
inline bool operator>=(const BufferSequencingEvent& rhs) const {
return !(*this < rhs);
}
inline bool operator==(int number) const {
return sequence_number() == number;
}
void ExecuteOrAddToFutureTasks(const std::string& task_name,
std::function<void()> task);
void ExecuteFutureTasks();
bool IsDefined() {
absl::MutexLock lock(&mu_);
return defined_status_.IsConcrete();
}
void SetDefinedStatus(absl::Status status) {
{
absl::MutexLock lock(&mu_);
defined_status_.emplace(status);
}
this->ExecuteFutureTasks();
}
absl::Status GetDefinedStatus() {
absl::MutexLock lock(&mu_);
CHECK(defined_status_.IsConcrete());
return defined_status_.get();
}
bool IsPredeterminedError() {
absl::MutexLock lock(&mu_);
return defined_status_.IsConcrete() && !defined_status_.get().ok();
}
private:
bool EventHasBeenRecorded() const ABSL_EXCLUSIVE_LOCKS_REQUIRED(mu_);
uint64_t sequence_number() const;
EventPool::Handle event_;
std::atomic<uint64_t> sequence_number_{0};
mutable absl::Mutex mu_;
absl::InlinedVector<se::Stream*, 2> streams_defined_on_ ABSL_GUARDED_BY(mu_);
absl::flat_hash_map<std::string, std::function<void()>>
on_ready_tasks_callback_ ABSL_GUARDED_BY(mu_);
tsl::thread::ThreadPool* thread_pool_;
tsl::AsyncValueRef<absl::Status> defined_status_ ABSL_GUARDED_BY(mu_);
};
class TrackedDeviceBuffer {
public:
struct StreamAndEvent {
se::Stream* stream;
std::shared_ptr<BufferSequencingEvent> event;
bool reference_held;
};
static std::shared_ptr<TrackedDeviceBuffer> FromScopedShapedBuffer(
ScopedShapedBuffer* shaped_buffer,
absl::Span<const std::shared_ptr<BufferSequencingEvent>>
definition_events);
ShapedBuffer AsShapedBuffer(const Shape& on_device_shape) const;
void AddToInputAsImmutable(
ShapeTree<MaybeOwningDeviceMemory>::iterator* iterator,
const ShapeTree<MaybeOwningDeviceMemory>::iterator& end) const;
void AddToInputAsDonated(
ShapeTree<MaybeOwningDeviceMemory>::iterator* iterator,
const ShapeTree<MaybeOwningDeviceMemory>::iterator& end,
ExecutionInput* execution_input,
se::DeviceMemoryAllocator* allocator) const;
se::DeviceMemoryAllocator* allocator() const { return allocator_; }
int device_ordinal() const { return device_ordinal_; }
absl::InlinedVector<se::DeviceMemoryBase, 1>& device_memory() {
return device_memory_;
}
const absl::InlinedVector<se::DeviceMemoryBase, 1>& device_memory() const {
return device_memory_;
}
absl::Span<const std::shared_ptr<BufferSequencingEvent>> definition_events()
const {
return definition_events_;
}
absl::Span<const StreamAndEvent> usage_events() const {
return usage_events_;
}
void ReleaseDeviceMemory() { device_memory_.clear(); }
void AddUsageEvent(se::Stream* usage_stream,
std::shared_ptr<BufferSequencingEvent> event,
bool reference_held);
using StreamAndEventContainer = absl::InlinedVector<StreamAndEvent, 3>;
StreamAndEventContainer LockUseAndTransferUsageEvents();
TrackedDeviceBuffer() : in_use_(true) {}
TrackedDeviceBuffer(se::DeviceMemoryAllocator* allocator, int device_ordinal,
absl::Span<se::DeviceMemoryBase const> device_memory,
absl::Span<const std::shared_ptr<BufferSequencingEvent>>
definition_events,
absl::AnyInvocable<void() &&> on_delete_callback);
~TrackedDeviceBuffer();
private:
se::DeviceMemoryAllocator* allocator_;
int device_ordinal_;
absl::InlinedVector<se::DeviceMemoryBase, 1> device_memory_;
absl::InlinedVector<std::shared_ptr<BufferSequencingEvent>, 2>
definition_events_;
bool in_use_;
StreamAndEventContainer usage_events_;
absl::AnyInvocable<void() &&> on_delete_callback_;
};
void GetDeviceBufferEvents(const TrackedDeviceBuffer& buffer,
bool get_usage_events,
absl::flat_hash_set<BufferSequencingEvent*>* events);
void WaitForBufferDefinitionEventsOnStream(const TrackedDeviceBuffer& buffer,
se::Stream* stream);
}
#endif
#include "xla/pjrt/tracked_device_buffer.h"
#include <algorithm>
#include <atomic>
#include <cstdint>
#include <functional>
#include <iterator>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "absl/functional/any_invocable.h"
#include "absl/status/status.h"
#include "absl/synchronization/mutex.h"
#include "absl/types/span.h"
#include "xla/pjrt/event_pool.h"
#include "xla/service/executable.h"
#include "xla/service/maybe_owning_device_memory.h"
#include "xla/service/shaped_buffer.h"
#include "xla/shape.h"
#include "xla/shape_tree.h"
#include "xla/shape_util.h"
#include "xla/stream_executor/device_memory.h"
#include "xla/stream_executor/device_memory_allocator.h"
#include "xla/stream_executor/event.h"
#include "tsl/platform/logging.h"
#include "tsl/profiler/lib/connected_traceme.h"
#include "tsl/profiler/lib/context_types.h"
namespace xla {
void BufferSequencingEvent::SetSequencingEvent(EventPool::Handle event,
se::Stream* stream) {
{
absl::MutexLock lock(&mu_);
defined_status_.emplace(absl::OkStatus());
CHECK(!event_.event());
event_ = std::move(event);
CHECK(streams_defined_on_.empty());
streams_defined_on_.push_back(stream);
sequence_number_.store(event_.sequence_number(), std::memory_order_seq_cst);
}
this->ExecuteFutureTasks();
}
bool BufferSequencingEvent::EventHasBeenRecorded() const {
return event_.event() != nullptr;
}
uint64_t BufferSequencingEvent::sequence_number() const {
uint64_t seq = sequence_number_.load(std::memory_order_seq_cst);
return seq;
}
void BufferSequencingEvent::WaitForEventOnStream(se::Stream* stream) {
absl::MutexLock lock(&mu_);
mu_.Await(
absl::Condition(this, &BufferSequencingEvent::EventHasBeenRecorded));
if (std::find(streams_defined_on_.begin(), streams_defined_on_.end(),
stream) != streams_defined_on_.end()) {
return;
}
stream->WaitFor(event_.event()).IgnoreError();
streams_defined_on_.push_back(stream);
}
absl::Status BufferSequencingEvent::WaitForEventOnExternalStream(
std::intptr_t stream) {
absl::MutexLock lock(&mu_);
mu_.Await(
absl::Condition(this, &BufferSequencingEvent::EventHasBeenRecorded));
return event_.event()->WaitForEventOnExternalStream(stream);
}
bool BufferSequencingEvent::DefinedOn(se::Stream* stream) {
absl::MutexLock lock(&mu_);
mu_.Await(
absl::Condition(this, &BufferSequencingEvent::EventHasBeenRecorded));
return std::find(streams_defined_on_.begin(), streams_defined_on_.end(),
stream) != streams_defined_on_.end();
}
bool BufferSequencingEvent::IsComplete() {
absl::MutexLock lock(&mu_);
mu_.Await(
absl::Condition(this, &BufferSequencingEvent::EventHasBeenRecorded));
return event_.event()->PollForStatus() == se::Event::Status::kComplete;
}
void BufferSequencingEvent::ExecuteOrAddToFutureTasks(
const std::string& task_name, std::function<void()> task) {
absl::MutexLock lock(&mu_);
tsl::profiler::TraceMeProducer producer(
"BufferSequencingEvent::ExecuteOrAddToFutureTasks",
tsl::profiler::ContextType::kPjRt);
uint64_t context_id = producer.GetContextId();
auto wrapped_task = [task = std::move(task), context_id]() {
tsl::profiler::TraceMeConsumer consumer("BufferSequencingEvent::Execute",
tsl::profiler::ContextType::kPjRt,
context_id);
task();
};
if (defined_status_.IsConcrete()) {
thread_pool_->Schedule(std::move(wrapped_task));
return;
}
on_ready_tasks_callback_[task_name] = std::move(wrapped_task);
}
void BufferSequencingEvent::ExecuteFutureTasks() {
absl::MutexLock lock(&mu_);
for (auto& [task_name, task_callback] : on_ready_tasks_callback_) {
thread_pool_->Schedule(std::move(task_callback));
}
on_ready_tasks_callback_.clear();
}
std::shared_ptr<TrackedDeviceBuffer>
TrackedDeviceBuffer::FromScopedShapedBuffer(
ScopedShapedBuffer* shaped_buffer,
absl::Span<const std::shared_ptr<BufferSequencingEvent>>
definition_events) {
ShapeTree<se::DeviceMemoryBase>::iterator iterator =
shaped_buffer->buffers().begin();
std::vector<se::DeviceMemoryBase> buffers;
buffers.reserve(1);
ShapeUtil::ForEachSubshape(
shaped_buffer->on_device_shape(), [&](const Shape&, const ShapeIndex&) {
CHECK(iterator != shaped_buffer->buffers().end());
buffers.push_back(iterator->second);
iterator->second = se::DeviceMemoryBase();
++iterator;
});
CHECK(iterator == shaped_buffer->buffers().end());
return std::make_shared<TrackedDeviceBuffer>(
shaped_buffer->memory_allocator(), shaped_buffer->device_ordinal(),
absl::Span<se::DeviceMemoryBase>(buffers), definition_events,
nullptr);
}
ShapedBuffer TrackedDeviceBuffer::AsShapedBuffer(
const Shape& on_device_shape) const {
ShapedBuffer shaped_buffer(on_device_shape, device_ordinal_);
ShapeTree<se::DeviceMemoryBase>::iterator iterator =
shaped_buffer.buffers().begin();
for (const se::DeviceMemoryBase& buf : device_memory_) {
CHECK(iterator != shaped_buffer.buffers().end());
iterator->second = buf;
++iterator;
}
CHECK(iterator == shaped_buffer.buffers().end());
return shaped_buffer;
}
void TrackedDeviceBuffer::AddToInputAsImmutable(
ShapeTree<MaybeOwningDeviceMemory>::iterator* iterator,
const ShapeTree<MaybeOwningDeviceMemory>::iterator& end) const {
for (const se::DeviceMemoryBase& buf : device_memory_) {
CHECK(*iterator != end);
(*iterator)->second = MaybeOwningDeviceMemory(buf);
++(*iterator);
}
}
void TrackedDeviceBuffer::AddToInputAsDonated(
ShapeTree<MaybeOwningDeviceMemory>::iterator* iterator,
const ShapeTree<MaybeOwningDeviceMemory>::iterator& end,
ExecutionInput* execution_input,
se::DeviceMemoryAllocator* allocator) const {
for (const se::DeviceMemoryBase& buf : device_memory_) {
CHECK(*iterator != end);
(*iterator)->second = MaybeOwningDeviceMemory(
se::OwningDeviceMemory(buf, device_ordinal_, allocator));
execution_input->SetUnownedIndex((*iterator)->first);
++(*iterator);
}
}
TrackedDeviceBuffer::TrackedDeviceBuffer(
se::DeviceMemoryAllocator* allocator, int device_ordinal,
absl::Span<se::DeviceMemoryBase const> device_memory,
absl::Span<const std::shared_ptr<BufferSequencingEvent>> definition_events,
absl::AnyInvocable<void() &&> on_delete_callback)
: allocator_(allocator),
device_ordinal_(device_ordinal),
device_memory_(device_memory.begin(), device_memory.end()),
definition_events_(std::make_move_iterator(definition_events.begin()),
std::make_move_iterator(definition_events.end())),
in_use_(true),
on_delete_callback_(std::move(on_delete_callback)) {}
TrackedDeviceBuffer::~TrackedDeviceBuffer() {
if (allocator_) {
for (const se::DeviceMemoryBase& buffer : device_memory_) {
absl::Status status = allocator_->Deallocate(device_ordinal_, buffer);
if (!status.ok()) {
LOG(ERROR) << "Buffer deallocation failed: " << status;
}
}
}
if (on_delete_callback_) {
std::move(on_delete_callback_)();
}
}
void TrackedDeviceBuffer::AddUsageEvent(
se::Stream* usage_stream, std::shared_ptr<BufferSequencingEvent> event,
bool reference_held) {
CHECK(in_use_);
if (*event == 0) {
usage_events_.push_back({usage_stream, event, reference_held});
return;
}
for (auto& existing : usage_events_) {
if (*existing.event == 0) continue;
if (existing.stream == usage_stream) {
if (*existing.event < *event) {
existing.event = event;
existing.reference_held = reference_held;
}
return;
}
}
usage_events_.push_back({usage_stream, event, reference_held});
}
TrackedDeviceBuffer::StreamAndEventContainer
TrackedDeviceBuffer::LockUseAndTransferUsageEvents() {
CHECK(in_use_);
in_use_ = false;
return std::move(usage_events_);
}
void GetDeviceBufferEvents(
const TrackedDeviceBuffer& buffer, bool get_usage_events,
absl::flat_hash_set<BufferSequencingEvent*>* events) {
if (get_usage_events) {
for (const auto& e : buffer.usage_events()) {
events->insert(e.event.get());
}
} else {
for (const auto& e : buffer.definition_events()) {
events->insert(e.get());
}
}
}
void WaitForBufferDefinitionEventsOnStream(const TrackedDeviceBuffer& buffer,
se::Stream* stream) {
absl::flat_hash_set<BufferSequencingEvent*> events;
GetDeviceBufferEvents(buffer, false, &events);
for (BufferSequencingEvent* event : events) {
event->WaitForEventOnStream(stream);
}
}
} | #include "xla/pjrt/tracked_device_buffer.h"
#include <memory>
#include <vector>
#include "absl/status/status.h"
#include "xla/client/client_library.h"
#include "xla/literal_util.h"
#include "xla/shape_util.h"
#include "xla/status_macros.h"
#include "xla/stream_executor/device_memory_allocator.h"
#include "xla/test.h"
namespace xla {
namespace {
absl::StatusOr<std::shared_ptr<TrackedDeviceBuffer>> MakeArray(
const Shape& shape, LocalClient* client) {
std::vector<stream_executor::DeviceMemoryBase> device_buffers;
TF_RETURN_IF_ERROR(ShapeUtil::ForEachSubshapeWithStatus(
client->backend().transfer_manager()->HostShapeToDeviceShape(shape),
[&](const Shape& subshape, const ShapeIndex&) -> absl::Status {
TF_ASSIGN_OR_RETURN(
se::OwningDeviceMemory device_memory,
client->backend().memory_allocator()->Allocate(
0,
client->backend().transfer_manager()->GetByteSizeRequirement(
subshape)));
device_buffers.push_back(device_memory.Release());
return absl::OkStatus();
}));
return std::make_shared<TrackedDeviceBuffer>(
client->backend().memory_allocator(), 0,
device_buffers,
absl::Span<const std::shared_ptr<BufferSequencingEvent>>(), nullptr);
}
TEST(TrackedDeviceBufferTest, AsShapedBuffer) {
LocalClient* client = ClientLibrary::LocalClientOrDie();
Shape a_shape = ShapeUtil::MakeShape(F32, {3, 101, 4});
Shape b_shape = ShapeUtil::MakeShape(S8, {77});
Shape c_shape = ShapeUtil::MakeShape(S64, {});
TF_ASSERT_OK_AND_ASSIGN(auto a_buffer, MakeArray(a_shape, client));
TF_ASSERT_OK_AND_ASSIGN(auto b_buffer, MakeArray(b_shape, client));
TF_ASSERT_OK_AND_ASSIGN(auto c_buffer, MakeArray(c_shape, client));
ASSERT_EQ(a_buffer->device_memory().size(), 1);
ASSERT_EQ(b_buffer->device_memory().size(), 1);
ASSERT_EQ(c_buffer->device_memory().size(), 1);
std::vector<se::DeviceMemoryBase> expected_buffer_sequence = {
a_buffer->device_memory()[0], b_buffer->device_memory()[0],
c_buffer->device_memory()[0]};
ShapedBuffer shaped_a = a_buffer->AsShapedBuffer(
client->backend().transfer_manager()->HostShapeToDeviceShape(a_shape));
ShapedBuffer shaped_b = b_buffer->AsShapedBuffer(
client->backend().transfer_manager()->HostShapeToDeviceShape(b_shape));
ShapedBuffer shaped_c = c_buffer->AsShapedBuffer(
client->backend().transfer_manager()->HostShapeToDeviceShape(c_shape));
auto expected_it = expected_buffer_sequence.begin();
for (auto it = shaped_a.buffers().begin(); it != shaped_a.buffers().end();
++it) {
ASSERT_TRUE(expected_it != expected_buffer_sequence.end());
EXPECT_TRUE(expected_it->IsSameAs(it->second));
++expected_it;
}
for (auto it = shaped_b.buffers().begin(); it != shaped_b.buffers().end();
++it) {
ASSERT_TRUE(expected_it != expected_buffer_sequence.end());
EXPECT_TRUE(expected_it->IsSameAs(it->second));
++expected_it;
}
for (auto it = shaped_c.buffers().begin(); it != shaped_c.buffers().end();
++it) {
ASSERT_TRUE(expected_it != expected_buffer_sequence.end());
EXPECT_TRUE(expected_it->IsSameAs(it->second));
++expected_it;
}
EXPECT_TRUE(expected_it == expected_buffer_sequence.end());
}
TEST(TrackedDeviceBufferTest, FromScopedShapedBuffer) {
LocalClient* client = ClientLibrary::LocalClientOrDie();
Literal literal = LiteralUtil::MakeTupleOwned(
LiteralUtil::CreateFullWithDescendingLayout<float>({10, 3, 7}, 33.4f),
LiteralUtil::One(S64));
TF_ASSERT_OK_AND_ASSIGN(
ScopedShapedBuffer shaped_buffer,
client->LiteralToShapedBuffer(literal, 0));
std::shared_ptr<TrackedDeviceBuffer> device_buffer =
TrackedDeviceBuffer::FromScopedShapedBuffer(&shaped_buffer, {});
EXPECT_EQ(device_buffer->device_memory().size(),
ShapeUtil::SubshapeCount(
client->backend().transfer_manager()->HostShapeToDeviceShape(
literal.shape())));
}
}
} | 2,204 |
#ifndef XLA_PJRT_PJRT_API_H_
#define XLA_PJRT_PJRT_API_H_
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/string_view.h"
#include "xla/pjrt/c/pjrt_c_api.h"
#include "tsl/platform/platform.h"
namespace pjrt {
absl::StatusOr<const PJRT_Api*> PjrtApi(absl::string_view device_type);
absl::Status SetPjrtApi(absl::string_view device_type, const PJRT_Api* api);
absl::StatusOr<const PJRT_Api*> LoadPjrtPlugin(absl::string_view device_type,
absl::string_view library_path);
absl::StatusOr<bool> IsPjrtPluginInitialized(absl::string_view device_type);
absl::Status InitializePjrtPlugin(absl::string_view device_type);
}
#endif
#include "xla/pjrt/pjrt_api.h"
#include <cstdlib>
#include <utility>
#include "absl/status/status.h"
#include "absl/strings/ascii.h"
#include "absl/strings/numbers.h"
#include "absl/strings/str_cat.h"
#include "xla/pjrt/c/pjrt_c_api.h"
#if !defined(PLATFORM_WINDOWS)
#include <dlfcn.h>
#endif
#include <string>
#include "absl/container/flat_hash_map.h"
#include "absl/status/statusor.h"
#include "absl/strings/string_view.h"
#include "xla/pjrt/c/pjrt_c_api_helpers.h"
#include "tsl/platform/errors.h"
#include "tsl/platform/logging.h"
namespace pjrt {
constexpr int kMinPjRtMinor = 29;
static auto* pjrt_apis =
new absl::flat_hash_map<std::string, std::pair<const PJRT_Api*, bool>>{};
static std::string CanonicalizeDeviceType(absl::string_view device_type) {
return absl::AsciiStrToLower(device_type);
}
absl::StatusOr<const PJRT_Api*> PjrtApi(absl::string_view device_type) {
std::string canonicalize_device_type = CanonicalizeDeviceType(device_type);
auto iter = pjrt_apis->find(canonicalize_device_type);
if (iter == pjrt_apis->end()) {
return tsl::errors::NotFound("PJRT_Api not found for device type ",
canonicalize_device_type);
}
return iter->second.first;
}
absl::Status SetPjrtApi(absl::string_view device_type, const PJRT_Api* api) {
std::string canonicalize_device_type = CanonicalizeDeviceType(device_type);
if (auto iter = pjrt_apis->find(canonicalize_device_type);
iter != pjrt_apis->end()) {
return tsl::errors::AlreadyExists(
"PJRT_Api already exists for device type ", canonicalize_device_type);
}
(*pjrt_apis)[canonicalize_device_type] =
std::make_pair(api, false);
LOG(INFO) << "PJRT_Api is set for device type " << canonicalize_device_type;
return absl::OkStatus();
}
typedef const PJRT_Api* (*PjrtApiInitFn)();
absl::StatusOr<const PJRT_Api*> LoadPjrtPlugin(absl::string_view device_type,
absl::string_view library_path) {
#ifdef PLATFORM_WINDOWS
return tsl::errors::Unimplemented(
"LoadPjrtPlugin is not implemented on windows yet.");
#else
void* library = dlopen(library_path.data(), RTLD_LAZY);
if (library == nullptr) {
return tsl::errors::Internal("Failed to open ", library_path, ": ",
dlerror());
}
PjrtApiInitFn init_fn;
*reinterpret_cast<void**>(&init_fn) = dlsym(library, "GetPjrtApi");
if (init_fn == nullptr) {
return tsl::errors::NotFound("GetPjrtApi not found in ", library_path);
}
LOG(INFO) << "GetPjrtApi was found for " << device_type << " at "
<< library_path;
const PJRT_Api* api = init_fn();
TF_RETURN_IF_ERROR(SetPjrtApi(device_type, api));
return api;
#endif
}
absl::StatusOr<bool> IsPjrtPluginInitialized(absl::string_view device_type) {
std::string canonicalize_device_type = CanonicalizeDeviceType(device_type);
auto iter = pjrt_apis->find(canonicalize_device_type);
if (iter == pjrt_apis->end()) {
return absl::NotFoundError(absl::StrCat(
"PJRT_Api not found for device type ", canonicalize_device_type,
". Call SetPjrtApi before calling IsPjrtPluginInitialized."));
}
return iter->second.second;
}
static bool IsPjRtCompatibilityEnabled() {
const char* val = getenv("ENABLE_PJRT_COMPATIBILITY");
if (val == nullptr) {
return false;
}
bool enabled = false;
if (!absl::SimpleAtob(val, &enabled)) {
return false;
}
return enabled;
}
absl::Status InitializePjrtPlugin(absl::string_view device_type) {
std::string canonicalize_device_type = CanonicalizeDeviceType(device_type);
auto iter = pjrt_apis->find(canonicalize_device_type);
if (iter == pjrt_apis->end()) {
return absl::NotFoundError(absl::StrCat(
"PJRT_Api not found for device type ", canonicalize_device_type,
". Call SetPjrtApi before calling IsPjrtPluginInitialized."));
}
if (iter->second.second) {
return absl::InvalidArgumentError(
absl::StrCat("InitializePjrtPlugin requested to run on already "
"initialized plugin ",
canonicalize_device_type));
}
const PJRT_Api* pjrt_api = iter->second.first;
LOG(INFO) << "The PJRT plugin has PJRT API version "
<< pjrt_api->pjrt_api_version.major_version << "."
<< pjrt_api->pjrt_api_version.minor_version
<< ". The framework PJRT API version is " << PJRT_API_MAJOR << "."
<< PJRT_API_MINOR << ".";
if (IsPjRtCompatibilityEnabled()) {
if (pjrt_api->pjrt_api_version.major_version != PJRT_API_MAJOR) {
return absl::InvalidArgumentError(absl::StrCat(
"Mismatched PJRT plugin PJRT API major version (",
pjrt_api->pjrt_api_version.major_version,
") and framework PJRT API major version ", PJRT_API_MAJOR, ")."));
}
if (pjrt_api->pjrt_api_version.minor_version < kMinPjRtMinor) {
return absl::InvalidArgumentError(absl::StrCat(
"Plugin PJRT API version ", pjrt_api->pjrt_api_version.major_version,
".", pjrt_api->pjrt_api_version.minor_version,
" is older than the minimum supported version ", PJRT_API_MAJOR, ".",
kMinPjRtMinor));
}
} else {
if (pjrt_api->pjrt_api_version.major_version != PJRT_API_MAJOR ||
pjrt_api->pjrt_api_version.minor_version != PJRT_API_MINOR) {
return absl::InvalidArgumentError(
absl::StrCat("Mismatched PJRT plugin PJRT API version (",
pjrt_api->pjrt_api_version.major_version, ".",
pjrt_api->pjrt_api_version.minor_version,
") and framework PJRT API version ", PJRT_API_MAJOR, ".",
PJRT_API_MINOR, ")."));
}
}
PJRT_Plugin_Initialize_Args args;
args.struct_size = PJRT_Plugin_Initialize_Args_STRUCT_SIZE;
args.extension_start = nullptr;
RETURN_STATUS_IF_PJRT_ERROR(pjrt_api->PJRT_Plugin_Initialize(&args),
pjrt_api);
iter->second.second = true;
return absl::OkStatus();
}
} | #include "xla/pjrt/pjrt_api.h"
#include <string>
#include <gtest/gtest.h>
#include "xla/pjrt/c/pjrt_c_api.h"
#include "xla/pjrt/c/pjrt_c_api_wrapper_impl.h"
#include "tsl/lib/core/status_test_util.h"
#include "tsl/platform/status_matchers.h"
#include "tsl/protobuf/error_codes.pb.h"
namespace {
using ::testing::HasSubstr;
using ::tsl::testing::StatusIs;
TEST(PjRtApiTest, SetAndGetGlobalPjRtApi) {
PJRT_Api api;
api.struct_size = PJRT_Api_STRUCT_SIZE;
api.pjrt_api_version.major_version = PJRT_API_MAJOR;
api.pjrt_api_version.minor_version = PJRT_API_MINOR;
TF_ASSERT_OK(pjrt::SetPjrtApi("CPU", &api));
TF_ASSERT_OK_AND_ASSIGN(const PJRT_Api* output, pjrt::PjrtApi("CPU"));
TF_ASSERT_OK_AND_ASSIGN(const PJRT_Api* output_lowercase,
pjrt::PjrtApi("cpu"));
TF_ASSERT_OK_AND_ASSIGN(bool is_initialized,
pjrt::IsPjrtPluginInitialized("CPU"));
EXPECT_FALSE(is_initialized);
EXPECT_EQ(output, &api);
EXPECT_EQ(output_lowercase, &api);
EXPECT_THAT(pjrt::SetPjrtApi("CPU", &api),
StatusIs(tensorflow::error::ALREADY_EXISTS,
HasSubstr("PJRT_Api already exists for device type")));
EXPECT_THAT(pjrt::PjrtApi("TPU"),
StatusIs(tensorflow::error::NOT_FOUND,
HasSubstr("PJRT_Api not found for device type tpu")));
}
TEST(PjRtApiTest, InitPjRtPlugin) {
PJRT_Api api;
api.struct_size = PJRT_Api_STRUCT_SIZE;
api.pjrt_api_version.major_version = PJRT_API_MAJOR;
api.pjrt_api_version.minor_version = PJRT_API_MINOR;
api.PJRT_Plugin_Initialize = pjrt::PJRT_Plugin_Initialize_NoOp;
std::string plugin_name = "plugin";
TF_ASSERT_OK(pjrt::SetPjrtApi(plugin_name, &api));
TF_ASSERT_OK_AND_ASSIGN(bool is_initialized,
pjrt::IsPjrtPluginInitialized(plugin_name));
EXPECT_FALSE(is_initialized);
TF_ASSERT_OK(pjrt::InitializePjrtPlugin(plugin_name));
TF_ASSERT_OK_AND_ASSIGN(is_initialized,
pjrt::IsPjrtPluginInitialized(plugin_name));
EXPECT_TRUE(is_initialized);
}
} | 2,205 |
#ifndef XLA_PJRT_PJRT_FUTURE_H_
#define XLA_PJRT_PJRT_FUTURE_H_
#include <algorithm>
#include <atomic>
#include <cstdint>
#include <functional>
#include <memory>
#include <type_traits>
#include <utility>
#include "absl/status/status.h"
#include "absl/types/span.h"
#include "xla/tsl/concurrency/async_value.h"
#include "xla/tsl/concurrency/async_value_ref.h"
#include "xla/tsl/concurrency/ref_count.h"
#include "tsl/platform/logging.h"
namespace xla {
template <class T = void>
class PjRtFuture;
namespace internal {
template <class T, bool unique>
class PjRtFutureBase;
}
PjRtFuture<> JoinFutures(absl::Span<const PjRtFuture<>> futures);
class ScopedAsyncTrackingEvent {
public:
virtual ~ScopedAsyncTrackingEvent() = default;
private:
template <class T, bool unique>
friend class internal::PjRtFutureBase;
virtual void AddDependency(tsl::RCReference<tsl::AsyncValue> dependency) = 0;
};
struct PjRtFutureHelpers {
public:
struct ProfilingKeys {
uint64_t traceme_context_id = -1;
};
using OnBlockStartFn = std::function<ProfilingKeys()>;
using OnBlockEndFn = std::function<void(ProfilingKeys)>;
};
namespace internal {
template <typename T>
struct IsStatusOr : public std::false_type {};
template <typename T>
struct IsStatusOr<absl::StatusOr<T>> : public std::true_type {};
template <bool unique>
class PjRtFutureMoveControl;
template <>
class PjRtFutureMoveControl<true> {
protected:
PjRtFutureMoveControl() = default;
PjRtFutureMoveControl(const PjRtFutureMoveControl&) = delete;
PjRtFutureMoveControl& operator=(const PjRtFutureMoveControl&) = delete;
PjRtFutureMoveControl(PjRtFutureMoveControl&&) = default;
PjRtFutureMoveControl& operator=(PjRtFutureMoveControl&&) = default;
};
template <>
class PjRtFutureMoveControl<false> {
protected:
PjRtFutureMoveControl() = default;
PjRtFutureMoveControl(const PjRtFutureMoveControl&) = default;
PjRtFutureMoveControl& operator=(const PjRtFutureMoveControl&) = default;
PjRtFutureMoveControl(PjRtFutureMoveControl&&) = default;
PjRtFutureMoveControl& operator=(PjRtFutureMoveControl&&) = default;
};
template <typename T, bool unique = !std::is_copy_constructible_v<T>>
class PjRtFutureBase : public PjRtFutureMoveControl<unique> {
protected:
PjRtFutureBase(tsl::AsyncValueRef<T> promise,
PjRtFutureHelpers::OnBlockStartFn on_block_start,
PjRtFutureHelpers::OnBlockEndFn on_block_end)
: promise_(std::move(promise)),
on_block_start_(std::move(on_block_start)),
on_block_end_(std::move(on_block_end)) {}
public:
PjRtFutureBase() = default;
explicit PjRtFutureBase(
T t, PjRtFutureHelpers::OnBlockStartFn on_block_start = nullptr,
PjRtFutureHelpers::OnBlockEndFn on_block_end = nullptr)
: PjRtFutureBase(tsl::MakeAvailableAsyncValueRef<T>(std::move(t)),
std::move(on_block_start), std::move(on_block_end)) {}
bool IsValid() const { return promise_ != nullptr; }
bool IsReady() {
CHECK(IsValid());
return promise_.IsAvailable();
}
bool IsKnownReady() {
CHECK(IsValid());
return promise_.IsAvailable();
}
void AssertHappensBefore(ScopedAsyncTrackingEvent* event) {
CHECK(IsValid());
if (event) event->AddDependency(promise_.CopyRCRef());
}
protected:
static constexpr bool is_unique() { return unique; }
class Promise {
public:
Promise() = default;
Promise(Promise&& other) = default;
Promise& operator=(Promise&& other) = default;
Promise(const Promise& other) = default;
Promise& operator=(const Promise& other) = default;
operator bool() const { return static_cast<bool>(promise_); }
protected:
explicit Promise(tsl::AsyncValueRef<T> promise)
: promise_(std::move(promise)) {}
template <typename... Args>
void emplace(Args&&... args) const {
DCHECK(promise_) << "Promise must wrap an async value";
promise_.template emplace<T>(std::forward<Args>(args)...);
}
tsl::AsyncValueRef<T> release() { return std::move(promise_); }
tsl::AsyncValue* async_value() const { return promise_.GetAsyncValue(); }
#ifndef NDEBUG
int64_t AddFuture() { return num_futures_->fetch_add(1); }
#endif
private:
tsl::AsyncValueRef<T> promise_;
#ifndef NDEBUG
std::shared_ptr<std::atomic<int64_t>> num_futures_ =
std::make_shared<std::atomic<int64_t>>(0);
#endif
};
PjRtFutureHelpers::ProfilingKeys OnBlockStart() const {
return on_block_start_ ? on_block_start_()
: PjRtFutureHelpers::ProfilingKeys();
}
void OnBlockEnd(PjRtFutureHelpers::ProfilingKeys keys) const {
if (on_block_end_) on_block_end_(std::move(keys));
}
void BlockUntilReady() const {
CHECK(IsValid());
if (!promise_.IsAvailable()) {
PjRtFutureHelpers::ProfilingKeys keys = OnBlockStart();
tsl::BlockUntilReady(promise_);
OnBlockEnd(std::move(keys));
}
DCHECK(promise_.IsConcrete());
}
const T& Await() const& {
BlockUntilReady();
return *promise_;
}
std::conditional_t<unique, T, const T&> Await() && {
BlockUntilReady();
if constexpr (unique) {
return std::move(*promise_);
} else {
return *promise_;
}
}
template <typename F, std::enable_if_t<std::is_invocable_v<F, const T&> &&
!unique>* = nullptr>
void OnReady(F&& f) const& {
CHECK(IsValid());
promise_.AndThen(
[promise = promise_.AsPtr(), f = std::forward<F>(f)]() mutable {
DCHECK(promise.IsConcrete());
f(*promise);
});
}
template <
typename F,
std::enable_if_t<unique ? std::is_invocable_v<F, T>
: std::is_invocable_v<F, const T&>>* = nullptr>
void OnReady(F&& f) && {
CHECK(IsValid());
promise_.AndThen(
[promise = promise_.AsPtr(), f = std::forward<F>(f)]() mutable {
DCHECK(promise.IsConcrete());
if constexpr (unique) {
f(std::move(*promise));
} else {
f(*promise);
}
});
}
private:
tsl::AsyncValueRef<T> promise_;
PjRtFutureHelpers::OnBlockStartFn on_block_start_;
PjRtFutureHelpers::OnBlockEndFn on_block_end_;
};
}
template <class T>
class PjRtFuture : public internal::PjRtFutureBase<absl::StatusOr<T>> {
using Base = internal::PjRtFutureBase<absl::StatusOr<T>>;
static_assert(!std::is_same_v<T, absl::Status>,
"Use PjRtFuture<> specialization for stateless futures");
static_assert(
!internal::IsStatusOr<T>::value,
"PjRtFuture<T> already has an implicit absl::StatusOr<T> semantics");
public:
class Promise : public Base::Promise {
public:
using Base::Promise::Promise;
void Set(absl::StatusOr<T> value) {
Base::Promise::emplace(std::move(value));
}
private:
friend class PjRtFuture<T>;
};
static Promise CreatePromise() {
return Promise(tsl::MakeUnconstructedAsyncValueRef<absl::StatusOr<T>>());
}
using Base::Base;
explicit PjRtFuture(
Promise promise,
PjRtFutureHelpers::OnBlockStartFn on_block_start = nullptr,
PjRtFutureHelpers::OnBlockEndFn on_block_end = nullptr)
: Base(promise.release(), std::move(on_block_start),
std::move(on_block_end)) {
#ifndef NDEBUG
if constexpr (Base::is_unique()) {
DCHECK_EQ(promise.AddFuture(), 0)
<< "Unique PjRtFuture cannot share a promise object";
}
#endif
}
using Base::Await;
using Base::OnReady;
};
template <>
class PjRtFuture<void> : public internal::PjRtFutureBase<absl::Status> {
using Base = internal::PjRtFutureBase<absl::Status>;
public:
class Promise : public Base::Promise {
public:
using Base::Promise::async_value;
using Base::Promise::Promise;
void Set(absl::Status status = absl::OkStatus()) {
Base::Promise::emplace(std::move(status));
}
private:
friend class PjRtFuture<void>;
};
static Promise CreatePromise() {
return Promise(tsl::MakeUnconstructedAsyncValueRef<absl::Status>());
}
using Base::Base;
explicit PjRtFuture(
Promise promise,
PjRtFutureHelpers::OnBlockStartFn on_block_start = nullptr,
PjRtFutureHelpers::OnBlockEndFn on_block_end = nullptr)
: Base(promise.release(), std::move(on_block_start),
std::move(on_block_end)) {}
using Base::Await;
using Base::OnReady;
};
}
#endif
#include "xla/pjrt/pjrt_future.h"
#include <atomic>
#include <cstdint>
#include <memory>
#include <utility>
#include "absl/base/thread_annotations.h"
#include "absl/status/status.h"
#include "absl/synchronization/mutex.h"
#include "absl/types/span.h"
#include "tsl/platform/logging.h"
namespace xla {
namespace {
struct State {
explicit State(int32_t size)
: pending_count(size), promise(PjRtFuture<>::CreatePromise()) {}
std::atomic<int32_t> pending_count;
PjRtFuture<>::Promise promise;
absl::Mutex mu;
absl::Status status ABSL_GUARDED_BY(&mu);
};
}
PjRtFuture<> JoinFutures(absl::Span<const PjRtFuture<>> futures) {
if (futures.empty()) {
return PjRtFuture<>(absl::OkStatus());
} else if (futures.size() == 1) {
return futures.front();
}
auto state = std::make_shared<State>(futures.size());
for (const PjRtFuture<>& future : futures) {
future.OnReady([state](absl::Status status) {
if (!status.ok()) {
absl::MutexLock lock(&state->mu);
state->status.Update(status);
}
const int pending_count =
state->pending_count.fetch_sub(1, std::memory_order_acq_rel);
CHECK_GE(pending_count, 1) << "Pending count can't drop below 0";
if (pending_count == 1) {
absl::MutexLock lock(&state->mu);
state->promise.Set(std::move(state->status));
}
});
}
return PjRtFuture<>(state->promise);
}
} | #include "xla/pjrt/pjrt_future.h"
#include <cstdint>
#include <memory>
#include <utility>
#include <vector>
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "tsl/platform/test.h"
namespace xla {
TEST(PjRtFutureTest, StatelessFuture) {
auto promise = PjRtFuture<>::CreatePromise();
PjRtFuture<> future(promise);
EXPECT_FALSE(future.IsReady());
promise.Set();
EXPECT_TRUE(future.IsReady());
EXPECT_EQ(future.Await(), absl::OkStatus());
future.OnReady(
[](absl::Status status) { EXPECT_EQ(status, absl::OkStatus()); });
}
TEST(PjRtFutureTest, CopyableFuture) {
auto promise = PjRtFuture<int32_t>::CreatePromise();
PjRtFuture<int32_t> future(promise);
PjRtFuture<int32_t> copy_constructed(future);
PjRtFuture<int32_t> copy_assigned = future;
EXPECT_FALSE(copy_constructed.IsReady());
EXPECT_FALSE(copy_assigned.IsReady());
promise.Set(42);
EXPECT_TRUE(copy_constructed.IsReady());
EXPECT_TRUE(copy_assigned.IsReady());
}
TEST(PjRtFutureTest, MoveConstructedFuture) {
auto promise = PjRtFuture<std::unique_ptr<int32_t>>::CreatePromise();
PjRtFuture<std::unique_ptr<int32_t>> future(promise);
PjRtFuture<std::unique_ptr<int32_t>> move_constructed(std::move(future));
EXPECT_FALSE(move_constructed.IsReady());
promise.Set(std::make_unique<int32_t>(42));
EXPECT_TRUE(move_constructed.IsReady());
}
TEST(PjRtFutureTest, MoveAssignedFuture) {
auto promise = PjRtFuture<std::unique_ptr<int32_t>>::CreatePromise();
PjRtFuture<std::unique_ptr<int32_t>> future(promise);
PjRtFuture<std::unique_ptr<int32_t>> move_assigned = std::move(future);
EXPECT_FALSE(move_assigned.IsReady());
promise.Set(std::make_unique<int32_t>(42));
EXPECT_TRUE(move_assigned.IsReady());
}
TEST(PjRtFutureTest, AwaitMoveOnlyFuture) {
auto promise = PjRtFuture<std::unique_ptr<int32_t>>::CreatePromise();
PjRtFuture<std::unique_ptr<int32_t>> future(promise);
promise.Set(std::make_unique<int32_t>(42));
EXPECT_EQ(**future.Await(), 42);
EXPECT_EQ(**std::move(future).Await(), 42);
}
TEST(PjRtFutureTest, OnReadyRvalueFuture) {
auto promise = PjRtFuture<int32_t>::CreatePromise();
PjRtFuture<int32_t> future(promise);
promise.Set(42);
std::move(future).OnReady(
[](absl::StatusOr<int32_t> value) { EXPECT_EQ(*value, 42); });
}
TEST(PjRtFutureTest, OnReadyMoveOnlyFuture) {
auto promise = PjRtFuture<std::unique_ptr<int32_t>>::CreatePromise();
PjRtFuture<std::unique_ptr<int32_t>> future(promise);
promise.Set(std::make_unique<int32_t>(42));
std::move(future).OnReady([](absl::StatusOr<std::unique_ptr<int32_t>> value) {
EXPECT_EQ(**value, 42);
});
}
TEST(PjRtFutureTest, StatelessError) {
auto promise = PjRtFuture<>::CreatePromise();
PjRtFuture<> future(promise);
EXPECT_FALSE(future.IsReady());
promise.Set(absl::InternalError("test"));
EXPECT_TRUE(future.IsReady());
absl::Status status = future.Await();
EXPECT_EQ(status, absl::InternalError("test"));
future.OnReady([](absl::Status status) {
EXPECT_EQ(status, absl::InternalError("test"));
});
}
TEST(PjRtFutureTest, StatelessImmediate) {
PjRtFuture<> ok_future(absl::OkStatus());
PjRtFuture<> error_future(absl::InternalError("test"));
EXPECT_TRUE(ok_future.IsReady());
EXPECT_TRUE(error_future.IsReady());
EXPECT_EQ(ok_future.Await(), absl::OkStatus());
EXPECT_EQ(error_future.Await(), absl::InternalError("test"));
ok_future.OnReady(
[](absl::Status status) { EXPECT_EQ(status, absl::OkStatus()); });
error_future.OnReady([](absl::Status status) {
EXPECT_EQ(status, absl::InternalError("test"));
});
}
TEST(PjRtFutureTest, StatefulFuture) {
auto promise = PjRtFuture<int32_t>::CreatePromise();
PjRtFuture<int32_t> future(promise);
EXPECT_FALSE(future.IsReady());
promise.Set(42);
EXPECT_TRUE(future.IsReady());
future.OnReady([](absl::StatusOr<int32_t> value) { EXPECT_EQ(*value, 42); });
}
TEST(PjRtFutureTest, StatusFuture) {
auto promise = PjRtFuture<>::CreatePromise();
PjRtFuture<> future(promise);
EXPECT_FALSE(future.IsReady());
promise.Set(absl::OkStatus());
EXPECT_TRUE(future.IsReady());
future.OnReady(
[](absl::Status status) { EXPECT_EQ(status, absl::OkStatus()); });
}
TEST(PjRtFutureTest, StatusOrFuture) {
auto promise = PjRtFuture<int32_t>::CreatePromise();
PjRtFuture<int32_t> future(promise);
EXPECT_FALSE(future.IsReady());
promise.Set(42);
EXPECT_TRUE(future.IsReady());
future.OnReady([](absl::StatusOr<int32_t> value) { EXPECT_EQ(*value, 42); });
}
TEST(PjRtFutureTest, JoinFutures) {
auto empty_join = JoinFutures({});
EXPECT_TRUE(empty_join.IsReady());
EXPECT_EQ(empty_join.Await(), absl::OkStatus());
auto promise0 = PjRtFuture<>::CreatePromise();
auto promise1 = PjRtFuture<>::CreatePromise();
std::vector<PjRtFuture<>> futures0 = {PjRtFuture<>(promise0)};
std::vector<PjRtFuture<>> futures1 = {PjRtFuture<>(promise0),
PjRtFuture<>(promise1)};
auto join_one = JoinFutures(futures0);
EXPECT_FALSE(join_one.IsReady());
auto join_two = JoinFutures(futures1);
EXPECT_FALSE(join_two.IsReady());
promise0.Set();
EXPECT_TRUE(join_one.IsReady());
EXPECT_FALSE(join_two.IsReady());
EXPECT_EQ(join_one.Await(), absl::OkStatus());
promise1.Set();
EXPECT_TRUE(join_two.IsReady());
EXPECT_EQ(join_two.Await(), absl::OkStatus());
}
TEST(PjRtFutureTest, JoinErrors) {
auto empty_join = JoinFutures({});
EXPECT_TRUE(empty_join.IsReady());
EXPECT_EQ(empty_join.Await(), absl::OkStatus());
auto promise0 = PjRtFuture<>::CreatePromise();
auto promise1 = PjRtFuture<>::CreatePromise();
std::vector<PjRtFuture<>> futures0 = {PjRtFuture<>(promise0)};
std::vector<PjRtFuture<>> futures1 = {PjRtFuture<>(promise0),
PjRtFuture<>(promise1)};
auto join_one = JoinFutures(futures0);
EXPECT_FALSE(join_one.IsReady());
auto join_two = JoinFutures(futures1);
EXPECT_FALSE(join_two.IsReady());
promise0.Set(absl::InternalError("error #0"));
EXPECT_TRUE(join_one.IsReady());
EXPECT_FALSE(join_two.IsReady());
EXPECT_EQ(join_one.Await(), absl::InternalError("error #0"));
promise1.Set(absl::InternalError("error #1"));
EXPECT_TRUE(join_two.IsReady());
EXPECT_EQ(join_two.Await(), absl::InternalError("error #0"));
}
} | 2,206 |
#ifndef XLA_PJRT_PJRT_C_API_CLIENT_H_
#define XLA_PJRT_PJRT_C_API_CLIENT_H_
#include <cstddef>
#include <cstdint>
#include <functional>
#include <memory>
#include <optional>
#include <string>
#include <utility>
#include <variant>
#include <vector>
#include "absl/container/flat_hash_map.h"
#include "absl/container/inlined_vector.h"
#include "absl/functional/any_invocable.h"
#include "absl/log/check.h"
#include "absl/log/log.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/string_view.h"
#include "absl/synchronization/mutex.h"
#include "absl/types/span.h"
#include "mlir/IR/BuiltinOps.h"
#include "xla/client/xla_computation.h"
#include "xla/hlo/ir/hlo_module.h"
#include "xla/layout.h"
#include "xla/literal.h"
#include "xla/pjrt/c/pjrt_c_api.h"
#include "xla/pjrt/c/pjrt_c_api_helpers.h"
#include "xla/pjrt/distributed/key_value_store_interface.h"
#include "xla/pjrt/pjrt_client.h"
#include "xla/pjrt/pjrt_common.h"
#include "xla/pjrt/pjrt_compiler.h"
#include "xla/pjrt/pjrt_device_description.h"
#include "xla/pjrt/pjrt_executable.h"
#include "xla/pjrt/pjrt_future.h"
#include "xla/pjrt/pjrt_layout.h"
#include "xla/service/computation_placer.h"
#include "xla/service/hlo_cost_analysis.h"
#include "xla/shape.h"
#include "xla/tsl/framework/allocator.h"
#include "xla/util.h"
#include "xla/xla_data.pb.h"
namespace xla {
class PjRtCApiClient;
class PjRtCApiDeviceDescription : public PjRtDeviceDescription {
public:
PjRtCApiDeviceDescription(const PJRT_Api* c_api,
PJRT_DeviceDescription* device_description);
int id() const override;
int process_index() const override;
absl::string_view device_kind() const override;
absl::string_view DebugString() const override;
absl::string_view ToString() const override;
const absl::flat_hash_map<std::string, PjRtDeviceAttribute>& Attributes()
const override;
private:
const PJRT_Api* c_api_;
PJRT_DeviceDescription* device_description_;
absl::flat_hash_map<std::string, xla::PjRtDeviceAttribute> attributes_;
void InitAttributes();
};
class PjRtCApiMemorySpace : public PjRtMemorySpace {
public:
explicit PjRtCApiMemorySpace(PJRT_Memory* c_memory, PjRtCApiClient* client)
: client_(client), c_memory_(c_memory) {}
PjRtClient* client() const override;
absl::Span<PjRtDevice* const> devices() const override { return devices_; }
int id() const override;
absl::string_view kind() const override;
int kind_id() const override;
absl::string_view DebugString() const override;
absl::string_view ToString() const override;
const PJRT_Api* pjrt_c_api() const;
PJRT_Memory* c_memory() const { return c_memory_; }
private:
friend class PjRtCApiClient;
PjRtCApiClient* client_;
PJRT_Memory* c_memory_;
std::vector<PjRtDevice*> devices_;
};
class PjRtCApiDevice : public PjRtDevice {
public:
explicit PjRtCApiDevice(PJRT_Device* device, PjRtCApiClient* client);
PjRtClient* client() const override;
bool IsAddressable() const override;
int local_hardware_id() const override;
PjRtLocalHardwareId local_hardware_id_typed() const override;
absl::Status TransferToInfeed(const LiteralSlice& literal) override {
return Unimplemented(
"PJRT C API does not support TransferToInfeed. Please report an issue "
"at https:
}
absl::Status TransferFromOutfeed(MutableBorrowingLiteral literal) override {
return Unimplemented(
"PJRT C API does not support TransferFromOutfeed. Please report an "
"issue at https:
"feature.");
}
absl::Span<PjRtMemorySpace* const> memory_spaces() const override {
return memory_spaces_;
}
absl::StatusOr<PjRtMemorySpace*> default_memory_space() const override;
std::unique_ptr<ScopedAsyncTrackingEvent> CreateAsyncTrackingEvent(
absl::string_view description) const override {
LOG(FATAL)
<< "PJRT C API does not support CreateAsyncTrackingEvent. Please "
"report an issue at https:
"need this feature.";
return nullptr;
}
PJRT_Device* c_device() const { return device_; }
const PjRtCApiDeviceDescription& description() const override {
return description_;
}
absl::StatusOr<tsl::AllocatorStats> GetAllocatorStats() const override;
absl::StatusOr<std::intptr_t> GetStreamForExternalReadyEvents()
const override;
private:
friend class PjRtCApiClient;
PjRtCApiClient* client_ = nullptr;
PJRT_Device* device_;
PjRtCApiDeviceDescription description_;
std::vector<PjRtMemorySpace*> memory_spaces_;
};
class PjRtCApiCompiler : public PjRtCompiler {
public:
explicit PjRtCApiCompiler(const PJRT_Api* c_api) : c_api_(c_api) {}
absl::StatusOr<std::unique_ptr<PjRtExecutable>> Compile(
CompileOptions options, const XlaComputation& computation,
const PjRtTopologyDescription& topology, PjRtClient* client) override;
absl::StatusOr<std::unique_ptr<PjRtExecutable>> Compile(
CompileOptions options, mlir::ModuleOp module,
const PjRtTopologyDescription& topology, PjRtClient* client) override;
private:
const PJRT_Api* c_api_;
};
class PjRtCApiTopologyDescription : public PjRtTopologyDescription {
public:
PjRtCApiTopologyDescription(const PJRT_Api* c_api,
PJRT_TopologyDescription* c_topology, bool owned);
PjRtPlatformId platform_id() const override {
CHECK(false) << "PJRT C API does not support platform_id.";
}
absl::string_view platform_name() const override;
absl::string_view platform_version() const override;
std::optional<PjRtCompiler*> compiler() const override {
return compiler_.get();
}
PJRT_TopologyDescription* c_topology() const { return c_topology_; }
std::vector<std::unique_ptr<const PjRtDeviceDescription>> DeviceDescriptions()
const override;
absl::StatusOr<std::string> Serialize() const override;
const absl::flat_hash_map<std::string, PjRtDeviceAttribute>& Attributes()
const override {
return attributes_;
}
absl::StatusOr<Layout> GetDefaultLayout(
PrimitiveType element_type,
absl::Span<const int64_t> dims) const override {
return Unimplemented("PJRT C API does not support GetDefaultLayout");
}
private:
std::unique_ptr<PjRtCApiCompiler> compiler_;
const PJRT_Api* c_api_;
std::unique_ptr<PJRT_TopologyDescription,
::pjrt::PJRT_TopologyDescriptionDeleter>
owned_c_topology_;
PJRT_TopologyDescription* c_topology_;
absl::flat_hash_map<std::string, xla::PjRtDeviceAttribute> attributes_;
void InitAttributes();
};
class PjRtCApiClient : public PjRtClient {
public:
PjRtCApiClient(
const PJRT_Api* c_api, PJRT_Client* c_client,
std::unique_ptr<::pjrt::PJRT_KeyValueCallbackData> kv_callback_data);
int process_index() const override;
int device_count() const override;
int addressable_device_count() const override;
absl::Span<PjRtDevice* const> devices() const override;
absl::Span<PjRtDevice* const> addressable_devices() const override;
absl::StatusOr<PjRtDevice*> LookupDevice(
PjRtGlobalDeviceId global_device_id) const override;
absl::StatusOr<PjRtDevice*> LookupAddressableDevice(
PjRtLocalDeviceId local_device_id) const override;
absl::Span<PjRtMemorySpace* const> memory_spaces() const override;
PjRtPlatformId platform_id() const override { return platform_id_; }
absl::string_view platform_name() const override { return platform_name_; };
absl::string_view platform_version() const override;
std::optional<PjRtPluginAttributes> plugin_attributes() const override;
PjRtRuntimeType runtime_type() const override {
return PjRtRuntimeType::kTfrt;
}
absl::StatusOr<DeviceAssignment> GetDefaultDeviceAssignment(
int num_replicas, int num_partitions) const override;
absl::StatusOr<std::unique_ptr<HloCostAnalysis>> GetHloCostAnalysis()
const override {
return Unimplemented(
"PJRT C API does not support GetHloCostAnalysis. Please report an "
"issue at https:
"feature.");
}
absl::StatusOr<Layout> GetDefaultLayout(
PrimitiveType element_type, absl::Span<const int64_t> dims) override;
absl::StatusOr<std::unique_ptr<PjRtLoadedExecutable>> Compile(
const XlaComputation& computation, CompileOptions options) override;
absl::StatusOr<std::unique_ptr<PjRtLoadedExecutable>> Compile(
mlir::ModuleOp module, CompileOptions options) override;
absl::StatusOr<std::unique_ptr<PjRtLoadedExecutable>> DeserializeExecutable(
absl::string_view serialized,
std::optional<CompileOptions> options) override;
absl::StatusOr<std::unique_ptr<PjRtBuffer>> CreateUninitializedBuffer(
const Shape& shape, PjRtDevice* device) override {
return Unimplemented(
"PJRT C API does not support CreateUninitializedBuffer. Please report "
"an issue at https:
"feature.");
}
absl::StatusOr<const PjRtTopologyDescription*> GetTopologyDescription()
const override;
absl::StatusOr<std::unique_ptr<AsyncHostToDeviceTransferManager>>
CreateBuffersForAsyncHostToDevice(absl::Span<const Shape> shapes,
PjRtDevice* device) override {
return Unimplemented(
"PJRT C API does not support CreateBuffersForAsyncHostToDevice. Please "
"report an issue at https:
"this feature.");
}
absl::StatusOr<std::unique_ptr<PjRtClient::AsyncHostToDeviceTransferManager>>
CreateBuffersForAsyncHostToDevice(absl::Span<const Shape> shapes,
PjRtMemorySpace* memory_space) override {
return Unimplemented(
"PJRT C API does not support CreateBuffersForAsyncHostToDevice. Please "
"report an issue at https:
"this feature.");
}
absl::StatusOr<std::unique_ptr<PjRtBuffer>> BufferFromHostBuffer(
const void* data, PrimitiveType type, absl::Span<int64_t const> dims,
std::optional<absl::Span<int64_t const>> byte_strides,
HostBufferSemantics host_buffer_semantics,
absl::AnyInvocable<void() &&> on_done_with_host_buffer,
PjRtDevice* device) override;
absl::StatusOr<std::unique_ptr<PjRtBuffer>> BufferFromHostBuffer(
const void* data, PrimitiveType type, absl::Span<int64_t const> dims,
std::optional<absl::Span<int64_t const>> byte_strides,
HostBufferSemantics host_buffer_semantics,
absl::AnyInvocable<void() &&> on_done_with_host_buffer,
PjRtDevice* device, const Layout* device_layout) override;
absl::StatusOr<std::unique_ptr<PjRtBuffer>> BufferFromHostBuffer(
const void* data, PrimitiveType type, absl::Span<int64_t const> dims,
std::optional<absl::Span<int64_t const>> byte_strides,
HostBufferSemantics host_buffer_semantics,
absl::AnyInvocable<void() &&> on_done_with_host_buffer,
PjRtMemorySpace* memory_space, const Layout* device_layout) override;
absl::StatusOr<std::unique_ptr<PjRtBuffer>> BufferFromHostLiteral(
const LiteralSlice& literal, PjRtDevice* device) override {
return Unimplemented(
"PJRT C API does not support BufferFromHostLiteral. Please report an "
"issue at https:
"feature.");
}
absl::StatusOr<std::unique_ptr<PjRtBuffer>> CreateViewOfDeviceBuffer(
void* device_ptr, const Shape& shape, PjRtDevice* device,
std::function<void()> on_delete_callback,
std::optional<std::intptr_t> stream) override;
absl::StatusOr<std::uintptr_t> UnsafeBufferPointer(
PjRtBuffer* buffer) override;
absl::StatusOr<std::vector<std::unique_ptr<PjRtBuffer>>>
MakeCrossHostReceiveBuffers(absl::Span<const Shape> shapes,
PjRtDevice* device,
PjRtCrossHostRecvNotifier notifier) override {
return Unimplemented(
"PJRT C API does not support MakeCrossHostReceiveBuffers. Please "
"report an issue at https:
"this feature.");
}
absl::StatusOr<std::vector<std::unique_ptr<PjRtBuffer>>>
MakeCrossHostReceiveBuffersForGather(
absl::Span<const Shape> shapes, std::vector<GatherDetails> gather_details,
PjRtDevice* device, PjRtCrossHostRecvNotifier notifier) override {
return Unimplemented(
"PJRT C API does not support MakeCrossHostReceiveBuffers. Please "
"report an issue at https:
"this feature.");
}
absl::StatusOr<ChannelHandle> CreateChannelHandle() override {
return Unimplemented(
"PJRT C API does not support CreateChannelHandle. Please report an "
"issue at https:
"feature.");
}
absl::StatusOr<ChannelHandle> CreateDeviceToHostChannelHandle() override {
return Unimplemented(
"PJRT C API does not support CreateDeviceToHostChannelHandle. Please "
"report an issue at https:
"this feature.");
}
absl::StatusOr<ChannelHandle> CreateHostToDeviceChannelHandle() override {
return Unimplemented(
"PJRT C API does not support CreateHostToDeviceChannelHandle. Please "
"report an issue at https:
"this feature.");
}
absl::Status Defragment() override {
return Unimplemented(
"PJRT C API does not support Defragment. Please report an issue at "
"https:
}
bool SupportsSendRecvCallbacks() const override { return true; }
const PJRT_Api* pjrt_c_api() const;
PJRT_Client* pjrt_c_client() { return c_client_.get(); }
PjRtCApiDevice* GetCppDevice(PJRT_Device* c_device) const {
auto it = c_to_cpp_device_map_.find(c_device);
CHECK(it != c_to_cpp_device_map_.end());
return it->second;
}
PjRtCApiMemorySpace* GetCppMemory(PJRT_Memory* c_memory) const {
auto it = c_to_cpp_memory_map_.find(c_memory);
CHECK(it != c_to_cpp_memory_map_.end());
return it->second;
}
PjRtHostMemoryForDeviceManager* GetPjRtHostMemoryForDeviceManager()
const override {
return nullptr;
}
private:
void InitDevicesAndMemorySpaces();
void InitAttributes();
absl::StatusOr<std::unique_ptr<PjRtBuffer>> BufferFromHostBufferInternalImpl(
const void* data, PrimitiveType type, absl::Span<int64_t const> dims,
std::optional<absl::Span<int64_t const>> byte_strides,
HostBufferSemantics host_buffer_semantics,
absl::AnyInvocable<void() &&> on_done_with_host_buffer,
std::variant<PjRtDevice*, PjRtMemorySpace*> device_or_memory,
const Layout* device_layout);
const PJRT_Api* c_api_;
std::unique_ptr<PJRT_Client, ::pjrt::PJRT_ClientDeleter> c_client_;
std::unique_ptr<::pjrt::PJRT_KeyValueCallbackData> kv_callback_data_;
std::vector<std::unique_ptr<PjRtCApiDevice>> owned_devices_;
std::vector<PjRtDevice*> devices_;
std::vector<PjRtDevice*> addressable_devices_;
absl::flat_hash_map<PJRT_Device*, PjRtCApiDevice*> c_to_cpp_device_map_;
std::vector<std::unique_ptr<PjRtCApiMemorySpace>> owned_memory_spaces_;
std::vector<PjRtMemorySpace*> addressable_memory_spaces_;
absl::flat_hash_map<PJRT_Memory*, PjRtCApiMemorySpace*> c_to_cpp_memory_map_;
absl::StatusOr<const PjRtCApiTopologyDescription> topo_desc_;
const std::string platform_version_;
const std::string platform_name_;
const PjRtPlatformId platform_id_;
absl::flat_hash_map<std::string, xla::PjRtValueType> attributes_;
};
class PjRtCApiBuffer : public PjRtBuffer {
public:
PjRtCApiBuffer(PjRtCApiClient* client, PJRT_Buffer* buffer);
PrimitiveType element_type() const override;
absl::Span<const int64_t> dimensions() const override;
std::unique_ptr<PjRtLayout> layout() const override;
bool IsTuple() const override { return false; }
const Shape& on_device_shape() const override {
LOG(FATAL) << "PjRtBuffer::on_device_shape() not implemented in PJRT C API";
}
bool has_dynamic_dimensions() const override;
absl::Span<const bool> is_dynamic_dimension() const override;
absl::StatusOr<std::vector<int64_t>> logical_dimensions() override;
absl::StatusOr<Shape> logical_on_device_shape() override {
LOG(FATAL) << "PjRtBuffer::on_logical_device_shape() not implemented in "
"PJRT C API";
}
PjRtMemorySpace* memory_space() const override;
PjRtDevice* device() const override;
PjRtClient* client() const override { return client_; }
absl::StatusOr<std::unique_ptr<ExternalReference>> AcquireExternalReference()
override;
PjRtFuture<> ToLiteral(MutableLiteralBase* literal) override;
PjRtFuture<> LazyToLiteral(
absl::AnyInvocable<absl::StatusOr<MutableLiteralBase*>() &&> generator)
override;
absl::StatusOr<size_t> GetOnDeviceSizeInBytes() const override;
PjRtFuture<> CopyRawToHost(void* dst, int64_t offset,
int64_t transfer_size) override {
return PjRtFuture<>(Unimplemented(
"PJRT C API does not support CopyRawToHost. Please report an issue at "
"https:
}
void Delete() override;
absl::StatusOr<std::unique_ptr<ExternalReference>>
ReleaseDeviceMemoryOwnership(bool wait_for_operations_to_complete) override {
return Unimplemented(
"PJRT C API does not support ReleaseDeviceMemoryOwnership");
}
bool IsDeleted() override;
absl::StatusOr<std::unique_ptr<PjRtBuffer>> CopyToDevice(
PjRtDevice* dst_device) override;
absl::StatusOr<std::unique_ptr<PjRtBuffer>> CopyToMemorySpace(
PjRtMemorySpace* dst_memory_space) override;
void CopyToRemoteDevice(PjRtFuture<std::string> serialized_descriptor,
RemoteSendCallback on_done) override {
LOG(ERROR) << "PJRT C API does not support CopyToRemoteDevice. Please "
"report an issue at https:
"you need this feature.";
}
void CopyToRemoteDeviceScattered(
PjRtFuture<std::vector<std::string>> serialized_descriptors,
std::vector<RemoteSendCallback> callbacks,
const ScatterDetails& scatter_details) override {
LOG(ERROR)
<< "PJRT C API does not support CopyToRemoteDeviceScattered. Please "
"report an issue at https:
"need this feature.";
}
PjRtFuture<> GetReadyFuture() override;
bool IsOnCpu() const override;
PJRT_Buffer* c_buffer() const { return buffer_.get(); }
const PJRT_Api* pjrt_c_api() const { return client_->pjrt_c_api(); }
private:
PJRT_Event* GetReadyEvent();
void MakePromiseTrackEvent();
PjRtCApiClient* client_;
std::unique_ptr<PJRT_Buffer, ::pjrt::PJRT_BufferDeleter> buffer_;
std::unique_ptr<PJRT_Event, ::pjrt::PJRT_EventDeleter> readiness_event_;
std::shared_ptr<PjRtFuture<>::Promise> readiness_promise_;
mutable std::optional<PjRtXlaLayout> layout_;
mutable std::optional<absl::InlinedVector<bool, InlineRank()>>
is_dynamic_dimension_;
mutable absl::Mutex mu_;
};
class PjRtCApiExternalReference : public PjRtBuffer::ExternalReference {
public:
PjRtCApiExternalReference(PjRtCApiClient* client, PjRtCApiBuffer* buffer,
void* data_ptr)
: client_(client), buffer_(buffer) {
data_ptr_ = data_ptr;
}
~PjRtCApiExternalReference() override;
absl::Status WaitUntilBufferReadyOnStream(std::intptr_t stream) override;
private:
PjRtCApiClient* client_;
PjRtCApiBuffer* buffer_;
};
class PjRtCApiExecutable : public PjRtExecutable {
public:
PjRtCApiExecutable(const PJRT_Api* c_api, PJRT_Executable* executable);
absl::string_view name() const override;
int num_replicas() const override;
int num_partitions() const override;
int64_t SizeOfGeneratedCodeInBytes() const override;
absl::StatusOr<absl::flat_hash_map<std::string, PjRtValueType>>
GetCostAnalysis() const override;
absl::StatusOr<std::vector<std::shared_ptr<HloModule>>> GetHloModules()
const override;
absl::StatusOr<CompiledMemoryStats> GetCompiledMemoryStats() const override {
return pjrt::GetCompiledMemoryStats(c_api_, executable_.get());
}
absl::StatusOr<std::vector<Shape>> GetOutputShapes() const override {
LOG(FATAL) << "PjRtExecutable::GetOutputShapes() not implemented in PJRT C "
"API. Please use PjRtExecutable::GetOutputElementTypes() or "
"PjRtExecutable::GetOutputDimensions().";
}
absl::StatusOr<std::vector<std::vector<PrimitiveType>>>
GetOutputElementTypes() const override;
absl::StatusOr<std::vector<std::vector<DimensionVector>>>
GetOutputDimensions() const override;
absl::StatusOr<std::vector<std::vector<absl::string_view>>>
GetOutputMemoryKinds() const override;
const PJRT_Api* pjrt_c_api() const { return c_api_; }
PJRT_Executable* c_executable() const { return executable_.get(); }
absl::StatusOr<std::string> SerializeExecutable() const override;
absl::StatusOr<std::string> FingerprintExecutable() const override;
private:
const PJRT_Api* c_api_;
std::unique_ptr<PJRT_Executable, ::pjrt::PJRT_ExecutableDeleter> executable_;
};
class PjRtCApiLoadedExecutable : public PjRtLoadedExecutable {
public:
PjRtCApiLoadedExecutable(PjRtCApiClient* client,
PJRT_LoadedExecutable* executable);
PjRtClient* client() const override { return client_; }
absl::string_view name() const override { return executable_->name(); }
int num_replicas() const override { return executable_->num_replicas(); }
int num_partitions() const override { return executable_->num_partitions(); }
int64_t SizeOfGeneratedCodeInBytes() const override {
return executable_->SizeOfGeneratedCodeInBytes();
}
absl::StatusOr<absl::flat_hash_map<std::string, PjRtValueType>>
GetCostAnalysis() const override {
return executable_->GetCostAnalysis();
}
const DeviceAssignment& device_assignment() const override {
CHECK(false) << "PJRT C API does not support device_assignment";
}
absl::Span<const LogicalDeviceIds> addressable_device_logical_ids()
const override {
CHECK(false)
<< "PJRT C API does not support addressable_device_logical_ids";
}
absl::Span<PjRtDevice* const> addressable_devices() const override {
return addressable_devices_;
}
absl::StatusOr<std::vector<std::shared_ptr<HloModule>>> GetHloModules()
const override {
return executable_->GetHloModules();
}
absl::StatusOr<CompiledMemoryStats> GetCompiledMemoryStats() const override {
return executable_->GetCompiledMemoryStats();
}
absl::StatusOr<std::vector<Shape>> GetOutputShapes() const override {
LOG(FATAL)
<< "PjRtLoadedExecutable::GetOutputShapes() not implemented in PJRT C "
"API. Please use PjRtLoadedExecutable::GetOutputElementTypes() or "
"PjRtLoadedExecutable::GetOutputDimensions().";
}
absl::StatusOr<std::vector<std::vector<PrimitiveType>>>
GetOutputElementTypes() const override {
return executable_->GetOutputElementTypes();
}
absl::StatusOr<std::vector<std::vector<DimensionVector>>>
GetOutputDimensions() const override {
return executable_->GetOutputDimensions();
}
absl::StatusOr<std::vector<std::vector<absl::string_view>>>
GetOutputMemoryKinds() const override {
return executable_->GetOutputMemoryKinds();
}
absl::StatusOr<std::vector<std::vector<std::unique_ptr<PjRtBuffer>>>> Execute(
absl::Span<const std::vector<PjRtBuffer*>> argument_handles,
const ExecuteOptions& options,
std::optional<std::vector<PjRtFuture<>>>& returned_futures) override;
absl::StatusOr<std::vector<std::unique_ptr<PjRtBuffer>>> ExecuteSharded(
absl::Span<PjRtBuffer* const> argument_handles, PjRtDevice* device,
const ExecuteOptions& options,
std::optional<PjRtFuture<>>& returned_future, bool fill_future) override;
absl::StatusOr<std::vector<std::unique_ptr<PjRtBuffer>>> ExecutePortable(
absl::Span<PjRtBuffer* const> argument_handles, PjRtDevice* device,
const ExecuteOptions& options,
std::optional<PjRtFuture<>>& returned_future, bool fill_future) override;
void Delete() override;
bool IsDeleted() override;
absl::StatusOr<std::string> SerializeExecutable() const override {
return executable_->SerializeExecutable();
}
const PJRT_Api* pjrt_c_api() const { return client_->pjrt_c_api(); }
PJRT_Executable* c_executable() const { return executable_->c_executable(); }
PJRT_LoadedExecutable* c_loaded_executable() const {
return loaded_executable_.get();
}
bool IsReturnedFutureSupported() const override { return true; }
using SendCallbackFunction = std::function<PJRT_Error*(
PJRT_Chunk*, PJRT_CallbackError*, size_t, bool)>;
using RecvCallbackFunction = std::function<void(PJRT_CopyToDeviceStream*)>;
absl::StatusOr<std::string> FingerprintExecutable() const override;
private:
struct SendRecvCallbackData {
std::vector<std::vector<PJRT_SendCallbackInfo>> c_send_callbacks;
std::vector<PJRT_SendCallbackInfo*> c_send_callback_lists;
std::vector<std::vector<PJRT_RecvCallbackInfo>> c_recv_callbacks;
std::vector<PJRT_RecvCallbackInfo*> c_recv_callback_lists;
std::vector<SendCallbackFunction> send_callback_functions;
std::vector<RecvCallbackFunction> recv_callback_functions;
};
absl::StatusOr<PJRT_LoadedExecutable_Execute_Args> GetCommonExecuteArgs(
absl::Span<const std::vector<PjRtBuffer*>> argument_handles,
const ExecuteOptions& options, PJRT_ExecuteOptions& c_options,
std::vector<std::vector<PJRT_Buffer*>>& c_argument_lists_storage,
std::vector<PJRT_Buffer**>& c_arguments,
std::vector<std::vector<PJRT_Buffer*>>& c_output_lists_storage,
std::vector<PJRT_Buffer**>& c_output_lists,
std::optional<std::vector<PJRT_Event*>>& device_complete_events,
SendRecvCallbackData& send_recv_callback_data,
std::vector<int64_t>& non_donatable_input_indices_storage);
absl::StatusOr<std::vector<std::unique_ptr<PjRtBuffer>>>
ExecuteWithSingleDevice(absl::Span<PjRtBuffer* const> argument_handles,
PjRtDevice* device, const ExecuteOptions& options,
std::optional<PjRtFuture<>>& returned_future,
bool fill_future);
PjRtCApiClient* client_;
std::unique_ptr<PJRT_LoadedExecutable, ::pjrt::PJRT_LoadedExecutableDeleter>
loaded_executable_;
std::unique_ptr<PjRtCApiExecutable> executable_;
std::vector<PjRtDevice*> addressable_devices_;
void InitDevices();
};
class CApiCopyToDeviceStream : public CopyToDeviceStream {
public:
CApiCopyToDeviceStream(PJRT_CopyToDeviceStream* c_stream,
const PJRT_Api* c_api);
~CApiCopyToDeviceStream() override;
PjRtFuture<> AddChunk(PjRtChunk chunk) override;
private:
PJRT_CopyToDeviceStream* c_stream_;
const PJRT_Api* c_api_;
};
absl::StatusOr<std::unique_ptr<PjRtClient>> GetCApiClient(
absl::string_view device_type,
const absl::flat_hash_map<std::string, PjRtValueType>& create_options = {},
std::shared_ptr<KeyValueStoreInterface> kv_store = nullptr);
absl::StatusOr<std::unique_ptr<PjRtTopologyDescription>> GetCApiTopology(
const PJRT_Api* c_api, absl::string_view topology_name,
const absl::flat_hash_map<std::string, PjRtValueType>& create_options);
absl::StatusOr<std::unique_ptr<PjRtTopologyDescription>> GetCApiTopology(
absl::string_view device_type, absl::string_view topology_name,
const absl::flat_hash_map<std::string, PjRtValueType>& create_options = {});
}
#endif
#include "xla/pjrt/pjrt_c_api_client.h"
#include <cstddef>
#include <cstdint>
#include <functional>
#include <memory>
#include <optional>
#include <string>
#include <utility>
#include <variant>
#include <vector>
#include "absl/cleanup/cleanup.h"
#include "absl/container/flat_hash_map.h"
#include "absl/container/inlined_vector.h"
#include "absl/functional/any_invocable.h"
#include "absl/log/check.h"
#include "absl/log/log.h"
#include "absl/status/s | #include "xla/pjrt/pjrt_c_api_client.h"
#include <cstdint>
#include <memory>
#include <optional>
#include <string>
#include <utility>
#include <vector>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "absl/status/status.h"
#include "xla/client/xla_builder.h"
#include "xla/literal_util.h"
#include "xla/pjrt/c/pjrt_c_api_cpu_internal.h"
#include "xla/pjrt/pjrt_api.h"
#include "xla/pjrt/pjrt_client.h"
#include "xla/pjrt/pjrt_compiler.h"
#include "xla/pjrt/pjrt_executable.h"
#include "xla/shape.h"
#include "xla/shape_util.h"
#include "xla/tests/literal_test_util.h"
#include "tsl/lib/core/status_test_util.h"
#include "tsl/platform/statusor.h"
#include "tsl/platform/test.h"
namespace xla {
namespace {
static void SetUpCpuPjRtApi() {
std::string device_type = "cpu";
auto status = ::pjrt::PjrtApi(device_type);
if (!status.ok()) {
TF_ASSERT_OK(
pjrt::SetPjrtApi(device_type, ::pjrt::cpu_plugin::GetCpuPjrtApi()));
}
}
TEST(PjRtCApiClientTest, IsDynamicDimension) {
SetUpCpuPjRtApi();
TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<PjRtClient> client,
GetCApiClient("cpu"));
std::vector<int32_t> data0{1, 2, 3, 4, 5, 6};
Shape shape0 = ShapeUtil::MakeShape(S32, {2, 3});
TF_ASSERT_OK_AND_ASSIGN(
auto param0,
client->BufferFromHostBuffer(
data0.data(), shape0.element_type(), shape0.dimensions(),
std::nullopt,
PjRtClient::HostBufferSemantics::kImmutableOnlyDuringCall, nullptr,
client->addressable_devices()[0]));
std::vector<int32_t> data1{2};
Shape shape1 = ShapeUtil::MakeShape(S32, {});
TF_ASSERT_OK_AND_ASSIGN(
auto param1,
client->BufferFromHostBuffer(
data1.data(), shape1.element_type(), shape1.dimensions(),
std::nullopt,
PjRtClient::HostBufferSemantics::kImmutableOnlyDuringCall, nullptr,
client->addressable_devices()[0]));
XlaBuilder builder("DynamicReshape");
auto inp_0 = Parameter(&builder, 0, shape0, "input0");
auto inp_1 = Parameter(&builder, 1, shape1, "input1");
std::vector<bool> dims_are_dynamic = {false, true};
auto reshaped =
DynamicReshape(inp_0, {inp_1, inp_1}, {2, 3}, dims_are_dynamic);
auto computation = builder.Build(reshaped).value();
std::unique_ptr<PjRtLoadedExecutable> executable =
client->Compile(computation, CompileOptions()).value();
ExecuteOptions execute_options;
execute_options.non_donatable_input_indices = {0};
std::vector<std::vector<std::unique_ptr<PjRtBuffer>>> results =
executable->Execute({{param0.get(), param1.get()}}, execute_options)
.value();
ASSERT_EQ(results[0].size(), 1);
auto* result_buffer = results[0][0].get();
auto is_dynamic_dimension = result_buffer->is_dynamic_dimension();
EXPECT_THAT(is_dynamic_dimension,
::testing::ElementsAreArray(dims_are_dynamic));
}
TEST(PjRtCApiClientTest, PlatformId) {
SetUpCpuPjRtApi();
TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<PjRtClient> client,
GetCApiClient("cpu"));
EXPECT_EQ(client->platform_name(), xla::CpuName());
EXPECT_EQ(client->platform_id(), xla::CpuId());
}
TEST(PjRtCApiClientTest, EmptyExecutableFingerprint) {
SetUpCpuPjRtApi();
TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<PjRtClient> client,
GetCApiClient("cpu"));
Shape shape = ShapeUtil::MakeShapeWithType<float>({4});
XlaBuilder builder("sum");
auto inp_0 = Parameter(&builder, 0, shape, "input0");
auto inp_1 = Parameter(&builder, 1, shape, "input1");
auto sum = Add(inp_0, inp_1);
builder.SetUpAlias({}, 0, {});
auto computation = builder.Build(sum).value();
std::unique_ptr<PjRtLoadedExecutable> executable =
client->Compile(computation, CompileOptions()).value();
PjRtCApiClient* c_client = dynamic_cast<PjRtCApiClient*>(client.get());
ASSERT_NE(c_client, nullptr);
if (c_client->pjrt_c_api()->pjrt_api_version.minor_version >= 35) {
EXPECT_FALSE(executable->FingerprintExecutable().ok());
} else {
EXPECT_EQ(executable->FingerprintExecutable().status().code(),
absl::StatusCode::kUnimplemented);
}
}
TEST(PjRtClientTest, CreateViewAndCopyToDeviceAsyncExternalCpuOnly) {
SetUpCpuPjRtApi();
TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<PjRtClient> client,
GetCApiClient("cpu"));
ASSERT_GT(client->addressable_devices().size(), 1);
std::vector<int32_t> data(4, 0);
auto* data_ptr = data.data();
Shape shape = ShapeUtil::MakeShape(S32, {4});
TF_ASSERT_OK_AND_ASSIGN(
auto buffer,
client->CreateViewOfDeviceBuffer(
data_ptr, shape, client->addressable_devices()[0],
[data = std::move(data)]() mutable {}));
TF_ASSERT_OK_AND_ASSIGN(
std::unique_ptr<PjRtBuffer> result,
buffer->CopyToDevice(client->addressable_devices()[1]));
buffer.reset();
ASSERT_TRUE(result);
TF_ASSERT_OK_AND_ASSIGN(auto literal, result->ToLiteralSync());
std::vector<int32_t> expected(4, 0);
EXPECT_TRUE(LiteralTestUtil::Equal(LiteralUtil::CreateR1<int32_t>(expected),
*literal));
}
}
} | 2,207 |
#ifndef XLA_PJRT_TF_PJRT_CLIENT_H_
#define XLA_PJRT_TF_PJRT_CLIENT_H_
#include <functional>
#include <memory>
#include <optional>
#include <string>
#include <utility>
#include <vector>
#include "absl/base/thread_annotations.h"
#include "absl/container/flat_hash_map.h"
#include "absl/container/flat_hash_set.h"
#include "absl/synchronization/mutex.h"
#include "xla/pjrt/pjrt_client.h"
#include "xla/pjrt/pjrt_future.h"
#include "tsl/platform/errors.h"
namespace xla {
class TfPjRtClient;
class TfPjRtBuffer : public PjRtBuffer {
public:
TfPjRtBuffer(TfPjRtClient* client, std::unique_ptr<PjRtBuffer> wrapped);
~TfPjRtBuffer() override;
PjRtBuffer* wrapped() const { return wrapped_.get(); }
const Shape& on_device_shape() const override {
return wrapped_->on_device_shape();
}
absl::StatusOr<Shape> logical_on_device_shape() override {
return wrapped_->logical_on_device_shape();
}
PjRtMemorySpace* memory_space() const override {
return wrapped_->memory_space();
}
PjRtDevice* device() const override { return wrapped_->device(); }
PjRtClient* client() const override;
absl::StatusOr<std::unique_ptr<ExternalReference>> AcquireExternalReference()
override {
return wrapped_->AcquireExternalReference();
}
PjRtFuture<> ToLiteral(MutableLiteralBase* literal) override {
return wrapped_->ToLiteral(literal);
}
PjRtFuture<> LazyToLiteral(
absl::AnyInvocable<absl::StatusOr<MutableLiteralBase*>() &&> generator)
override {
return wrapped_->LazyToLiteral(std::move(generator));
}
absl::StatusOr<size_t> GetOnDeviceSizeInBytes() const override {
return wrapped_->GetOnDeviceSizeInBytes();
}
PjRtFuture<> CopyRawToHost(void* dst, int64_t offset,
int64_t transfer_size) override {
return wrapped_->CopyRawToHost(dst, offset, transfer_size);
}
void Delete() override { wrapped_->Delete(); }
absl::StatusOr<std::unique_ptr<ExternalReference>>
ReleaseDeviceMemoryOwnership(bool wait_for_operations_to_complete) override {
return wrapped_->ReleaseDeviceMemoryOwnership(
wait_for_operations_to_complete);
}
bool IsDeleted() override { return wrapped_->IsDeleted(); }
absl::StatusOr<std::unique_ptr<PjRtBuffer>> CopyToDevice(
PjRtDevice* dst_device) override;
absl::StatusOr<std::unique_ptr<PjRtBuffer>> CopyToMemorySpace(
PjRtMemorySpace* dst_memory_space) override {
return Unimplemented("CopyToMemorySpace not implemented");
}
void CopyToRemoteDevice(PjRtFuture<std::string> serialized_descriptor,
RemoteSendCallback on_done) override {
wrapped_->CopyToRemoteDevice(std::move(serialized_descriptor),
std::move(on_done));
}
void CopyToRemoteDeviceScattered(
PjRtFuture<std::vector<std::string>> serialized_descriptors,
std::vector<RemoteSendCallback> callbacks,
const ScatterDetails& scatter_details) override {
return wrapped_->CopyToRemoteDeviceScattered(
std::move(serialized_descriptors), std::move(callbacks),
scatter_details);
}
PjRtFuture<> GetReadyFuture() override { return wrapped_->GetReadyFuture(); }
bool IsOnCpu() const override { return wrapped_->IsOnCpu(); }
void DestroyWrappedBuffer() { wrapped_.reset(nullptr); }
private:
TfPjRtClient* client_;
std::unique_ptr<PjRtBuffer> wrapped_;
};
class TfPjRtExecutable : public PjRtLoadedExecutable {
public:
TfPjRtExecutable(TfPjRtClient* client,
std::unique_ptr<PjRtLoadedExecutable> wrapped);
PjRtLoadedExecutable* wrapped() const { return wrapped_.get(); }
PjRtClient* client() const override;
absl::string_view name() const override { return wrapped_->name(); }
int num_replicas() const override { return wrapped_->num_replicas(); }
int num_partitions() const override { return wrapped_->num_partitions(); }
int64_t SizeOfGeneratedCodeInBytes() const override {
return wrapped_->SizeOfGeneratedCodeInBytes();
}
const DeviceAssignment& device_assignment() const override {
return wrapped_->device_assignment();
}
absl::Span<const LogicalDeviceIds> addressable_device_logical_ids()
const override {
return wrapped_->addressable_device_logical_ids();
}
absl::Span<PjRtDevice* const> addressable_devices() const override {
return wrapped_->addressable_devices();
}
absl::StatusOr<std::vector<std::shared_ptr<HloModule>>> GetHloModules()
const override {
return wrapped_->GetHloModules();
}
absl::StatusOr<std::vector<std::vector<absl::string_view>>>
GetOutputMemoryKinds() const override {
return wrapped_->GetOutputMemoryKinds();
}
using PjRtLoadedExecutable::Execute;
absl::StatusOr<std::vector<std::vector<std::unique_ptr<PjRtBuffer>>>> Execute(
absl::Span<const std::vector<PjRtBuffer*>> argument_handles,
const ExecuteOptions& options,
std::optional<std::vector<PjRtFuture<>>>& returned_futures) override;
using PjRtLoadedExecutable::ExecuteSharded;
absl::StatusOr<std::vector<std::unique_ptr<PjRtBuffer>>> ExecuteSharded(
absl::Span<PjRtBuffer* const> argument_handles, PjRtDevice* device,
const ExecuteOptions& options,
std::optional<PjRtFuture<>>& returned_future, bool fill_future) override;
using PjRtLoadedExecutable::ExecutePortable;
absl::StatusOr<std::vector<std::unique_ptr<PjRtBuffer>>> ExecutePortable(
absl::Span<PjRtBuffer* const> argument_handles, PjRtDevice* device,
const ExecuteOptions& options,
std::optional<PjRtFuture<>>& returned_future, bool fill_future) override;
void Delete() override { return wrapped_->Delete(); }
bool IsDeleted() override { return wrapped_->IsDeleted(); }
bool IsReturnedFutureSupported() const override {
return wrapped_->IsReturnedFutureSupported();
}
absl::StatusOr<std::string> SerializeExecutable() const override {
return wrapped_->SerializeExecutable();
}
absl::StatusOr<struct CompileOptions> GetCompileOptions() const override {
return wrapped_->GetCompileOptions();
}
absl::StatusOr<std::string> FingerprintExecutable() const override {
return wrapped_->FingerprintExecutable();
}
private:
TfPjRtClient* client_;
std::unique_ptr<PjRtLoadedExecutable> wrapped_;
};
class TfPjRtClient : public PjRtClient {
public:
static std::unique_ptr<TfPjRtClient> CreateTfPjRtClient(
std::unique_ptr<PjRtClient> wrapped);
explicit TfPjRtClient(std::unique_ptr<PjRtClient> wrapped);
~TfPjRtClient() override;
int process_index() const override { return wrapped_->process_index(); }
int device_count() const override { return wrapped_->device_count(); }
int addressable_device_count() const override {
return wrapped_->addressable_device_count();
}
absl::Span<PjRtDevice* const> devices() const override {
return wrapped_->devices();
}
absl::Span<PjRtDevice* const> addressable_devices() const override {
return wrapped_->addressable_devices();
}
absl::StatusOr<PjRtDevice*> LookupDevice(
PjRtGlobalDeviceId global_device_id) const override {
return wrapped_->LookupDevice(global_device_id);
}
absl::StatusOr<PjRtDevice*> LookupAddressableDevice(
PjRtLocalDeviceId local_device_id) const override {
if (wrapped_ == nullptr) {
return tsl::errors::Internal(
"Wrapped PJRT client in TfPjRtClient is already destroyed.");
}
return wrapped_->LookupAddressableDevice(local_device_id);
}
absl::Span<PjRtMemorySpace* const> memory_spaces() const override {
return wrapped_->memory_spaces();
}
PjRtPlatformId platform_id() const override {
return wrapped_->platform_id();
}
absl::string_view platform_name() const override {
return wrapped_->platform_name();
}
absl::string_view platform_version() const override {
return wrapped_->platform_version();
}
PjRtRuntimeType runtime_type() const override {
return wrapped_->runtime_type();
}
absl::StatusOr<DeviceAssignment> GetDefaultDeviceAssignment(
int num_replicas, int num_partitions) const override {
return wrapped_->GetDefaultDeviceAssignment(num_replicas, num_partitions);
}
absl::StatusOr<Layout> GetDefaultLayout(
PrimitiveType element_type, absl::Span<const int64_t> dims) override {
return wrapped_->GetDefaultLayout(element_type, dims);
}
absl::StatusOr<std::unique_ptr<HloCostAnalysis>> GetHloCostAnalysis()
const override {
return wrapped_->GetHloCostAnalysis();
}
absl::StatusOr<std::unique_ptr<PjRtLoadedExecutable>> Compile(
const XlaComputation& computation, CompileOptions options) override {
return WrapExecutable(wrapped_->Compile(computation, options));
}
absl::StatusOr<std::unique_ptr<PjRtLoadedExecutable>> Compile(
mlir::ModuleOp module, CompileOptions options) override {
return WrapExecutable(wrapped_->Compile(std::move(module), options));
}
absl::StatusOr<std::unique_ptr<PjRtLoadedExecutable>> DeserializeExecutable(
absl::string_view serialized,
std::optional<CompileOptions> options) override {
return WrapExecutable(wrapped_->DeserializeExecutable(serialized, options));
}
absl::StatusOr<std::unique_ptr<PjRtBuffer>> CreateUninitializedBuffer(
const Shape& shape, PjRtDevice* device) override {
return Unimplemented(
"CreateUninitializedBuffer not supported for TfPjRtClient.");
}
absl::StatusOr<std::unique_ptr<AsyncHostToDeviceTransferManager>>
CreateBuffersForAsyncHostToDevice(absl::Span<const Shape> shapes,
PjRtDevice* device) override {
return Unimplemented(
"AsyncHostToDeviceTransferManager not supported for Tf.");
}
absl::StatusOr<std::unique_ptr<AsyncHostToDeviceTransferManager>>
CreateBuffersForAsyncHostToDevice(absl::Span<const Shape> shapes,
PjRtMemorySpace* memory_space) override {
return Unimplemented(
"AsyncHostToDeviceTransferManager not supported for Tf.");
}
absl::StatusOr<std::unique_ptr<PjRtBuffer>> BufferFromHostBuffer(
const void* data, PrimitiveType type, absl::Span<int64_t const> dims,
std::optional<absl::Span<int64_t const>> byte_strides,
HostBufferSemantics host_buffer_semantics,
absl::AnyInvocable<void() &&> on_done_with_host_buffer,
PjRtDevice* device) override {
return WrapBuffer(wrapped_->BufferFromHostBuffer(
data, type, dims, byte_strides, host_buffer_semantics,
std::move(on_done_with_host_buffer), device));
}
absl::StatusOr<std::unique_ptr<PjRtBuffer>> BufferFromHostBuffer(
const void* data, PrimitiveType type, absl::Span<int64_t const> dims,
std::optional<absl::Span<int64_t const>> byte_strides,
HostBufferSemantics host_buffer_semantics,
absl::AnyInvocable<void() &&> on_done_with_host_buffer,
PjRtDevice* device, const Layout* device_layout) override {
return WrapBuffer(wrapped_->BufferFromHostBuffer(
data, type, dims, byte_strides, host_buffer_semantics,
std::move(on_done_with_host_buffer), device, device_layout));
}
absl::StatusOr<std::unique_ptr<PjRtBuffer>> BufferFromHostLiteral(
const LiteralSlice& literal, PjRtDevice* device) override {
return WrapBuffer(wrapped_->BufferFromHostLiteral(literal, device));
}
absl::StatusOr<std::unique_ptr<PjRtBuffer>> CreateViewOfDeviceBuffer(
void* device_ptr, const Shape& shape, PjRtDevice* device,
std::function<void()> on_delete_callback,
std::optional<std::intptr_t> stream) override {
return WrapBuffer(wrapped_->CreateViewOfDeviceBuffer(
device_ptr, shape, device, on_delete_callback, stream));
}
absl::StatusOr<std::uintptr_t> UnsafeBufferPointer(
PjRtBuffer* buffer) override {
return wrapped_->UnsafeBufferPointer(UnwrapBuffer(buffer));
}
absl::StatusOr<std::vector<std::unique_ptr<PjRtBuffer>>>
MakeCrossHostReceiveBuffers(absl::Span<const Shape> shapes,
PjRtDevice* device,
PjRtCrossHostRecvNotifier notifier) override {
return wrapped_->MakeCrossHostReceiveBuffers(shapes, device,
std::move(notifier));
}
absl::StatusOr<std::vector<std::unique_ptr<PjRtBuffer>>>
MakeCrossHostReceiveBuffersForGather(
absl::Span<const Shape> shapes, std::vector<GatherDetails> gather_details,
PjRtDevice* device, PjRtCrossHostRecvNotifier notifier) override {
return wrapped_->MakeCrossHostReceiveBuffersForGather(
shapes, std::move(gather_details), device, std::move(notifier));
}
absl::StatusOr<ChannelHandle> CreateChannelHandle() override {
return wrapped_->CreateChannelHandle();
}
absl::StatusOr<ChannelHandle> CreateDeviceToHostChannelHandle() override {
return wrapped_->CreateDeviceToHostChannelHandle();
}
absl::StatusOr<ChannelHandle> CreateHostToDeviceChannelHandle() override {
return wrapped_->CreateHostToDeviceChannelHandle();
}
absl::StatusOr<const PjRtTopologyDescription*> GetTopologyDescription()
const override {
return wrapped_->GetTopologyDescription();
}
absl::Status Defragment() override { return wrapped_->Defragment(); }
PjRtClient* wrapped() const { return wrapped_.get(); }
absl::StatusOr<std::unique_ptr<PjRtBuffer>> WrapBuffer(
absl::StatusOr<std::unique_ptr<PjRtBuffer>> to_wrap);
void TrackBuffer(TfPjRtBuffer* buffer);
void UntrackBuffer(const TfPjRtBuffer* buffer);
void DestroyWrappedBuffersAndClient();
private:
PjRtBuffer* UnwrapBuffer(PjRtBuffer* buffer) const {
return tensorflow::down_cast<TfPjRtBuffer*>(buffer)->wrapped();
}
const PjRtLoadedExecutable& UnwrapExecutable(
const PjRtLoadedExecutable& executable) const {
return *tensorflow::down_cast<const TfPjRtExecutable*>(&executable)
->wrapped();
}
absl::StatusOr<std::unique_ptr<PjRtLoadedExecutable>> WrapExecutable(
absl::StatusOr<std::unique_ptr<PjRtLoadedExecutable>> to_wrap);
std::unique_ptr<PjRtClient> wrapped_;
absl::flat_hash_map<int, int> mutex_id_from_device_id_;
struct DeviceBuffers {
absl::Mutex mu;
absl::flat_hash_set<TfPjRtBuffer*> alive_buffers ABSL_GUARDED_BY(mu);
};
std::vector<DeviceBuffers> alive_buffers_;
};
}
#endif
#include "xla/pjrt/tf_pjrt_client.h"
#include <memory>
#include <optional>
#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/synchronization/mutex.h"
#include "xla/pjrt/pjrt_client.h"
namespace xla {
TfPjRtBuffer::TfPjRtBuffer(TfPjRtClient* client,
std::unique_ptr<PjRtBuffer> wrapped)
: client_(client), wrapped_(std::move(wrapped)) {
client_->TrackBuffer(this);
}
TfPjRtBuffer::~TfPjRtBuffer() { client_->UntrackBuffer(this); }
PjRtClient* TfPjRtBuffer::client() const { return client_; }
PjRtClient* TfPjRtExecutable::client() const { return client_; }
absl::StatusOr<std::unique_ptr<PjRtBuffer>> TfPjRtBuffer::CopyToDevice(
PjRtDevice* dst_device) {
TF_ASSIGN_OR_RETURN(std::unique_ptr<PjRtBuffer> result,
wrapped_->CopyToDevice(dst_device));
return std::unique_ptr<PjRtBuffer>(
std::make_unique<TfPjRtBuffer>(client_, std::move(result)));
}
TfPjRtExecutable::TfPjRtExecutable(
TfPjRtClient* client, std::unique_ptr<PjRtLoadedExecutable> wrapped)
: client_(client), wrapped_(std::move(wrapped)) {}
absl::StatusOr<std::vector<std::vector<std::unique_ptr<PjRtBuffer>>>>
TfPjRtExecutable::Execute(
absl::Span<const std::vector<PjRtBuffer*>> argument_handles,
const ExecuteOptions& options,
std::optional<std::vector<PjRtFuture<>>>& returned_futures) {
std::vector<std::vector<PjRtBuffer*>> unwrapped_argument_handles;
unwrapped_argument_handles.reserve(argument_handles.size());
for (auto& handles : argument_handles) {
unwrapped_argument_handles.emplace_back();
auto& unwrapped_handles = unwrapped_argument_handles.back();
unwrapped_handles.reserve(handles.size());
for (PjRtBuffer* buffer : handles) {
unwrapped_handles.push_back(
tensorflow::down_cast<TfPjRtBuffer*>(buffer)->wrapped());
}
}
TF_ASSIGN_OR_RETURN(auto out, wrapped_->Execute(unwrapped_argument_handles,
options, returned_futures));
for (auto& buffer_list : out) {
for (std::unique_ptr<PjRtBuffer>& buffer : buffer_list) {
buffer = std::make_unique<TfPjRtBuffer>(client_, std::move(buffer));
}
}
return out;
}
absl::StatusOr<std::vector<std::unique_ptr<PjRtBuffer>>>
TfPjRtExecutable::ExecuteSharded(absl::Span<PjRtBuffer* const> argument_handles,
PjRtDevice* device,
const ExecuteOptions& options,
std::optional<PjRtFuture<>>& returned_future,
bool fill_future) {
std::vector<PjRtBuffer*> unwrapped_argument_handles;
unwrapped_argument_handles.reserve(argument_handles.size());
for (PjRtBuffer* buffer : argument_handles) {
unwrapped_argument_handles.push_back(
tensorflow::down_cast<TfPjRtBuffer*>(buffer)->wrapped());
}
TF_ASSIGN_OR_RETURN(auto out, wrapped_->ExecuteSharded(
unwrapped_argument_handles, device, options,
returned_future, fill_future));
for (std::unique_ptr<PjRtBuffer>& buffer : out) {
buffer = std::make_unique<TfPjRtBuffer>(client_, std::move(buffer));
}
return out;
}
absl::StatusOr<std::vector<std::unique_ptr<PjRtBuffer>>>
TfPjRtExecutable::ExecutePortable(
absl::Span<PjRtBuffer* const> argument_handles, PjRtDevice* device,
const ExecuteOptions& options, std::optional<PjRtFuture<>>& returned_future,
bool fill_future) {
std::vector<PjRtBuffer*> unwrapped_argument_handles;
unwrapped_argument_handles.reserve(argument_handles.size());
for (PjRtBuffer* buffer : argument_handles) {
unwrapped_argument_handles.push_back(
tensorflow::down_cast<TfPjRtBuffer*>(buffer)->wrapped());
}
TF_ASSIGN_OR_RETURN(auto out, wrapped_->ExecutePortable(
unwrapped_argument_handles, device, options,
returned_future, fill_future));
for (std::unique_ptr<PjRtBuffer>& buffer : out) {
buffer = std::make_unique<TfPjRtBuffer>(client_, std::move(buffer));
}
return out;
}
TfPjRtClient::TfPjRtClient(std::unique_ptr<PjRtClient> wrapped)
: wrapped_(std::move(wrapped)) {
LOG(INFO) << "TfPjRtClient created.";
int num_mutexes = wrapped_->addressable_device_count();
alive_buffers_ = std::vector<DeviceBuffers>(num_mutexes);
for (int i = 0; i < num_mutexes; ++i) {
mutex_id_from_device_id_.insert(
{wrapped_->addressable_devices()[i]->id(), i});
}
}
TfPjRtClient::~TfPjRtClient() { LOG(INFO) << "TfPjRtClient destroyed."; }
absl::StatusOr<std::unique_ptr<PjRtBuffer>> TfPjRtClient::WrapBuffer(
absl::StatusOr<std::unique_ptr<PjRtBuffer>> to_wrap) {
TF_ASSIGN_OR_RETURN(std::unique_ptr<PjRtBuffer> buffer, std::move(to_wrap));
return std::unique_ptr<PjRtBuffer>(
std::make_unique<TfPjRtBuffer>(this, std::move(buffer)));
}
absl::StatusOr<std::unique_ptr<PjRtLoadedExecutable>>
TfPjRtClient::WrapExecutable(
absl::StatusOr<std::unique_ptr<PjRtLoadedExecutable>> to_wrap) {
TF_ASSIGN_OR_RETURN(std::unique_ptr<PjRtLoadedExecutable> executable,
std::move(to_wrap));
return std::unique_ptr<PjRtLoadedExecutable>(
std::make_unique<TfPjRtExecutable>(this, std::move(executable)));
}
static int GetMutexId(
const TfPjRtBuffer* buffer,
const absl::flat_hash_map<int, int>& mutex_id_from_device_id) {
auto iters = mutex_id_from_device_id.find(buffer->wrapped()->device()->id());
CHECK(iters != mutex_id_from_device_id.end())
<< "Mutex id not found for device id: "
<< buffer->wrapped()->device()->id();
return iters->second;
}
void TfPjRtClient::TrackBuffer(TfPjRtBuffer* buffer) {
int mutex_id = GetMutexId(buffer, mutex_id_from_device_id_);
{
absl::MutexLock lock(&alive_buffers_[mutex_id].mu);
alive_buffers_[mutex_id].alive_buffers.insert(buffer);
}
}
void TfPjRtClient::UntrackBuffer(const TfPjRtBuffer* buffer) {
if (buffer->wrapped() == nullptr) {
return;
}
int mutex_id = GetMutexId(buffer, mutex_id_from_device_id_);
{
absl::MutexLock lock(&alive_buffers_[mutex_id].mu);
alive_buffers_[mutex_id].alive_buffers.erase(buffer);
}
}
void TfPjRtClient::DestroyWrappedBuffersAndClient() {
int num_mutexes = alive_buffers_.size();
for (int i = 0; i < num_mutexes; ++i) {
absl::MutexLock lock(&alive_buffers_[i].mu);
for (auto* buffer : alive_buffers_[i].alive_buffers) {
buffer->DestroyWrappedBuffer();
}
}
wrapped_.reset(nullptr);
LOG(INFO) << "TfPjRtClient::DestroyWrappedBuffersAndClient completed.";
}
std::unique_ptr<TfPjRtClient> TfPjRtClient::CreateTfPjRtClient(
std::unique_ptr<PjRtClient> wrapped) {
return std::make_unique<TfPjRtClient>(std::move(wrapped));
}
} | #include "xla/pjrt/tf_pjrt_client.h"
#include <string>
#include <utility>
#include <vector>
#include <gtest/gtest.h>
#include "xla/literal_util.h"
#include "xla/pjrt/cpu/cpu_client.h"
#include "xla/service/hlo_parser.h"
#include "tsl/platform/env.h"
#include "tsl/platform/file_system.h"
#include "tsl/platform/test.h"
namespace xla {
namespace {
TEST(TfClientTest, ExecuteAndHloSnapshot) {
constexpr char kProgram[] = R"(
HloModule add
ENTRY add {
x = f32[3,2] parameter(0)
y = f32[3,2] parameter(1)
ROOT add = f32[3,2] add(x, y)
})";
TF_ASSERT_OK_AND_ASSIGN(auto client, GetTfrtCpuClient(true));
client = TfPjRtClient::CreateTfPjRtClient(std::move(client));
TF_ASSERT_OK_AND_ASSIGN(auto hlo_module,
ParseAndReturnUnverifiedModule(kProgram, {}));
std::string dir = tsl::testing::TmpDir();
xla::CompileOptions options;
auto* debug_opts = options.executable_build_options.mutable_debug_options();
debug_opts->set_xla_dump_to(dir);
debug_opts->set_xla_dump_hlo_snapshots(true);
XlaComputation xla_computation(hlo_module->ToProto());
TF_ASSERT_OK_AND_ASSIGN(auto pjrt_executable,
client->Compile(xla_computation, options));
std::vector<float> data1{1.0, 2.0, 3.0, 4.0, 5.0, 6.0};
std::vector<float> data2{10.0, 20.0, 30.0, 40.0, 50.0, 60.0};
Shape shape = ShapeUtil::MakeShape(F32, {3, 2});
TF_ASSERT_OK_AND_ASSIGN(
auto buffer1,
client->BufferFromHostBuffer(
data1.data(), shape.element_type(), shape.dimensions(),
std::nullopt,
PjRtClient::HostBufferSemantics::kImmutableOnlyDuringCall, nullptr,
client->addressable_devices()[0]));
TF_ASSERT_OK_AND_ASSIGN(
auto buffer2,
client->BufferFromHostBuffer(
data2.data(), shape.element_type(), shape.dimensions(),
std::nullopt,
PjRtClient::HostBufferSemantics::kImmutableOnlyDuringCall, nullptr,
client->addressable_devices()[0]));
auto result = pjrt_executable->Execute(
{{buffer1.get(), buffer2.get()}},
{});
ASSERT_TRUE(result.ok());
tsl::FileSystem* fs;
ASSERT_TRUE(tsl::Env::Default()->GetFileSystemForFile(dir, &fs).ok());
std::vector<std::string> paths;
ASSERT_TRUE(fs->GetMatchingPaths(dir + "/*.snapshot.*.pb", &paths).ok());
ASSERT_EQ(paths.size(), 1);
HloSnapshot snapshot;
ASSERT_TRUE(
tsl::ReadBinaryProto(tsl::Env::Default(), paths[0], &snapshot).ok());
ASSERT_EQ(*Literal::CreateFromProto(snapshot.arguments(0)),
LiteralUtil::CreateR2<float>({{1.0, 2.0}, {3.0, 4.0}, {5.0, 6.0}}));
ASSERT_EQ(
*Literal::CreateFromProto(snapshot.arguments(1)),
LiteralUtil::CreateR2<float>({{10.0, 20.0}, {30.0, 40.0}, {50.0, 60.0}}));
ASSERT_EQ(
*Literal::CreateFromProto(snapshot.result()),
LiteralUtil::CreateR2<float>({{11.0, 22.0}, {33.0, 44.0}, {55.0, 66.0}}));
auto* tf_pjrt_client =
tensorflow::down_cast<xla::TfPjRtClient*>(client.get());
tf_pjrt_client->DestroyWrappedBuffersAndClient();
}
}
} | 2,208 |
#ifndef XLA_PJRT_PJRT_STREAM_EXECUTOR_CLIENT_H_
#define XLA_PJRT_PJRT_STREAM_EXECUTOR_CLIENT_H_
#include <array>
#include <cstddef>
#include <cstdint>
#include <functional>
#include <map>
#include <memory>
#include <optional>
#include <string>
#include <tuple>
#include <utility>
#include <vector>
#include "absl/base/thread_annotations.h"
#include "absl/container/flat_hash_map.h"
#include "absl/container/flat_hash_set.h"
#include "absl/container/inlined_vector.h"
#include "absl/functional/any_invocable.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/string_view.h"
#include "absl/synchronization/mutex.h"
#include "absl/types/span.h"
#include "mlir/IR/BuiltinOps.h"
#include "xla/client/executable_build_options.h"
#include "xla/client/local_client.h"
#include "xla/client/xla_computation.h"
#include "xla/executable_run_options.h"
#include "xla/hlo/ir/hlo_module.h"
#include "xla/layout.h"
#include "xla/literal.h"
#include "xla/pjrt/local_device_state.h"
#include "xla/pjrt/pjrt_client.h"
#include "xla/pjrt/pjrt_common.h"
#include "xla/pjrt/pjrt_compiler.h"
#include "xla/pjrt/pjrt_device_description.h"
#include "xla/pjrt/pjrt_executable.h"
#include "xla/pjrt/pjrt_future.h"
#include "xla/pjrt/tracked_device_buffer.h"
#include "xla/pjrt/transpose.h"
#include "xla/service/computation_placer.h"
#include "xla/service/executable.h"
#include "xla/service/gpu/gpu_executable_run_options.h"
#include "xla/service/hlo_cost_analysis.h"
#include "xla/service/maybe_owning_device_memory.h"
#include "xla/service/shaped_buffer.h"
#include "xla/shape.h"
#include "xla/shape_tree.h"
#include "xla/stream_executor/stream.h"
#include "xla/tsl/framework/allocator.h"
#include "xla/util.h"
#include "xla/xla_data.pb.h"
#include "tsl/platform/casts.h"
#include "tsl/platform/threadpool.h"
namespace xla {
class PjRtStreamExecutorDeviceDescription : public PjRtDeviceDescription {
public:
explicit PjRtStreamExecutorDeviceDescription(int id, std::string device_kind,
int process_index = 0)
: id_(id),
process_index_(process_index),
device_kind_(std::move(device_kind)) {}
int id() const override { return id_; }
int process_index() const override { return process_index_; }
absl::string_view device_kind() const override { return device_kind_; }
absl::string_view ToString() const override { return to_string_; }
absl::string_view DebugString() const override { return debug_string_; }
int core_on_chip() const { return core_index_; }
absl::Span<int const> coords() const { return absl::MakeSpan(coords_); }
const absl::flat_hash_map<std::string, PjRtDeviceAttribute>& Attributes()
const override {
return attributes_;
}
void SetAttributes(
absl::flat_hash_map<std::string, PjRtDeviceAttribute> attributes) {
attributes_ = std::move(attributes);
}
void SetDebugString(std::string debug_string) {
debug_string_ = std::move(debug_string);
}
void SetToString(std::string to_string) { to_string_ = std::move(to_string); }
void SetCoords(std::array<int, 1> coords) { coords_ = coords; }
void SetCoreOnChip(int core_index) { core_index_ = core_index; }
private:
const int id_;
const int process_index_;
const std::string device_kind_;
int core_index_ = -1;
std::string debug_string_ = "<unknown SE device>";
std::string to_string_ = "<unknown SE device>";
absl::flat_hash_map<std::string, PjRtDeviceAttribute> attributes_;
std::array<int, 1> coords_;
};
class PjRtStreamExecutorDevice : public PjRtDevice {
public:
explicit PjRtStreamExecutorDevice(
int id, std::unique_ptr<LocalDeviceState> local_device_state,
std::string device_kind, int process_index = 0)
: description_(id, std::move(device_kind), process_index),
local_device_id_(local_device_state
? local_device_state->local_device_id()
: PjRtLocalDeviceId(-1)),
local_hardware_id_(local_device_state
? local_device_state->local_hardware_id()
: PjRtLocalHardwareId(-1)),
local_device_state_(std::move(local_device_state)) {}
~PjRtStreamExecutorDevice() override = default;
void SetClient(PjRtClient* client) {
CHECK(client_ == nullptr);
client_ = client;
description().SetDebugString(absl::StrCat(platform_name(), ":", id()));
description().SetToString(absl::StrCat(platform_name(), "(id=", id(), ")"));
}
PjRtStreamExecutorDeviceDescription& description() { return description_; }
const PjRtStreamExecutorDeviceDescription& description() const override {
return description_;
}
PjRtPlatformId platform_id() const;
absl::string_view platform_name() const;
PjRtClient* client() const override { return client_; }
bool IsAddressable() const override { return local_device_id_ != -1; }
int local_hardware_id() const override {
return local_hardware_id_typed().value();
}
PjRtLocalDeviceId local_device_id() const override {
return local_device_id_;
}
PjRtLocalHardwareId local_hardware_id_typed() const override {
return local_hardware_id_;
}
LocalDeviceState* local_device_state() const {
return local_device_state_.get();
}
absl::StatusOr<LocalDeviceState*> GetLocalDeviceState() const;
absl::Status TransferToInfeed(const LiteralSlice& literal) override;
absl::Status TransferFromOutfeed(MutableBorrowingLiteral literal) override;
void AttachMemorySpace(PjRtMemorySpace* memory_space);
absl::Span<PjRtMemorySpace* const> memory_spaces() const override;
absl::StatusOr<PjRtMemorySpace*> default_memory_space() const override;
absl::StatusOr<PjRtMemorySpace*> memory_space_by_kind(
absl::string_view memory_space_kind) const override;
absl::StatusOr<PjRtMemorySpace*> memory_space_by_kind_id(int id) const;
absl::StatusOr<std::intptr_t> GetStreamForExternalReadyEvents()
const override;
std::unique_ptr<ScopedAsyncTrackingEvent> CreateAsyncTrackingEvent(
absl::string_view description) const override {
return nullptr;
}
private:
PjRtStreamExecutorDeviceDescription description_;
const PjRtLocalDeviceId local_device_id_;
const PjRtLocalHardwareId local_hardware_id_;
const std::unique_ptr<LocalDeviceState> local_device_state_;
PjRtClient* client_ = nullptr;
absl::InlinedVector<PjRtMemorySpace*, 1> memory_spaces_;
absl::flat_hash_map<int, PjRtMemorySpace*> memory_spaces_by_id_;
};
class PjRtStreamExecutorMemorySpace : public PjRtMemorySpace {
public:
PjRtStreamExecutorMemorySpace(int id, PjRtDevice* device,
absl::string_view kind, int kind_id);
PjRtClient* client() const override { return device_->client(); }
absl::Span<PjRtDevice* const> devices() const override {
return absl::Span<PjRtDevice* const>(&device_, device_ != nullptr ? 1 : 0);
}
int id() const override { return id_; }
absl::string_view kind() const override { return kind_; }
int kind_id() const override { return kind_id_; }
absl::string_view DebugString() const override { return debug_string_; }
absl::string_view ToString() const override { return to_string_; }
private:
int id_;
PjRtDevice* device_ = nullptr;
absl::string_view kind_;
int kind_id_;
std::string debug_string_;
std::string to_string_;
};
class PjRtStreamExecutorClient : public PjRtClient {
public:
explicit PjRtStreamExecutorClient(
std::string platform_name, LocalClient* client,
std::vector<std::unique_ptr<PjRtStreamExecutorDevice>> devices,
int process_index, std::unique_ptr<se::DeviceMemoryAllocator> allocator,
std::unique_ptr<tsl::Allocator> host_memory_allocator,
bool should_stage_host_to_device_transfers,
std::unique_ptr<gpu::GpuExecutableRunOptions> gpu_run_options);
~PjRtStreamExecutorClient() override = default;
int process_index() const override { return process_index_; }
int device_count() const override { return devices_.size(); }
int addressable_device_count() const override {
return addressable_devices_.size();
}
absl::Span<PjRtDevice* const> devices() const override { return devices_; }
absl::Span<PjRtDevice* const> addressable_devices() const override {
return addressable_devices_;
}
absl::StatusOr<PjRtDevice*> LookupDevice(
PjRtGlobalDeviceId global_device_id) const override {
auto it = id_to_device_.find(global_device_id.value());
if (it != id_to_device_.end()) {
return it->second;
}
return InvalidArgument("No matching device found for device_id %d",
global_device_id.value());
}
absl::StatusOr<PjRtDevice*> LookupAddressableDevice(
PjRtLocalDeviceId local_device_id) const override;
absl::Span<PjRtMemorySpace* const> memory_spaces() const override;
PjRtPlatformId platform_id() const override { return platform_id_; }
absl::string_view platform_name() const override { return platform_name_; }
absl::string_view platform_version() const override { return "<unknown>"; }
PjRtRuntimeType runtime_type() const override { return kStreamExecutor; }
virtual bool EnqueueD2DTransfersOnSrcStream() const { return true; }
absl::StatusOr<DeviceAssignment> GetDefaultDeviceAssignment(
int num_replicas, int num_partitions) const override;
absl::StatusOr<Layout> GetDefaultLayout(
PrimitiveType element_type, absl::Span<const int64_t> dims) override;
absl::StatusOr<std::unique_ptr<PjRtLoadedExecutable>> Compile(
const XlaComputation& computation, CompileOptions options) override;
absl::StatusOr<std::unique_ptr<PjRtLoadedExecutable>> Compile(
mlir::ModuleOp mlir_module, CompileOptions options) override;
virtual absl::StatusOr<std::string> SerializeExecutable(
const PjRtLoadedExecutable& executable) const;
absl::StatusOr<std::unique_ptr<PjRtLoadedExecutable>> DeserializeExecutable(
absl::string_view serialized,
std::optional<CompileOptions> options) override;
absl::StatusOr<std::unique_ptr<PjRtLoadedExecutable>>
LoadSerializedExecutable(absl::string_view serialized,
std::optional<CompileOptions> options,
const LoadOptions& load_options) override;
absl::StatusOr<std::unique_ptr<HloCostAnalysis>> GetHloCostAnalysis()
const override;
absl::StatusOr<std::unique_ptr<PjRtBuffer>> CreateUninitializedBuffer(
const Shape& shape, PjRtDevice* device) override;
absl::StatusOr<std::unique_ptr<PjRtBuffer>> CreateUninitializedBuffer(
const Shape& shape, PjRtDevice* device,
std::shared_ptr<BufferSequencingEvent> definition_event);
absl::StatusOr<std::unique_ptr<PjRtBuffer>> CreateErrorBuffer(
absl::Status error, const Shape& shape, PjRtMemorySpace* memory) override;
absl::StatusOr<std::unique_ptr<PjRtClient::AsyncHostToDeviceTransferManager>>
CreateBuffersForAsyncHostToDevice(absl::Span<const Shape> shapes,
PjRtDevice* device) override {
return Unimplemented("Async transfer to buffers not implemented");
};
absl::StatusOr<std::unique_ptr<PjRtClient::AsyncHostToDeviceTransferManager>>
CreateBuffersForAsyncHostToDevice(absl::Span<const Shape> shapes,
PjRtMemorySpace* memory_space) override {
return Unimplemented("Async transfer to buffers not implemented");
};
absl::StatusOr<std::unique_ptr<PjRtBuffer>> BufferFromHostBuffer(
const void* data, PrimitiveType type, absl::Span<int64_t const> dims,
std::optional<absl::Span<int64_t const>> byte_strides,
HostBufferSemantics host_buffer_semantics,
absl::AnyInvocable<void() &&> on_done_with_host_buffer,
PjRtDevice* device, const Layout* device_layout) override;
absl::StatusOr<std::unique_ptr<PjRtBuffer>> BufferFromHostBuffer(
const void* data, PrimitiveType type, absl::Span<int64_t const> dims,
std::optional<absl::Span<int64_t const>> byte_strides,
HostBufferSemantics host_buffer_semantics,
absl::AnyInvocable<void() &&> on_done_with_host_buffer,
PjRtDevice* device) override;
absl::StatusOr<std::unique_ptr<PjRtBuffer>> BufferFromHostBuffer(
const void* data, PrimitiveType type, absl::Span<int64_t const> dims,
std::optional<absl::Span<int64_t const>> byte_strides,
HostBufferSemantics host_buffer_semantics,
absl::AnyInvocable<void() &&> on_done_with_host_buffer,
PjRtMemorySpace* memory_space, const Layout* device_layout) override;
absl::StatusOr<std::unique_ptr<PjRtBuffer>> BufferFromHostLiteral(
const LiteralSlice& literal, PjRtDevice* device) override;
absl::StatusOr<std::unique_ptr<PjRtBuffer>> BufferFromHostLiteral(
const LiteralSlice& literal, PjRtMemorySpace* memory_space) override;
absl::StatusOr<std::vector<std::unique_ptr<PjRtBuffer>>>
MakeCrossHostReceiveBuffers(absl::Span<const Shape> shapes,
PjRtDevice* device,
PjRtCrossHostRecvNotifier notifier) override;
absl::StatusOr<std::vector<std::unique_ptr<PjRtBuffer>>>
MakeCrossHostReceiveBuffersForGather(
absl::Span<const Shape> shapes, std::vector<GatherDetails> gather_details,
PjRtDevice* device, PjRtCrossHostRecvNotifier notifier) override;
absl::StatusOr<std::unique_ptr<PjRtBuffer>> CreateViewOfDeviceBuffer(
void* device_ptr, const Shape& shape, PjRtDevice* device,
std::function<void()> on_delete_callback,
std::optional<std::intptr_t> stream) override;
absl::StatusOr<ChannelHandle> CreateChannelHandle() override {
return client()->CreateChannelHandle();
}
absl::StatusOr<ChannelHandle> CreateDeviceToHostChannelHandle() override {
return client()->CreateDeviceToHostChannelHandle();
}
absl::StatusOr<ChannelHandle> CreateHostToDeviceChannelHandle() override {
return client()->CreateHostToDeviceChannelHandle();
}
absl::Status Defragment() override {
return Unimplemented("Defragment not implemented");
}
LocalDeviceState& device_state(int device_ordinal) const {
return *tensorflow::down_cast<PjRtStreamExecutorDevice*>(
LookupAddressableDevice(xla::PjRtLocalDeviceId(device_ordinal))
.value())
->local_device_state();
}
LocalClient* client() const { return client_; }
se::DeviceMemoryAllocator* allocator() const { return allocator_; }
tsl::Allocator* host_memory_allocator() const {
return host_memory_allocator_.get();
}
bool should_stage_host_to_device_transfers() const {
return should_stage_host_to_device_transfers_;
}
gpu::GpuExecutableRunOptions* gpu_run_options() const {
return gpu_run_options_.get();
}
tsl::thread::ThreadPool* thread_pool() { return &thread_pool_; }
protected:
friend class PjRtStreamExecutorBuffer;
virtual absl::Status EnqueueCrossHostReceive(
absl::Span<const std::unique_ptr<PjRtBuffer>> buffers,
std::shared_ptr<BufferSequencingEvent> definition_event,
PjRtCrossHostRecvNotifier notifier,
std::optional<std::vector<GatherDetails>> gather_details) const {
return Unimplemented("Cross host receives not implemented.");
}
virtual void CopyToRemoteDevice(
PjRtBuffer* buffer, absl::string_view serialized_descriptor,
PjRtBuffer::RemoteSendCallback on_done) const {
on_done(Unimplemented("Cross host sends not implemented."),
false);
}
virtual void CopyToRemoteDeviceScattered(
PjRtBuffer* buffer, std::vector<std::string> serialized_descriptors,
std::vector<PjRtBuffer::RemoteSendCallback> callbacks,
const PjRtBuffer::ScatterDetails& scatter_details) const {
for (const auto& cb : callbacks) {
cb(Unimplemented("Scattered cross host sends not implemented."),
false);
}
}
virtual PjRtFuture<> CopyRawSubBufferToHost(PjRtBuffer* buffer,
PjRtFuture<void*> dst,
int64_t offset,
int64_t transfer_size) {
return PjRtFuture<>(Unimplemented("Raw copies to host not implemented."));
}
struct ExecutableExtras {
std::shared_ptr<DeviceAssignment> device_assignment;
std::vector<PjRtLoadedExecutable::LogicalDeviceIds>
addressable_device_logical_ids;
std::vector<PjRtDevice*> addressable_devices;
};
absl::StatusOr<ExecutableExtras> GetExecutableExtras(CompileOptions* options);
const PjRtPlatformId platform_id_;
const std::string platform_name_;
LocalClient* client_;
std::unique_ptr<tsl::Allocator> host_memory_allocator_;
se::DeviceMemoryAllocator* allocator_;
std::unique_ptr<se::DeviceMemoryAllocator> owned_allocator_;
std::vector<std::unique_ptr<PjRtStreamExecutorDevice>> owned_devices_;
std::vector<PjRtDevice*> devices_;
std::map<int, PjRtDevice*> id_to_device_;
std::vector<PjRtDevice*> addressable_devices_;
int process_index_;
std::vector<std::unique_ptr<PjRtMemorySpace>> owned_memory_spaces_;
std::vector<PjRtMemorySpace*> memory_spaces_;
bool should_stage_host_to_device_transfers_;
std::unique_ptr<gpu::GpuExecutableRunOptions> gpu_run_options_;
tsl::thread::ThreadPool thread_pool_;
absl::Mutex transpose_mu_;
TransposePlanCache transpose_cache_ ABSL_GUARDED_BY(transpose_mu_);
};
absl::StatusOr<DeviceAssignment> DevicesToDeviceAssignment(
absl::Span<const std::vector<PjRtDevice*>> devices);
class PjRtStreamExecutorBuffer : public PjRtBuffer {
public:
class ScopedHold {
public:
enum Type { kUsage = 0, kExternalReference, kDonation, kMaxValue };
enum State {
kUninitialized = 0,
kValid,
kMoved,
kConverted,
kReleased,
kDonated,
kError
};
~ScopedHold();
ScopedHold(ScopedHold&& other);
ScopedHold(const ScopedHold&) = delete;
ScopedHold& operator=(const ScopedHold&) = delete;
Type type() const { return type_; }
absl::Status status() const {
switch (state_) {
case kUninitialized:
return InvalidArgument("Buffer has not been initialized");
case kValid:
return absl::OkStatus();
case kMoved:
return InvalidArgument("Buffer has been moved.");
case kConverted:
return InvalidArgument("Buffer has been converted");
case kReleased:
return InvalidArgument("Buffer has been released");
case kDonated:
return InvalidArgument("Buffer has been donated");
case kError:
return status_;
default:
CHECK(false) << "Unexpected state value " << state_;
}
}
bool ok() const { return state_ == kValid; }
const std::shared_ptr<TrackedDeviceBuffer>& buffer() const {
CHECK_EQ(state_, kValid);
CHECK_NE(buffer_, nullptr);
return buffer_;
}
TrackedDeviceBuffer* operator->() const { return buffer().get(); }
const TrackedDeviceBuffer& operator*() const { return *buffer(); }
void ConvertUsageHold(se::Stream* usage_stream,
std::shared_ptr<BufferSequencingEvent> event,
bool reference_held);
void ConfirmDonation();
void AddToInput(ShapeTree<MaybeOwningDeviceMemory>::iterator* iterator,
const ShapeTree<MaybeOwningDeviceMemory>::iterator& end,
ExecutionInput* execution_input,
se::DeviceMemoryAllocator* allocator) const;
private:
friend class PjRtStreamExecutorBuffer;
friend class PjRtStreamExecutorClient;
using ForClosure =
std::tuple<PjRtStreamExecutorBuffer*, Type, State, absl::Status,
std::shared_ptr<TrackedDeviceBuffer>>;
ScopedHold(PjRtStreamExecutorBuffer* parent, Type type)
: parent_(parent), type_(type), state_(kUninitialized) {}
explicit ScopedHold(const ForClosure& closure_helper)
: parent_(std::get<0>(closure_helper)),
type_(std::get<1>(closure_helper)),
state_(std::get<2>(closure_helper)),
status_(std::get<3>(closure_helper)),
buffer_(std::get<4>(closure_helper)) {
CHECK(status_.ok() && buffer_ != nullptr);
}
void SetState(State state) { state_ = state; }
void Acquire(
absl::StatusOr<std::shared_ptr<TrackedDeviceBuffer>>&& buffer_or);
ForClosure ToClosure();
PjRtStreamExecutorBuffer* const parent_;
const Type type_;
State state_;
absl::Status status_;
std::shared_ptr<TrackedDeviceBuffer> buffer_;
};
PjRtStreamExecutorBuffer(Shape on_device_shape,
std::shared_ptr<TrackedDeviceBuffer> device_buffer,
PjRtClient* client, PjRtDevice* device,
PjRtMemorySpace* memory_space);
~PjRtStreamExecutorBuffer() override;
PjRtStreamExecutorBuffer(const PjRtStreamExecutorBuffer&) = delete;
PjRtStreamExecutorBuffer(PjRtStreamExecutorBuffer&&) = delete;
PjRtStreamExecutorBuffer& operator=(const PjRtStreamExecutorBuffer&) = delete;
PjRtStreamExecutorBuffer& operator=(PjRtStreamExecutorBuffer&&) = delete;
const Shape& on_device_shape() const override { return on_device_shape_; }
absl::StatusOr<Shape> logical_on_device_shape() override;
PjRtMemorySpace* memory_space() const override { return memory_space_; }
PjRtStreamExecutorDevice* device() const override { return device_; }
PjRtPlatformId platform_id() const { return client_->platform_id(); }
absl::string_view platform_name() const { return client_->platform_name(); }
PjRtStreamExecutorClient* client() const override { return client_; }
bool IsEmptyTuple() const {
return on_device_shape_.IsTuple() &&
on_device_shape_.tuple_shapes_size() == 0;
}
absl::StatusOr<std::unique_ptr<ExternalReference>> AcquireExternalReference()
override;
absl::StatusOr<std::unique_ptr<ExternalReference>>
ReleaseDeviceMemoryOwnership(bool wait_for_operations_to_complete) override;
using PjRtBuffer::ToLiteralSync;
PjRtFuture<> ToLiteral(MutableLiteralBase* literal) override;
PjRtFuture<> LazyToLiteral(
absl::AnyInvocable<absl::StatusOr<MutableLiteralBase*>() &&> generator)
override;
absl::StatusOr<size_t> GetOnDeviceSizeInBytes() const override;
PjRtFuture<> CopyRawToHost(void* dst, int64_t offset,
int64_t transfer_size) override;
PjRtFuture<> CopyRawToHostFuture(PjRtFuture<void*> dst, int64_t offset,
int64_t transfer_size) override;
void Delete() override;
bool IsDeleted() override;
absl::StatusOr<ShapedBuffer> AsShapedBuffer() const;
ScopedHold GetBufferWithHold(ScopedHold::Type type);
ScopedHold GetBufferWithUsageHold() {
return GetBufferWithHold(ScopedHold::kUsage);
}
ScopedHold GetBufferWithExternalReference() {
return GetBufferWithHold(ScopedHold::kExternalReference);
}
absl::StatusOr<std::unique_ptr<PjRtBuffer>> CopyToDevice(
PjRtDevice* dst_device) override;
absl::StatusOr<std::unique_ptr<PjRtBuffer>> CopyToMemorySpace(
PjRtMemorySpace* dst_memory_space) override;
void CopyToRemoteDevice(PjRtFuture<std::string> serialized_descriptor,
RemoteSendCallback on_done) override;
void CopyToRemoteDeviceScattered(
PjRtFuture<std::vector<std::string>> serialized_descriptors,
std::vector<RemoteSendCallback> callbacks,
const ScatterDetails& scatter_details) override;
PjRtFuture<> GetReadyFuture() override;
bool IsOnCpu() const override; | #include "xla/pjrt/pjrt_stream_executor_client.h"
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include <gmock/gmock.h>
#include "absl/functional/any_invocable.h"
#include "absl/synchronization/mutex.h"
#include "xla/client/client_library.h"
#include "xla/client/xla_builder.h"
#include "xla/literal.h"
#include "xla/literal_comparison.h"
#include "xla/literal_util.h"
#include "xla/pjrt/pjrt_client.h"
#include "xla/pjrt/pjrt_future.h"
#include "xla/service/platform_util.h"
#include "xla/shape_util.h"
#include "xla/test.h"
#include "xla/tsl/concurrency/async_value_ref.h"
#include "xla/xla_data.pb.h"
#include "tsl/lib/core/status_test_util.h"
#include "tsl/platform/status.h"
#include "tsl/platform/statusor.h"
namespace xla {
namespace {
absl::StatusOr<std::unique_ptr<PjRtStreamExecutorClient>> GetClient() {
LocalClient* local_client = xla::ClientLibrary::LocalClientOrDie();
TF_ASSIGN_OR_RETURN(se::Platform * platform,
PlatformUtil::GetPlatform("Host"));
se::StreamExecutorConfig config;
config.ordinal = 0;
TF_ASSIGN_OR_RETURN(se::StreamExecutor * executor,
platform->GetExecutor(config));
auto device_state = std::make_unique<LocalDeviceState>(
executor, local_client, LocalDeviceState::kSynchronous,
32,
false, false);
auto device = std::make_unique<PjRtStreamExecutorDevice>(
0, std::move(device_state), "cpu");
std::vector<std::unique_ptr<PjRtStreamExecutorDevice>> devices;
devices.emplace_back(std::move(device));
return std::make_unique<PjRtStreamExecutorClient>(
"cpu", local_client, std::move(devices),
0, nullptr,
nullptr,
false,
nullptr);
}
absl::StatusOr<std::unique_ptr<PjRtLoadedExecutable>> ToyExecutable(
PjRtStreamExecutorClient& client, Shape shape,
absl::AnyInvocable<void(XlaBuilder&)> set_up_aliases) {
CompileOptions compile_options;
XlaBuilder builder("Add");
auto a = Parameter(&builder, 0, shape, "a");
auto b = Parameter(&builder, 1, shape, "b");
auto c = Add(a, b);
auto d = Add(c, c);
Tuple(&builder, {c, d});
set_up_aliases(builder);
TF_ASSIGN_OR_RETURN(auto computation,
builder.Build(true));
TF_ASSIGN_OR_RETURN(auto executable,
client.Compile(computation, compile_options));
return executable;
}
absl::Status ExecuteWithSameInputBuffer(
absl::AnyInvocable<void(XlaBuilder&)> set_up_aliases) {
auto shape = xla::ShapeUtil::MakeScalarShape(xla::F32);
TF_ASSIGN_OR_RETURN(auto client, GetClient());
TF_RET_CHECK(!client->addressable_devices().empty());
auto* device0 = client->addressable_devices().front();
TF_ASSIGN_OR_RETURN(auto buffer,
client->CreateUninitializedBuffer(shape, device0));
TF_ASSIGN_OR_RETURN(auto executable,
ToyExecutable(*client, shape, std::move(set_up_aliases)));
return executable->Execute({{buffer.get(), buffer.get()}}, {})
.status();
}
TEST(PjRtStreamExecutorClientTest, DonateSameBufferTwice) {
auto status = ExecuteWithSameInputBuffer([](XlaBuilder& builder) {});
ASSERT_TRUE(status.ok());
status = ExecuteWithSameInputBuffer(
[](XlaBuilder& builder) { builder.SetUpAlias({0}, 0, {}); });
ASSERT_FALSE(status.ok());
EXPECT_THAT(status.message(), ::testing::HasSubstr("f(donate(a), a)"));
status = ExecuteWithSameInputBuffer(
[](XlaBuilder& builder) { builder.SetUpAlias({0}, 1, {}); });
ASSERT_FALSE(status.ok());
EXPECT_THAT(status.message(), ::testing::HasSubstr("f(a, donate(a))"));
status = ExecuteWithSameInputBuffer([](XlaBuilder& builder) {
builder.SetUpAlias({0}, 0, {});
builder.SetUpAlias({1}, 1, {});
});
ASSERT_FALSE(status.ok());
EXPECT_THAT(status.message(),
::testing::HasSubstr("f(donate(a), donate(a))"));
}
TEST(PjRtStreamExecutorClientTest, DonateWithControlDependency) {
TF_ASSERT_OK_AND_ASSIGN(auto client, GetClient());
auto literal = LiteralUtil::CreateR2({{1, 2, 3}, {4, 5, 6}});
TF_ASSERT_OK_AND_ASSIGN(
std::unique_ptr<PjRtBuffer> buffer,
client->BufferFromHostLiteral(literal, client->addressable_devices()[0]));
PjRtFuture<>::Promise promise = PjRtFuture<>::CreatePromise();
PjRtFuture<> future(promise);
auto blocked_buffer =
std::move(*(buffer->DonateWithControlDependency(future)));
EXPECT_TRUE(buffer->IsDeleted());
buffer.reset();
absl::Mutex mu;
auto result_literal = std::make_shared<Literal>(
ShapeUtil::DeviceShapeToHostShape(blocked_buffer->on_device_shape()));
bool got_literal = false;
blocked_buffer->ToLiteral(result_literal.get()).OnReady([&](absl::Status s) {
absl::MutexLock l(&mu);
TF_ASSERT_OK(s);
got_literal = true;
});
blocked_buffer.reset();
EXPECT_FALSE(got_literal);
promise.Set();
EXPECT_TRUE(future.IsReady());
{
absl::MutexLock l(&mu);
mu.Await(absl::Condition(&got_literal));
}
TF_ASSERT_OK(literal_comparison::Equal(literal, *result_literal));
}
}
} | 2,209 |
#ifndef XLA_PJRT_C_PJRT_C_API_HELPERS_H_
#define XLA_PJRT_C_PJRT_C_API_HELPERS_H_
#include <cstddef>
#include <cstdint>
#include <functional>
#include <memory>
#include <string>
#include <vector>
#include "absl/base/attributes.h"
#include "absl/container/flat_hash_map.h"
#include "absl/status/status.h"
#include "absl/strings/string_view.h"
#include "absl/types/span.h"
#include "xla/layout.h"
#include "xla/pjrt/c/pjrt_c_api.h"
#include "xla/pjrt/c/pjrt_c_api_layouts_extension.h"
#include "xla/pjrt/c/pjrt_c_api_profiler_extension.h"
#include "xla/pjrt/distributed/key_value_store_interface.h"
#include "xla/pjrt/pjrt_client.h"
#include "xla/pjrt/pjrt_common.h"
#include "xla/pjrt/pjrt_executable.h"
#include "xla/pjrt/pjrt_future.h"
#include "xla/shape.h"
#include "xla/xla_data.pb.h"
namespace pjrt {
ABSL_CONST_INIT extern const absl::string_view kHloFormat;
ABSL_CONST_INIT extern const absl::string_view kMlirFormat;
ABSL_CONST_INIT extern const absl::string_view kHloWithConfigFormat;
#define RETURN_STATUS_IF_PJRT_ERROR(expr, c_api) \
do { \
PJRT_Error* error = (expr); \
std::unique_ptr<PJRT_Error, pjrt::PJRT_ErrorDeleter> _error( \
error, pjrt::MakeErrorDeleter(c_api)); \
absl::Status _status = pjrt::PjrtErrorToStatus(_error.get(), c_api); \
if (!_status.ok()) { \
return _status; \
} \
} while (false)
using PJRT_ClientDeleter = std::function<void(PJRT_Client*)>;
PJRT_ClientDeleter MakeClientDeleter(const PJRT_Api* api);
using PJRT_ErrorDeleter = std::function<void(PJRT_Error*)>;
PJRT_ErrorDeleter MakeErrorDeleter(const PJRT_Api* api);
using PJRT_BufferDeleter = std::function<void(PJRT_Buffer*)>;
PJRT_BufferDeleter MakeBufferDeleter(const PJRT_Api* api);
using PJRT_ExecutableDeleter = std::function<void(PJRT_Executable*)>;
PJRT_ExecutableDeleter MakeExecutableDeleter(const PJRT_Api* api);
using PJRT_LoadedExecutableDeleter =
std::function<void(PJRT_LoadedExecutable*)>;
PJRT_LoadedExecutableDeleter MakeLoadedExecutableDeleter(const PJRT_Api* api);
using PJRT_EventDeleter = std::function<void(PJRT_Event*)>;
PJRT_EventDeleter MakeEventDeleter(const PJRT_Api* api);
using PJRT_SerializedExecutableDeleter =
std::function<void(PJRT_SerializedExecutable*)>;
using PJRT_TopologyDescriptionDeleter =
std::function<void(PJRT_TopologyDescription*)>;
PJRT_TopologyDescriptionDeleter MakeTopologyDescriptionDeleter(
const PJRT_Api* api);
using PJRT_Layouts_MemoryLayoutDeleter =
std::function<void(PJRT_Layouts_MemoryLayout*)>;
PJRT_Layouts_MemoryLayoutDeleter MakeMemoryLayoutDeleter(const PJRT_Api* api);
void LogFatalIfPjrtError(PJRT_Error* error, const PJRT_Api* api);
absl::string_view GetPjrtErrorMessage(const PJRT_Error* error,
const PJRT_Api* api);
PJRT_Error_Code GetErrorCode(const PJRT_Error* error, const PJRT_Api* api);
absl::Status PjrtErrorToStatus(const PJRT_Error* error, const PJRT_Api* api);
absl::StatusCode PjrtErrorToStatusCode(const PJRT_Error* error,
const PJRT_Api* api);
absl::StatusCode PjrtErrorCodeToStatusCode(PJRT_Error_Code code);
PJRT_Error_Code StatusCodeToPjrtErrorCode(absl::StatusCode code);
PJRT_Buffer_Type ConvertToPjRtBufferType(xla::PrimitiveType type);
xla::PrimitiveType ConvertFromPjRtBufferType(PJRT_Buffer_Type type);
PJRT_HostBufferSemantics ConvertToPjRtHostBufferSemantics(
xla::PjRtClient::HostBufferSemantics buffer_semantics);
xla::PjRtClient::HostBufferSemantics ConvertFromPjRtHostBufferSemantics(
PJRT_HostBufferSemantics buffer_semantics);
xla::PjRtFuture<> ConvertCEventToCppFuture(PJRT_Event* c_event,
const PJRT_Api* c_api);
absl::StatusOr<std::vector<PJRT_NamedValue>> ConvertToPjRtNamedValueList(
const absl::flat_hash_map<std::string, xla::PjRtValueType>& cpp_value_map);
absl::flat_hash_map<std::string, xla::PjRtValueType>
ConvertFromPjRtNamedValueList(const PJRT_NamedValue* c_value_list,
size_t list_size);
absl::Status ValidateCreateOptions(
const absl::flat_hash_map<std::string, xla::PjRtValueType>& value_map,
const absl::flat_hash_map<std::string, PJRT_NamedValue_Type>&
expected_name_and_types);
const std::vector<PJRT_NamedValue>& GetXlaPluginCAttributes();
absl::Status ActualStructSizeIsGreaterOrEqual(absl::string_view struct_name,
size_t expected_size,
size_t actual_size);
absl::string_view GetPlatformVersion(PJRT_Client* client, const PJRT_Api* api);
absl::string_view GetPlatformName(PJRT_Client* client, const PJRT_Api* api);
absl::StatusOr<PJRT_TopologyDescription*> GetTopologyDescription(
PJRT_Client* client, const PJRT_Api* api);
PJRT_Chunk ConvertFromCppChunk(xla::PjRtChunk chunk);
xla::PjRtChunk ConvertToCppChunk(const PJRT_Chunk& chunk);
PJRT_DeviceDescription* GetDeviceDescription(const PJRT_Api* api,
PJRT_Device* device);
absl::Span<PJRT_Memory* const> GetAddressableMemories(const PJRT_Api* api,
PJRT_Device* device);
int GetId(const PJRT_Api* api, PJRT_DeviceDescription* device_desc);
using PJRT_KeyValueGetCFunc =
std::function<PJRT_Error*(PJRT_KeyValueGetCallback_Args* args)>;
using PJRT_KeyValuePutCFunc =
std::function<PJRT_Error*(PJRT_KeyValuePutCallback_Args* args)>;
struct PJRT_KeyValueCallbackData {
PJRT_KeyValueCallbackData() = default;
PJRT_KeyValueCallbackData(const PJRT_KeyValueCallbackData&) = delete;
std::shared_ptr<xla::KeyValueStoreInterface> kv_store;
pjrt::PJRT_KeyValueGetCFunc kv_get_c_func;
pjrt::PJRT_KeyValuePutCFunc kv_put_c_func;
PJRT_KeyValueGetCallback c_kv_get;
PJRT_KeyValuePutCallback c_kv_put;
};
std::unique_ptr<PJRT_KeyValueCallbackData> ConvertToCKeyValueCallbacks(
std::shared_ptr<xla::KeyValueStoreInterface> kv_store);
using PJRT_SendCallbackFunction =
std::function<PJRT_Error*(PJRT_Chunk*, PJRT_CallbackError*, size_t, bool)>;
using PJRT_RecvCallbackFunction = std::function<void(PJRT_CopyToDeviceStream*)>;
PJRT_SendCallbackInfo CppSendCallbackToCSendCallback(
xla::SendCallback cpp_send_callback,
PJRT_SendCallbackFunction* send_callback_function);
PJRT_RecvCallbackInfo CppRecvCallbackToCRecvCallback(
xla::RecvCallback cpp_recv_callback,
PJRT_RecvCallbackFunction* recv_callback_function);
struct BufferMemoryLayoutData {
PJRT_Buffer_MemoryLayout c_layout;
std::vector<int64_t> minor_to_major;
std::vector<int64_t> tile_dims;
std::vector<size_t> tile_dim_sizes;
};
absl::StatusOr<BufferMemoryLayoutData> ConvertToBufferMemoryLayoutData(
const xla::Layout& cpp_layout);
absl::StatusOr<BufferMemoryLayoutData> ConvertToBufferMemoryLayoutData(
absl::Span<int64_t const> byte_strides);
absl::StatusOr<xla::Layout> ConvertToLayout(
const PJRT_Buffer_MemoryLayout_Tiled& c_tiled);
PJRT_Buffer_Type GetElementType(const PJRT_Api* api, PJRT_Buffer* buffer);
absl::Span<const int64_t> GetDimensions(const PJRT_Api* api,
PJRT_Buffer* buffer);
std::unique_ptr<PJRT_Layouts_MemoryLayout, PJRT_Layouts_MemoryLayoutDeleter>
GetMemoryLayout(const PJRT_Api* api, PJRT_Buffer* buffer);
absl::StatusOr<xla::Shape> BuildXlaShapeFromC(PJRT_Buffer_Type element_type,
const int64_t* dims,
size_t num_dims,
PJRT_Buffer_MemoryLayout* layout);
absl::string_view PlatformName(const PJRT_Api* api,
const PJRT_TopologyDescription* topo_desc);
absl::Span<PJRT_DeviceDescription* const> DeviceDescriptions(
const PJRT_Api* api, const PJRT_TopologyDescription* topo_desc);
absl::StatusOr<xla::CompiledMemoryStats> GetCompiledMemoryStats(
const PJRT_Api* api, PJRT_Executable* executable);
PJRT_Profiler_Extension CreatePjrtProfilerExtension(
absl::string_view traceme_name);
template <typename ExtType, typename InputType>
ExtType* FindExtension(InputType* in, PJRT_Extension_Type type) {
PJRT_Extension_Base* ext = in->extension_start;
while (ext != nullptr) {
if (ext->type == type) {
return reinterpret_cast<ExtType*>(ext);
}
ext = ext->next;
}
return nullptr;
}
template <typename InputType>
int64_t GetTracemeContextId(InputType* args) {
PJRT_Profiler_Extension* profiler_extension =
FindExtension<PJRT_Profiler_Extension>(
args, PJRT_Extension_Type::PJRT_Extension_Type_Profiler);
int64_t traceme_context_id = -1;
if (profiler_extension != nullptr) {
traceme_context_id = profiler_extension->traceme_context_id;
}
return traceme_context_id;
}
}
#endif
#include "xla/pjrt/c/pjrt_c_api_helpers.h"
#include <algorithm>
#include <cstddef>
#include <cstdint>
#include <functional>
#include <memory>
#include <string>
#include <string_view>
#include <utility>
#include <variant>
#include <vector>
#include "absl/container/flat_hash_map.h"
#include "absl/container/inlined_vector.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/string_view.h"
#include "absl/time/time.h"
#include "absl/types/span.h"
#include "xla/layout.h"
#include "xla/pjrt/c/pjrt_c_api.h"
#include "xla/pjrt/c/pjrt_c_api_layouts_extension.h"
#include "xla/pjrt/c/pjrt_c_api_profiler_extension.h"
#include "xla/pjrt/distributed/key_value_store_interface.h"
#include "xla/pjrt/pjrt_client.h"
#include "xla/pjrt/pjrt_common.h"
#include "xla/pjrt/pjrt_executable.h"
#include "xla/pjrt/pjrt_future.h"
#include "xla/primitive_util.h"
#include "xla/shape_util.h"
#include "xla/util.h"
#include "xla/xla_data.pb.h"
#include "tsl/platform/errors.h"
#include "tsl/platform/logging.h"
#include "tsl/platform/status.h"
#include "tsl/platform/statusor.h"
#include "tsl/profiler/lib/connected_traceme.h"
#include "tsl/profiler/lib/context_types.h"
namespace pjrt {
const absl::string_view kHloFormat = "hlo";
const absl::string_view kMlirFormat = "mlir";
const absl::string_view kHloWithConfigFormat = "hlo_with_config";
PJRT_ClientDeleter MakeClientDeleter(const PJRT_Api* api) {
return [api](PJRT_Client* client) -> void {
PJRT_Client_Destroy_Args destroy_args;
destroy_args.struct_size = PJRT_Client_Destroy_Args_STRUCT_SIZE;
destroy_args.extension_start = nullptr;
destroy_args.client = client;
PJRT_Error* error = api->PJRT_Client_Destroy(&destroy_args);
CHECK(error == nullptr);
};
}
PJRT_ErrorDeleter MakeErrorDeleter(const PJRT_Api* api) {
return [api](PJRT_Error* error) -> void {
PJRT_Error_Destroy_Args destroy_args;
destroy_args.struct_size = PJRT_Error_Destroy_Args_STRUCT_SIZE;
destroy_args.extension_start = nullptr;
destroy_args.error = error;
api->PJRT_Error_Destroy(&destroy_args);
};
}
PJRT_BufferDeleter MakeBufferDeleter(const PJRT_Api* api) {
return [api](PJRT_Buffer* buffer) -> void {
PJRT_Buffer_Destroy_Args destroy_args;
destroy_args.struct_size = PJRT_Buffer_Destroy_Args_STRUCT_SIZE;
destroy_args.extension_start = nullptr;
destroy_args.buffer = buffer;
pjrt::LogFatalIfPjrtError(api->PJRT_Buffer_Destroy(&destroy_args), api);
};
}
PJRT_ExecutableDeleter MakeExecutableDeleter(const PJRT_Api* api) {
return [api](PJRT_Executable* executable) -> void {
PJRT_Executable_Destroy_Args args;
args.struct_size = PJRT_Executable_Destroy_Args_STRUCT_SIZE;
args.extension_start = nullptr;
args.executable = executable;
pjrt::LogFatalIfPjrtError(api->PJRT_Executable_Destroy(&args), api);
};
}
PJRT_LoadedExecutableDeleter MakeLoadedExecutableDeleter(const PJRT_Api* api) {
return [api](PJRT_LoadedExecutable* executable) -> void {
PJRT_LoadedExecutable_Destroy_Args args;
args.struct_size = PJRT_LoadedExecutable_Destroy_Args_STRUCT_SIZE;
args.extension_start = nullptr;
args.executable = executable;
pjrt::LogFatalIfPjrtError(api->PJRT_LoadedExecutable_Destroy(&args), api);
};
}
absl::Status PjrtErrorToStatus(const PJRT_Error* error, const PJRT_Api* api) {
absl::Status status;
if (error != nullptr) {
status = absl::Status(PjrtErrorToStatusCode(error, api),
GetPjrtErrorMessage(error, api));
}
return status;
}
PJRT_TopologyDescriptionDeleter MakeTopologyDescriptionDeleter(
const PJRT_Api* api) {
return [api](PJRT_TopologyDescription* topology) -> void {
PJRT_TopologyDescription_Destroy_Args destroy_args;
destroy_args.struct_size =
PJRT_TopologyDescription_Destroy_Args_STRUCT_SIZE;
destroy_args.extension_start = nullptr;
destroy_args.topology = topology;
pjrt::LogFatalIfPjrtError(
api->PJRT_TopologyDescription_Destroy(&destroy_args), api);
};
}
PJRT_Layouts_MemoryLayoutDeleter MakeMemoryLayoutDeleter(const PJRT_Api* api) {
PJRT_Layouts_Extension* ext_api =
FindExtension<PJRT_Layouts_Extension>(api, PJRT_Extension_Type_Layouts);
CHECK_NE(ext_api, nullptr) << "MakeMemoryLayoutDeleter passed PJRT_Api that "
"doesn't support layouts extension";
return [api, ext_api](PJRT_Layouts_MemoryLayout* layout) -> void {
PJRT_Layouts_MemoryLayout_Destroy_Args args;
args.struct_size = PJRT_Layouts_MemoryLayout_Destroy_Args_STRUCT_SIZE;
args.extension_start = nullptr;
args.layout = layout;
pjrt::LogFatalIfPjrtError(ext_api->PJRT_Layouts_MemoryLayout_Destroy(&args),
api);
};
}
PJRT_Error_Code GetErrorCode(const PJRT_Error* error, const PJRT_Api* api) {
PJRT_Error_GetCode_Args args;
args.struct_size = PJRT_Error_GetCode_Args_STRUCT_SIZE;
args.extension_start = nullptr;
args.error = error;
pjrt::LogFatalIfPjrtError(api->PJRT_Error_GetCode(&args), api);
return args.code;
}
absl::StatusCode PjrtErrorToStatusCode(const PJRT_Error* error,
const PJRT_Api* api) {
return PjrtErrorCodeToStatusCode(GetErrorCode(error, api));
}
absl::StatusCode PjrtErrorCodeToStatusCode(PJRT_Error_Code code) {
switch (code) {
case PJRT_Error_Code_CANCELLED:
case PJRT_Error_Code_UNKNOWN:
case PJRT_Error_Code_INVALID_ARGUMENT:
case PJRT_Error_Code_DEADLINE_EXCEEDED:
case PJRT_Error_Code_NOT_FOUND:
case PJRT_Error_Code_ALREADY_EXISTS:
case PJRT_Error_Code_PERMISSION_DENIED:
case PJRT_Error_Code_RESOURCE_EXHAUSTED:
case PJRT_Error_Code_FAILED_PRECONDITION:
case PJRT_Error_Code_ABORTED:
case PJRT_Error_Code_OUT_OF_RANGE:
case PJRT_Error_Code_UNIMPLEMENTED:
case PJRT_Error_Code_INTERNAL:
case PJRT_Error_Code_UNAVAILABLE:
case PJRT_Error_Code_DATA_LOSS:
case PJRT_Error_Code_UNAUTHENTICATED:
return static_cast<absl::StatusCode>(code);
}
}
PJRT_Error_Code StatusCodeToPjrtErrorCode(absl::StatusCode code) {
switch (static_cast<tsl::error::Code>(code)) {
case tsl::error::CANCELLED:
case tsl::error::UNKNOWN:
case tsl::error::INVALID_ARGUMENT:
case tsl::error::DEADLINE_EXCEEDED:
case tsl::error::NOT_FOUND:
case tsl::error::ALREADY_EXISTS:
case tsl::error::PERMISSION_DENIED:
case tsl::error::UNAUTHENTICATED:
case tsl::error::RESOURCE_EXHAUSTED:
case tsl::error::FAILED_PRECONDITION:
case tsl::error::ABORTED:
case tsl::error::OUT_OF_RANGE:
case tsl::error::UNIMPLEMENTED:
case tsl::error::INTERNAL:
case tsl::error::UNAVAILABLE:
case tsl::error::DATA_LOSS:
return static_cast<PJRT_Error_Code>(code);
case tsl::error::OK:
CHECK(false) << "Status::OK() cannot be converted to PJRT_Error code, "
"use nullptr instead";
case tensorflow::error::
DO_NOT_USE_RESERVED_FOR_FUTURE_EXPANSION_USE_DEFAULT_IN_SWITCH_INSTEAD_:
CHECK(false) << "got DO_NOT_USE_RESERVED_FOR_FUTURE_EXPANSION_"
"USE_DEFAULT_IN_SWITCH_INSTEAD_";
case tensorflow::error::Code_INT_MIN_SENTINEL_DO_NOT_USE_:
CHECK(false) << "got Code_INT_MIN_SENTINEL_DO_NOT_USE_";
case tensorflow::error::Code_INT_MAX_SENTINEL_DO_NOT_USE_:
CHECK(false) << "got Code_INT_MAX_SENTINEL_DO_NOT_USE_";
}
}
absl::string_view GetPjrtErrorMessage(const PJRT_Error* error,
const PJRT_Api* api) {
PJRT_Error_Message_Args message_args;
message_args.struct_size = PJRT_Error_Message_Args_STRUCT_SIZE;
message_args.extension_start = nullptr;
message_args.error = error;
api->PJRT_Error_Message(&message_args);
return absl::string_view(message_args.message, message_args.message_size);
}
void LogFatalIfPjrtError(PJRT_Error* error, const PJRT_Api* api) {
std::unique_ptr<PJRT_Error, pjrt::PJRT_ErrorDeleter> _error(
error, MakeErrorDeleter(api));
absl::Status _status = PjrtErrorToStatus(_error.get(), api);
if (!_status.ok()) {
LOG(FATAL) << "Unexpected error status " << _status.message();
}
}
PJRT_EventDeleter MakeEventDeleter(const PJRT_Api* api) {
CHECK(api != nullptr);
return [api](PJRT_Event* managed) {
PJRT_Event_Destroy_Args args;
args.struct_size = PJRT_Event_Destroy_Args_STRUCT_SIZE;
args.extension_start = nullptr;
args.event = managed;
LogFatalIfPjrtError(api->PJRT_Event_Destroy(&args), api);
};
}
PJRT_Buffer_Type ConvertToPjRtBufferType(xla::PrimitiveType type) {
switch (type) {
case xla::PrimitiveType::PRIMITIVE_TYPE_INVALID:
return PJRT_Buffer_Type::PJRT_Buffer_Type_INVALID;
case xla::PrimitiveType::PRED:
return PJRT_Buffer_Type::PJRT_Buffer_Type_PRED;
case xla::PrimitiveType::TOKEN:
return PJRT_Buffer_Type::PJRT_Buffer_Type_TOKEN;
case xla::PrimitiveType::S2:
return PJRT_Buffer_Type::PJRT_Buffer_Type_S2;
case xla::PrimitiveType::S4:
return PJRT_Buffer_Type::PJRT_Buffer_Type_S4;
case xla::PrimitiveType::S8:
return PJRT_Buffer_Type::PJRT_Buffer_Type_S8;
case xla::PrimitiveType::S16:
return PJRT_Buffer_Type::PJRT_Buffer_Type_S16;
case xla::PrimitiveType::S32:
return PJRT_Buffer_Type::PJRT_Buffer_Type_S32;
case xla::PrimitiveType::S64:
return PJRT_Buffer_Type::PJRT_Buffer_Type_S64;
case xla::PrimitiveType::U2:
return PJRT_Buffer_Type::PJRT_Buffer_Type_U2;
case xla::PrimitiveType::U4:
return PJRT_Buffer_Type::PJRT_Buffer_Type_U4;
case xla::PrimitiveType::U8:
return PJRT_Buffer_Type::PJRT_Buffer_Type_U8;
case xla::PrimitiveType::U16:
return PJRT_Buffer_Type::PJRT_Buffer_Type_U16;
case xla::PrimitiveType::U32:
return PJRT_Buffer_Type::PJRT_Buffer_Type_U32;
case xla::PrimitiveType::U64:
return PJRT_Buffer_Type::PJRT_Buffer_Type_U64;
case xla::PrimitiveType::F16:
return PJRT_Buffer_Type::PJRT_Buffer_Type_F16;
case xla::PrimitiveType::F32:
return PJRT_Buffer_Type::PJRT_Buffer_Type_F32;
case xla::PrimitiveType::BF16:
return PJRT_Buffer_Type::PJRT_Buffer_Type_BF16;
case xla::PrimitiveType::F64:
return PJRT_Buffer_Type::PJRT_Buffer_Type_F64;
case xla::PrimitiveType::F8E5M2:
return PJRT_Buffer_Type::PJRT_Buffer_Type_F8E5M2;
case xla::PrimitiveType::F8E4M3FN:
return PJRT_Buffer_Type::PJRT_Buffer_Type_F8E4M3FN;
case xla::PrimitiveType::F8E4M3B11FNUZ:
return PJRT_Buffer_Type::PJRT_Buffer_Type_F8E4M3B11FNUZ;
case xla::PrimitiveType::F8E5M2FNUZ:
return PJRT_Buffer_Type::PJRT_Buffer_Type_F8E5M2FNUZ;
case xla::PrimitiveType::F8E4M3FNUZ:
return PJRT_Buffer_Type::PJRT_Buffer_Type_F8E4M3FNUZ;
case xla::PrimitiveType::C64:
return PJRT_Buffer_Type::PJRT_Buffer_Type_C64;
case xla::PrimitiveType::C128:
return PJRT_Buffer_Type::PJRT_Buffer_Type_C128;
default:
CHECK(false)
<< "Element type of the shape is not supported in C API layer: "
<< xla::primitive_util::LowercasePrimitiveTypeName(type);
}
}
xla::PrimitiveType ConvertFromPjRtBufferType(PJRT_Buffer_Type type) {
switch (type) {
case PJRT_Buffer_Type::PJRT_Buffer_Type_PRED:
return xla::PrimitiveType::PRED;
case PJRT_Buffer_Type::PJRT_Buffer_Type_TOKEN:
return xla::PrimitiveType::TOKEN;
case PJRT_Buffer_Type::PJRT_Buffer_Type_S2:
return xla::PrimitiveType::S2;
case PJRT_Buffer_Type::PJRT_Buffer_Type_S4:
return xla::PrimitiveType::S4;
case PJRT_Buffer_Type::PJRT_Buffer_Type_S8:
return xla::PrimitiveType::S8;
case PJRT_Buffer_Type::PJRT_Buffer_Type_S16:
return xla::PrimitiveType::S16;
case PJRT_Buffer_Type::PJRT_Buffer_Type_S32:
return xla::PrimitiveType::S32;
case PJRT_Buffer_Type::PJRT_Buffer_Type_S64:
return xla::PrimitiveType::S64;
case PJRT_Buffer_Type::PJRT_Buffer_Type_U2:
return xla::PrimitiveType::U2;
case PJRT_Buffer_Type::PJRT_Buffer_Type_U4:
return xla::PrimitiveType::U4;
case PJRT_Buffer_Type::PJRT_Buffer_Type_U8:
return xla::PrimitiveType::U8;
case PJRT_Buffer_Type::PJRT_Buffer_Type_U16:
return xla::PrimitiveType::U16;
case PJRT_Buffer_Type::PJRT_Buffer_Type_U32:
return xla::PrimitiveType::U32;
case PJRT_Buffer_Type::PJRT_Buffer_Type_U64:
return xla::PrimitiveType::U64;
case PJRT_Buffer_Type::PJRT_Buffer_Type_F16:
return xla::PrimitiveType::F16;
case PJRT_Buffer_Type::PJRT_Buffer_Type_F32:
return xla::PrimitiveType::F32;
case PJRT_Buffer_Type::PJRT_Buffer_Type_BF16:
return xla::PrimitiveType::BF16;
case PJRT_Buffer_Type::PJRT_Buffer_Type_F64:
return xla::PrimitiveType::F64;
case PJRT_Buffer_Type::PJRT_Buffer_Type_C64:
return xla::PrimitiveType::C64;
case PJRT_Buffer_Type::PJRT_Buffer_Type_C128:
return xla::PrimitiveType::C128;
case PJRT_Buffer_Type::PJRT_Buffer_Type_F8E5M2:
return xla::PrimitiveType::F8E5M2;
case PJRT_Buffer_Type::PJRT_Buffer_Type_F8E4M3FN:
return xla::PrimitiveType::F8E4M3FN;
case PJRT_Buffer_Type::PJRT_Buffer_Type_F8E4M3B11FNUZ:
return xla::PrimitiveType::F8E4M3B11FNUZ;
case PJRT_Buffer_Type::PJRT_Buffer_Type_F8E5M2FNUZ:
return xla::PrimitiveType::F8E5M2FNUZ;
case PJRT_Buffer_Type::PJRT_Buffer_Type_F8E4M3FNUZ:
return xla::PrimitiveType::F8E4M3FNUZ;
case PJRT_Buffer_Type::PJRT_Buffer_Type_INVALID:
CHECK(false) << "Buffer type is not supported in C API layer.";
}
}
const char* HostBufferSemanticsToString(
xla::PjRtClient::HostBufferSemantics h) {
switch (h) {
case xla::PjRtClient::HostBufferSemantics::kImmutableOnlyDuringCall:
return "xla::PjRtClient::HostBufferSemantics::kImmutableOnlyDuringCall";
case xla::PjRtClient::HostBufferSemantics::kImmutableZeroCopy:
return "xla::PjRtClient::HostBufferSemantics::kImmutableZeroCopy";
case xla::PjRtClient::HostBufferSemantics::kMutableZeroCopy:
return "xla::PjRtClient::HostBufferSemantics::kMutableZeroCopy";
case xla::PjRtClient::HostBufferSemantics::kImmutableUntilTransferCompletes:
return "xla::PjRtClient::HostBufferSemantics::"
"kImmutableUntilTransferCompletes";
}
}
PJRT_HostBufferSemantics ConvertToPjRtHostBufferSemantics(
xla::PjRtClient::HostBufferSemantics buffer_semantics) {
switch (buffer_semantics) {
case xla::PjRtClient::HostBufferSemantics::kImmutableOnlyDuringCall:
return PJRT_HostBufferSemantics::
PJRT_HostBufferSemantics_kImmutableOnlyDuringCall;
case xla::PjRtClient::HostBufferSemantics::kImmutableUntilTransferCompletes:
return PJRT_HostBufferSemantics::
PJRT_HostBufferSemantics_kImmutableUntilTransferCompletes;
case xla::PjRtClient::HostBufferSemantics::kImmutableZeroCopy:
return PJRT_HostBufferSemantics::
PJRT_HostBufferSemantics_kImmutableZeroCopy;
case xla::PjRtClient::HostBufferSemantics::kMutableZeroCopy:
return PJRT_HostBufferSemantics::
PJRT_HostBufferSemantics_kMutableZeroCopy;
default:
CHECK(false)
<< "Input host buffer semantics is not supported in C API layer: "
<< HostBufferSemanticsToString(buffer_semantics);
}
}
xla::PjRtClient::HostBufferSemantics ConvertFromPjRtHostBufferSemantics(
PJRT_HostBufferSemantics buffer_semantics) {
switch (buffer_semantics) {
case PJRT_HostBufferSemantics::
PJRT_HostBufferSemantics_kImmutableOnlyDuringCall:
return xla::PjRtClient::HostBufferSemantics::kImmutableOnlyDuringCall;
case PJRT_HostBufferSemantics::
PJRT_HostBufferSemantics_kImmutableUntilTransferCompletes:
return xla::PjRtClient::HostBufferSemantics::
kImmutableUntilTransferCompletes;
case PJRT_HostBufferSemantics::PJRT_HostBufferSemantics_kImmutableZeroCopy:
return xla::PjRtClient::HostBufferSemantics::kImmutableZeroCopy;
case PJRT_HostBufferSemantics::PJRT_HostBufferSemantics_kMutableZeroCopy:
return xla::PjRtClient::HostBufferSemantics::kMutableZeroCopy;
}
}
xla::PjRtFuture<> ConvertCEventToCppFuture(PJRT_Event* c_event,
const PJRT_Api* c_api) {
using xla::PjRtFuture;
PJRT_Event_OnReady_Args event_onready_args;
event_onready_args.struct_size = PJRT_Event_OnReady_Args_STRUCT_SIZE;
event_onready_args.extension_start = nullptr;
event_onready_args.event = c_event;
PjRtFuture<>::Promise promise = PjRtFuture<>::CreatePromise();
event_onready_args.user_arg = new std::function<void(PJRT_Error*)>(
[promise, c_event, c_api](PJRT_Error* error) mutable {
if (error != nullptr) {
promise.Set(::pjrt::PjrtErrorToStatus(error, c_api));
::pjrt::MakeErrorDeleter(c_api)(error);
} else {
promise.Set();
}
::pjrt::MakeEventDeleter(c_api)(c_event);
});
event_onready_args.callback = [](PJRT_Error* error, void* arg) {
std::function<void(PJRT_Error*)>* set_future =
reinterpret_ | #include "xla/pjrt/c/pjrt_c_api_helpers.h"
#include <cstddef>
#include <cstdint>
#include <memory>
#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 "absl/strings/str_cat.h"
#include "absl/time/time.h"
#include "xla/layout.h"
#include "xla/pjrt/c/pjrt_c_api.h"
#include "xla/pjrt/c/pjrt_c_api_wrapper_impl.h"
#include "xla/pjrt/distributed/in_memory_key_value_store.h"
#include "xla/pjrt/pjrt_client.h"
#include "xla/pjrt/pjrt_common.h"
#include "tsl/lib/core/status_test_util.h"
#include "tsl/platform/status.h"
#include "tsl/platform/status_matchers.h"
#include "tsl/platform/statusor.h"
namespace pjrt {
namespace {
using ::testing::HasSubstr;
TEST(PjRtCApiHelperTest, ConvertValidPjRtValueType) {
std::vector<int64_t> int64_list = {static_cast<int64_t>(1),
static_cast<int64_t>(2)};
absl::flat_hash_map<std::string, xla::PjRtValueType> original_cpp_map = {
{"string", "v1"},
{"int64", static_cast<int64_t>(1)},
{"int64_list", int64_list},
{"float", static_cast<float>(1.0)}};
TF_ASSERT_OK_AND_ASSIGN(std::vector<PJRT_NamedValue> c_map,
ConvertToPjRtNamedValueList(original_cpp_map));
auto converted_back_cpp_map =
ConvertFromPjRtNamedValueList(c_map.data(), c_map.size());
EXPECT_THAT(converted_back_cpp_map,
testing::UnorderedElementsAreArray(original_cpp_map));
}
TEST(PjRtCApiHelperTest, ValidOptionNameAndPjRtValueTypeIndex) {
const auto expected = absl::flat_hash_map<std::string, PJRT_NamedValue_Type>({
{"string", PJRT_NamedValue_Type::PJRT_NamedValue_kString},
{"int64", PJRT_NamedValue_Type::PJRT_NamedValue_kInt64},
});
absl::flat_hash_map<std::string, xla::PjRtValueType> valid_map = {
{"string", static_cast<std::string>("v1")},
{"int64", static_cast<int64_t>(1)}};
TF_EXPECT_OK(ValidateCreateOptions(valid_map, expected));
}
TEST(PjRtCApiHelperTest, InvalidOptionName) {
const auto expected = absl::flat_hash_map<std::string, PJRT_NamedValue_Type>({
{"string", PJRT_NamedValue_Type::PJRT_NamedValue_kString},
{"int64", PJRT_NamedValue_Type::PJRT_NamedValue_kInt64},
});
absl::flat_hash_map<std::string, xla::PjRtValueType> invalid_map = {
{"invalid", "v1"}};
auto status = ValidateCreateOptions(invalid_map, expected);
EXPECT_NE(status, absl::OkStatus());
EXPECT_THAT(status.message(),
HasSubstr("Unexpected option name passed to PJRT_Client_Create"));
}
TEST(PjRtCApiHelperTest, InvalidOptionTypeIndex) {
const auto expected = absl::flat_hash_map<std::string, PJRT_NamedValue_Type>({
{"string", PJRT_NamedValue_Type::PJRT_NamedValue_kString},
{"int64", PJRT_NamedValue_Type::PJRT_NamedValue_kInt64},
});
absl::flat_hash_map<std::string, xla::PjRtValueType> invalid_map = {
{"string", static_cast<int64_t>(1)}};
auto status = ValidateCreateOptions(invalid_map, expected);
EXPECT_NE(status, absl::OkStatus());
EXPECT_THAT(status.message(),
HasSubstr("Option passed to PJRT_Client_Create with name string "
"has type index 2 but expected type index is 0"));
}
TEST(PjRtCApiHelperTest, Callback) {
auto kv_store = std::make_shared<xla::InMemoryKeyValueStore>();
auto kv_callback_data = ConvertToCKeyValueCallbacks(kv_store);
auto converted_kv_store = ToCppKeyValueStore(
kv_callback_data->c_kv_get, &kv_callback_data->kv_get_c_func,
kv_callback_data->c_kv_put, &kv_callback_data->kv_put_c_func);
auto s = converted_kv_store->Set("key", "value");
TF_EXPECT_OK(s);
auto v = converted_kv_store->Get("key", absl::Seconds(1));
TF_EXPECT_OK(v.status());
EXPECT_EQ(*v, "value");
}
TEST(PjRtCApiHelperTest, ConvertToCLayoutFromStrides) {
std::vector<int64_t> strides = {4, 8};
absl::StatusOr<BufferMemoryLayoutData> layout_data =
ConvertToBufferMemoryLayoutData(strides);
EXPECT_TRUE(layout_data.ok());
EXPECT_EQ(
layout_data->c_layout.type,
PJRT_Buffer_MemoryLayout_Type::PJRT_Buffer_MemoryLayout_Type_Strides);
EXPECT_EQ(layout_data->c_layout.strides.num_byte_strides, 2);
EXPECT_EQ(layout_data->c_layout.strides.byte_strides[0], strides[0]);
EXPECT_EQ(layout_data->c_layout.strides.byte_strides[1], strides[1]);
}
TEST(PjRtCApiHelperTest, ConvertToCLayoutFromLayoutNoTiles) {
std::vector<int64_t> minor_to_major = {1, 0};
xla::Layout layout(minor_to_major);
TF_ASSERT_OK_AND_ASSIGN(BufferMemoryLayoutData layout_data,
ConvertToBufferMemoryLayoutData(layout));
EXPECT_EQ(layout_data.c_layout.type,
PJRT_Buffer_MemoryLayout_Type::PJRT_Buffer_MemoryLayout_Type_Tiled);
EXPECT_EQ(layout_data.c_layout.tiled.num_tiles, 0);
PJRT_Buffer_MemoryLayout_Tiled tiled = layout_data.c_layout.tiled;
EXPECT_EQ(tiled.minor_to_major_size, 2);
EXPECT_EQ(tiled.minor_to_major[0], minor_to_major[0]);
EXPECT_EQ(tiled.minor_to_major[1], minor_to_major[1]);
}
TEST(PjRtCApiHelperTest, ConvertToCLayoutFromLayoutWithTiles) {
std::vector<int64_t> minor_to_major = {1, 0};
xla::Layout layout(minor_to_major);
std::vector<int64_t> tile_dims_1 = {2, 4};
std::vector<int64_t> tile_dims_2 = {1};
layout.mutable_tiles()->push_back(xla::Tile(tile_dims_1));
layout.mutable_tiles()->push_back(xla::Tile(tile_dims_2));
TF_ASSERT_OK_AND_ASSIGN(BufferMemoryLayoutData layout_data,
ConvertToBufferMemoryLayoutData(layout));
EXPECT_EQ(layout_data.c_layout.type,
PJRT_Buffer_MemoryLayout_Type::PJRT_Buffer_MemoryLayout_Type_Tiled);
PJRT_Buffer_MemoryLayout_Tiled tiled = layout_data.c_layout.tiled;
EXPECT_EQ(tiled.minor_to_major_size, 2);
EXPECT_EQ(tiled.minor_to_major[0], minor_to_major[0]);
EXPECT_EQ(tiled.minor_to_major[1], minor_to_major[1]);
EXPECT_EQ(tiled.num_tiles, 2);
EXPECT_EQ(tiled.tile_dim_sizes[0], tile_dims_1.size());
EXPECT_EQ(tiled.tile_dim_sizes[1], tile_dims_2.size());
EXPECT_EQ(tiled.tile_dims[0], tile_dims_1[0]);
EXPECT_EQ(tiled.tile_dims[1], tile_dims_1[1]);
EXPECT_EQ(tiled.tile_dims[2], tile_dims_2[0]);
}
TEST(PjRtCApiHelperTest, ConvertFromCLayoutToLayout) {
PJRT_Buffer_MemoryLayout c_layout;
c_layout.type =
PJRT_Buffer_MemoryLayout_Type::PJRT_Buffer_MemoryLayout_Type_Tiled;
std::vector<int64_t> minor_to_major = {1, 0};
c_layout.tiled.minor_to_major_size = 2;
c_layout.tiled.minor_to_major = minor_to_major.data();
c_layout.tiled.num_tiles = 2;
std::vector<size_t> tile_dim_sizes = {2, 1};
c_layout.tiled.tile_dim_sizes = tile_dim_sizes.data();
std::vector<int64_t> tile_dims = {2, 4, 1};
c_layout.tiled.tile_dims = tile_dims.data();
TF_ASSERT_OK_AND_ASSIGN(xla::Layout layout, ConvertToLayout(c_layout.tiled));
EXPECT_EQ(layout.ToString(), "{1,0:T(2,4)(1)}");
}
TEST(PjRtCApiHelperTest, ConvertFromCLayoutToLayoutNoTile) {
PJRT_Buffer_MemoryLayout c_layout;
c_layout.type =
PJRT_Buffer_MemoryLayout_Type::PJRT_Buffer_MemoryLayout_Type_Tiled;
c_layout.tiled.num_tiles = 0;
std::vector<int64_t> minor_to_major = {1, 0};
c_layout.tiled.minor_to_major_size = 2;
c_layout.tiled.minor_to_major = minor_to_major.data();
TF_ASSERT_OK_AND_ASSIGN(xla::Layout layout, ConvertToLayout(c_layout.tiled));
EXPECT_EQ(layout.ToString(), "{1,0}");
}
}
} | 2,210 |
#ifndef XLA_PJRT_C_PJRT_C_API_GPU_H_
#define XLA_PJRT_C_PJRT_C_API_GPU_H_
#include "xla/pjrt/c/pjrt_c_api.h"
#include "xla/pjrt/c/pjrt_c_api_macros.h"
#ifdef __cplusplus
extern "C" {
#endif
PJRT_CAPI_EXPORT const PJRT_Api* GetPjrtApi();
#ifdef __cplusplus
}
#endif
#endif
#include "xla/pjrt/c/pjrt_c_api_gpu.h"
#include "absl/base/call_once.h"
#include "absl/log/initialize.h"
#include "xla/pjrt/c/pjrt_c_api.h"
#include "xla/pjrt/c/pjrt_c_api_gpu_internal.h"
#include "tsl/platform/platform.h"
const PJRT_Api* GetPjrtApi() {
#ifndef PLATFORM_GOOGLE
static absl::once_flag once;
absl::call_once(once, []() { absl::InitializeLog(); });
#endif
return pjrt::gpu_plugin::GetGpuPjrtApi();
} | #include "xla/pjrt/c/pjrt_c_api_gpu.h"
#include <cstdint>
#include <functional>
#include <memory>
#include <numeric>
#include <string>
#include <thread>
#include <utility>
#include <variant>
#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 "xla/ffi/api/ffi.h"
#include "xla/ffi/execution_context.h"
#include "xla/ffi/ffi_api.h"
#include "xla/literal.h"
#include "xla/literal_util.h"
#include "xla/pjrt/c/pjrt_c_api.h"
#include "xla/pjrt/c/pjrt_c_api_ffi_extension.h"
#include "xla/pjrt/c/pjrt_c_api_gpu_extension.h"
#include "xla/pjrt/c/pjrt_c_api_helpers.h"
#include "xla/pjrt/c/pjrt_c_api_test.h"
#include "xla/pjrt/c/pjrt_c_api_test_base.h"
#include "xla/pjrt/c/pjrt_c_api_wrapper_impl.h"
#include "xla/pjrt/distributed/in_memory_key_value_store.h"
#include "xla/pjrt/pjrt_common.h"
#include "xla/pjrt/pjrt_future.h"
#include "xla/service/custom_call_target_registry.h"
#include "xla/shape.h"
#include "xla/shape_util.h"
#include "xla/stream_executor/gpu/gpu_init.h"
#include "xla/tests/literal_test_util.h"
#include "tsl/platform/status.h"
#include "tsl/platform/status_matchers.h"
#include "tsl/platform/statusor.h"
namespace pjrt {
namespace {
#ifdef TENSORFLOW_USE_ROCM
const bool kUnused = (RegisterPjRtCApiTestFactory([]() { return GetPjrtApi(); },
"rocm"),
true);
#else
const bool kUnused = (RegisterPjRtCApiTestFactory([]() { return GetPjrtApi(); },
"cuda"),
true);
#endif
class PjrtCApiGpuTest : public PjrtCApiTestBase {
public:
PjrtCApiGpuTest() : PjrtCApiTestBase(GetPjrtApi()) {}
};
TEST_F(PjrtCApiGpuTest, CreateViewOfDeviceBuffer) {
std::unique_ptr<PJRT_Buffer, ::pjrt::PJRT_BufferDeleter> buffer =
create_buffer().first;
PJRT_Buffer_OpaqueDeviceMemoryDataPointer_Args device_buffer_ptr_args;
device_buffer_ptr_args.struct_size =
PJRT_Buffer_OpaqueDeviceMemoryDataPointer_Args_STRUCT_SIZE;
device_buffer_ptr_args.extension_start = nullptr;
device_buffer_ptr_args.buffer = buffer.get();
PJRT_Error* device_buffer_ptr_error =
api_->PJRT_Buffer_OpaqueDeviceMemoryDataPointer(&device_buffer_ptr_args);
ASSERT_EQ(device_buffer_ptr_error, nullptr);
PJRT_Buffer_Device_Args device_args = PJRT_Buffer_Device_Args{
PJRT_Buffer_Device_Args_STRUCT_SIZE,
nullptr,
buffer.get(),
};
PJRT_Error* device_error = api_->PJRT_Buffer_Device(&device_args);
ASSERT_EQ(device_error, nullptr);
PJRT_Client_CreateViewOfDeviceBuffer_Args create_view_args;
create_view_args.struct_size =
PJRT_Client_CreateViewOfDeviceBuffer_Args_STRUCT_SIZE;
create_view_args.extension_start = nullptr;
create_view_args.client = client_;
create_view_args.device_buffer_ptr = device_buffer_ptr_args.device_memory_ptr;
xla::Shape shape = xla::ShapeUtil::MakeShape(xla::S32, {4});
create_view_args.dims = shape.dimensions().data();
create_view_args.num_dims = shape.dimensions().size();
create_view_args.element_type =
pjrt::ConvertToPjRtBufferType(shape.element_type());
pjrt::BufferMemoryLayoutData c_layout_data;
TF_ASSERT_OK_AND_ASSIGN(
c_layout_data, pjrt::ConvertToBufferMemoryLayoutData(shape.layout()));
create_view_args.layout = &(c_layout_data.c_layout);
create_view_args.device = device_args.device;
std::function<void()> on_delete_callback = []() mutable {};
create_view_args.on_delete_callback_arg =
new std::function(on_delete_callback);
create_view_args.on_delete_callback = [](void* device_buffer_ptr,
void* user_arg) {
auto c_func = reinterpret_cast<std::function<void()>*>(user_arg);
(*c_func)();
delete c_func;
};
create_view_args.stream = reinterpret_cast<intptr_t>(nullptr);
PJRT_Error* error =
api_->PJRT_Client_CreateViewOfDeviceBuffer(&create_view_args);
ASSERT_EQ(error, nullptr);
std::unique_ptr<PJRT_Buffer, ::pjrt::PJRT_BufferDeleter> view_buffer(
create_view_args.buffer, ::pjrt::MakeBufferDeleter(api_));
PJRT_Buffer_ToHostBuffer_Args to_host_args;
to_host_args.struct_size = PJRT_Buffer_ToHostBuffer_Args_STRUCT_SIZE;
to_host_args.extension_start = nullptr;
to_host_args.src = view_buffer.get();
xla::Shape host_shape = xla::ShapeUtil::MakeShape(xla::F32, {4});
auto literal = std::make_shared<xla::Literal>(host_shape);
to_host_args.host_layout = nullptr;
to_host_args.dst = literal->untyped_data();
to_host_args.dst_size = xla::ShapeUtil::ByteSizeOfElements(host_shape);
to_host_args.event = nullptr;
PJRT_Error* to_host_error = api_->PJRT_Buffer_ToHostBuffer(&to_host_args);
ASSERT_EQ(to_host_error, nullptr);
xla::PjRtFuture<> transfer_to_host =
::pjrt::ConvertCEventToCppFuture(to_host_args.event, api_);
TF_CHECK_OK(transfer_to_host.Await());
ASSERT_EQ(literal->data<float>().size(), 4);
std::vector<float> float_data(4);
std::iota(float_data.begin(), float_data.end(), 41.0f);
EXPECT_TRUE(xla::LiteralTestUtil::Equal(
xla::LiteralUtil::CreateR1<float>(float_data), *literal));
}
TEST_F(PjrtCApiGpuTest, CreateAndDestroyExecuteContext) {
PJRT_ExecuteContext_Create_Args create_arg;
create_arg.struct_size = PJRT_ExecuteContext_Create_Args_STRUCT_SIZE;
create_arg.extension_start = nullptr;
create_arg.context = nullptr;
EXPECT_EQ(api_->PJRT_ExecuteContext_Create(&create_arg), nullptr);
EXPECT_NE(create_arg.context, nullptr);
const PJRT_FFI_Extension* ffi_extension =
pjrt::FindExtension<PJRT_FFI_Extension>(
api_, PJRT_Extension_Type::PJRT_Extension_Type_FFI);
ASSERT_NE(ffi_extension, nullptr);
std::string string_data = "string_data";
PJRT_FFI_UserData_Add_Args add_args;
add_args.struct_size = PJRT_FFI_UserData_Add_Args_STRUCT_SIZE;
add_args.extension_start = nullptr;
add_args.user_data.type_id = 42;
add_args.user_data.data = &string_data;
add_args.user_data.deleter = nullptr;
add_args.context = create_arg.context;
EXPECT_EQ(ffi_extension->user_data_add(&add_args), nullptr);
TF_ASSERT_OK_AND_ASSIGN(
auto lookup_user_data,
create_arg.context->execute_context->ffi_context().Lookup(
xla::ffi::ExecutionContext::TypeId(42)));
EXPECT_EQ(lookup_user_data, &string_data);
PJRT_ExecuteContext_Destroy_Args destroy_args;
destroy_args.struct_size = PJRT_Error_Destroy_Args_STRUCT_SIZE;
destroy_args.extension_start = nullptr;
destroy_args.context = create_arg.context;
api_->PJRT_ExecuteContext_Destroy(&destroy_args);
}
absl::StatusOr<PJRT_Client_Create_Args> BuildCreateArg(
::pjrt::PJRT_KeyValueCallbackData* kv_callback_data,
std::vector<PJRT_NamedValue>& c_options) {
PJRT_Client_Create_Args args;
args.struct_size = PJRT_Client_Create_Args_STRUCT_SIZE;
args.extension_start = nullptr;
args.create_options = c_options.data();
args.num_options = c_options.size();
args.kv_get_callback = kv_callback_data->c_kv_get;
args.kv_get_user_arg = &kv_callback_data->kv_get_c_func;
args.kv_put_callback = kv_callback_data->c_kv_put;
args.kv_put_user_arg = &kv_callback_data->kv_put_c_func;
args.client = nullptr;
return args;
}
TEST(PjrtCApiGpuKVStoreTest, CreateClientWithKVCallback) {
auto api = GetPjrtApi();
auto kv_store = std::make_shared<xla::InMemoryKeyValueStore>();
std::shared_ptr<::pjrt::PJRT_KeyValueCallbackData> kv_callback_data =
::pjrt::ConvertToCKeyValueCallbacks(kv_store);
int num_nodes = 2;
std::vector<std::thread> threads;
for (int i = 0; i < num_nodes; i++) {
threads.emplace_back([api, i, num_nodes,
kv_callback_data = kv_callback_data,
kv_store = kv_store] {
absl::flat_hash_map<std::string, xla::PjRtValueType> options = {
{"num_nodes", static_cast<int64_t>(num_nodes)},
{"node_id", static_cast<int64_t>(i)}};
TF_ASSERT_OK_AND_ASSIGN(std::vector<PJRT_NamedValue> c_options,
::pjrt::ConvertToPjRtNamedValueList(options));
TF_ASSERT_OK_AND_ASSIGN(
PJRT_Client_Create_Args create_arg,
BuildCreateArg(kv_callback_data.get(), c_options));
PJRT_Error* error = api->PJRT_Client_Create(&create_arg);
EXPECT_EQ(error, nullptr) << error->status.message();
PJRT_Client_Devices_Args device_args;
device_args.struct_size = PJRT_Client_Devices_Args_STRUCT_SIZE;
device_args.extension_start = nullptr;
device_args.client = create_arg.client;
PJRT_Error* device_error = api->PJRT_Client_Devices(&device_args);
EXPECT_EQ(device_error, nullptr);
EXPECT_EQ(device_args.num_devices, 2);
PJRT_Client_AddressableDevices_Args addressable_device_args;
addressable_device_args.struct_size =
PJRT_Client_AddressableDevices_Args_STRUCT_SIZE;
addressable_device_args.extension_start = nullptr;
addressable_device_args.client = create_arg.client;
PJRT_Error* addressable_device_error =
api->PJRT_Client_AddressableDevices(&addressable_device_args);
EXPECT_EQ(addressable_device_error, nullptr);
EXPECT_EQ(addressable_device_args.num_addressable_devices, 1);
PJRT_Client_Destroy_Args destroy_args;
destroy_args.struct_size = PJRT_Client_Destroy_Args_STRUCT_SIZE;
destroy_args.extension_start = nullptr;
destroy_args.client = create_arg.client;
PJRT_Error* destroy_error = api->PJRT_Client_Destroy(&destroy_args);
CHECK_EQ(destroy_error, nullptr);
});
}
for (auto& t : threads) {
t.join();
}
}
TEST(PjrtCApiGpuAllocatorTest, ValidOptionsParsing) {
auto api = GetPjrtApi();
std::vector<std::string> allocator_options = {"default", "platform", "bfc",
"cuda_async"};
for (const std::string& allocator_option : allocator_options) {
absl::flat_hash_map<std::string, xla::PjRtValueType> options = {
{"allocator", allocator_option},
{"visible_devices", xla::PjRtValueType(std::vector<int64_t>{0, 1})},
};
if (allocator_option == "bfc" || allocator_option == "cuda_async") {
options["memory_fraction"] = 0.5f;
}
if (allocator_option == "cuda_async") {
options["preallocate"] = true;
}
TF_ASSERT_OK_AND_ASSIGN(std::vector<PJRT_NamedValue> c_options,
::pjrt::ConvertToPjRtNamedValueList(options));
PJRT_Client_Create_Args create_arg;
create_arg.struct_size = PJRT_Client_Create_Args_STRUCT_SIZE;
create_arg.extension_start = nullptr;
create_arg.client = nullptr;
create_arg.create_options = c_options.data();
create_arg.num_options = c_options.size();
PJRT_Error* error = api->PJRT_Client_Create(&create_arg);
EXPECT_EQ(error, nullptr) << error->status.message();
PJRT_Client_Destroy_Args destroy_args;
destroy_args.struct_size = PJRT_Client_Destroy_Args_STRUCT_SIZE;
destroy_args.extension_start = nullptr;
destroy_args.client = create_arg.client;
PJRT_Error* destroy_error = api->PJRT_Client_Destroy(&destroy_args);
CHECK_EQ(destroy_error, nullptr);
}
}
TEST(PjrtCApiGpuAllocatorTest, InvalidAllocatorOptionsParsing) {
auto api = GetPjrtApi();
absl::flat_hash_map<std::string, xla::PjRtValueType> options = {
{"allocator", static_cast<std::string>("invalid_allocator")},
{"memory_fraction", 0.5f},
{"preallocate", true},
};
TF_ASSERT_OK_AND_ASSIGN(std::vector<PJRT_NamedValue> c_options,
::pjrt::ConvertToPjRtNamedValueList(options));
PJRT_Client_Create_Args create_arg;
create_arg.struct_size = PJRT_Client_Create_Args_STRUCT_SIZE;
create_arg.extension_start = nullptr;
create_arg.client = nullptr;
create_arg.create_options = c_options.data();
create_arg.num_options = c_options.size();
PJRT_Error* error = api->PJRT_Client_Create(&create_arg);
EXPECT_NE(error, nullptr);
EXPECT_THAT(error->status,
::tsl::testing::StatusIs(
absl::StatusCode::kUnimplemented,
"Allocator invalid_allocator not supported for PJRT GPU "
"plugin. Supported allocator options are: 'default', "
"'platform', 'bfc' and 'cuda_async'."));
PJRT_Error_Destroy_Args error_destroy_args;
error_destroy_args.struct_size = PJRT_Error_Destroy_Args_STRUCT_SIZE;
error_destroy_args.extension_start = nullptr;
error_destroy_args.error = error;
api->PJRT_Error_Destroy(&error_destroy_args);
}
TEST(PjrtCApiPlatformNameTest, AvailablePlatformName) {
auto api = GetPjrtApi();
std::string expected_platform_name_for_cuda = "cuda";
std::string expected_platform_name_for_rocm = "rocm";
absl::flat_hash_map<std::string, xla::PjRtValueType> options = {
{"platform_name", static_cast<std::string>("gpu")},
{"allocator", static_cast<std::string>("default")},
{"visible_devices", xla::PjRtValueType(std::vector<int64_t>{0, 1})},
};
TF_ASSERT_OK_AND_ASSIGN(std::vector<PJRT_NamedValue> c_options,
::pjrt::ConvertToPjRtNamedValueList(options));
PJRT_Client_Create_Args create_arg;
create_arg.struct_size = PJRT_Client_Create_Args_STRUCT_SIZE;
create_arg.extension_start = nullptr;
create_arg.client = nullptr;
create_arg.create_options = c_options.data();
create_arg.num_options = c_options.size();
PJRT_Error* error = api->PJRT_Client_Create(&create_arg);
EXPECT_EQ(error, nullptr) << error->status.message();
PJRT_Client_PlatformName_Args platform_name_args;
platform_name_args.struct_size = PJRT_Client_PlatformName_Args_STRUCT_SIZE;
platform_name_args.extension_start = nullptr;
platform_name_args.client = create_arg.client;
PJRT_Error* platform_name_error =
api->PJRT_Client_PlatformName(&platform_name_args);
EXPECT_EQ(platform_name_error, nullptr);
#if TENSORFLOW_USE_ROCM
EXPECT_EQ(platform_name_args.platform_name, expected_platform_name_for_rocm);
#else
EXPECT_EQ(platform_name_args.platform_name, expected_platform_name_for_cuda);
#endif
PJRT_Client_Destroy_Args destroy_args;
destroy_args.struct_size = PJRT_Client_Destroy_Args_STRUCT_SIZE;
destroy_args.extension_start = nullptr;
destroy_args.client = create_arg.client;
PJRT_Error* destroy_error = api->PJRT_Client_Destroy(&destroy_args);
CHECK_EQ(destroy_error, nullptr);
}
TEST(PjrtCApiPlatformNameTest, UnavailablePlatformName) {
auto api = GetPjrtApi();
absl::flat_hash_map<std::string, xla::PjRtValueType> options = {
{"platform_name", static_cast<std::string>("invalid_platform_name")},
{"allocator", static_cast<std::string>("default")},
{"visible_devices", xla::PjRtValueType(std::vector<int64_t>{0, 1})},
};
TF_ASSERT_OK_AND_ASSIGN(std::vector<PJRT_NamedValue> c_options,
::pjrt::ConvertToPjRtNamedValueList(options));
PJRT_Client_Create_Args create_arg;
create_arg.struct_size = PJRT_Client_Create_Args_STRUCT_SIZE;
create_arg.extension_start = nullptr;
create_arg.client = nullptr;
create_arg.create_options = c_options.data();
create_arg.num_options = c_options.size();
PJRT_Error* error = api->PJRT_Client_Create(&create_arg);
EXPECT_NE(error, nullptr);
EXPECT_THAT(error->status,
::tsl::testing::StatusIs(
absl::StatusCode::kNotFound,
testing::StartsWith("Could not find registered platform with "
"name: \"invalid_platform_name\". "
"Available platform names are:")));
PJRT_Error_Destroy_Args error_destroy_args;
error_destroy_args.struct_size = PJRT_Error_Destroy_Args_STRUCT_SIZE;
error_destroy_args.extension_start = nullptr;
error_destroy_args.error = error;
api->PJRT_Error_Destroy(&error_destroy_args);
}
void TestCustomCallV2() {}
TEST(PjrtCApiGpuExtensionTest, CustomCallUntyped) {
PJRT_Gpu_Register_Custom_Call_Args args;
args.struct_size = PJRT_Gpu_Register_Custom_Call_Args_STRUCT_SIZE;
std::string function_name = "untyped_function_name";
args.function_name = function_name.c_str();
args.function_name_size = function_name.size();
args.api_version = 0;
args.custom_call_function = reinterpret_cast<void*>(&TestCustomCallV2);
auto api = GetPjrtApi();
const PJRT_Extension_Base* next =
reinterpret_cast<const PJRT_Extension_Base*>(api->extension_start);
while (next != nullptr &&
next->type !=
PJRT_Extension_Type::PJRT_Extension_Type_Gpu_Custom_Call) {
next = next->next;
}
ASSERT_NE(next, nullptr);
PJRT_Error* error =
reinterpret_cast<const PJRT_Gpu_Custom_Call*>(next)->custom_call(&args);
CHECK_EQ(error, nullptr);
void* custom_call = xla::CustomCallTargetRegistry::Global()->Lookup(
function_name, stream_executor::GpuPlatformName());
EXPECT_EQ(custom_call, reinterpret_cast<void*>(&TestCustomCallV2));
}
static void* kNoop = xla::ffi::Ffi::Bind()
.To([]() { return xla::ffi::Error::Success(); })
.release();
TEST(PjrtCApiGpuExtensionTest, CustomCallTyped) {
PJRT_Gpu_Register_Custom_Call_Args args;
args.struct_size = PJRT_Gpu_Register_Custom_Call_Args_STRUCT_SIZE;
std::string function_name = "typed_function_name";
args.function_name = function_name.c_str();
args.function_name_size = function_name.size();
args.api_version = 1;
args.custom_call_function = kNoop;
auto api = GetPjrtApi();
const PJRT_Extension_Base* next =
reinterpret_cast<const PJRT_Extension_Base*>(api->extension_start);
while (next != nullptr &&
next->type !=
PJRT_Extension_Type::PJRT_Extension_Type_Gpu_Custom_Call) {
next = next->next;
}
ASSERT_NE(next, nullptr);
PJRT_Error* error =
reinterpret_cast<const PJRT_Gpu_Custom_Call*>(next)->custom_call(&args);
CHECK_EQ(error, nullptr);
auto registration =
xla::ffi::FindHandler(function_name, stream_executor::GpuPlatformName())
.value();
EXPECT_EQ(reinterpret_cast<void*>(registration.bundle.execute), kNoop);
}
}
} | 2,211 |
#ifndef XLA_PJRT_C_PJRT_C_API_CPU_H_
#define XLA_PJRT_C_PJRT_C_API_CPU_H_
#include "xla/pjrt/c/pjrt_c_api.h"
#ifdef __cplusplus
extern "C" {
#endif
const PJRT_Api* GetPjrtApi();
#ifdef __cplusplus
}
#endif
#endif
#include "xla/pjrt/c/pjrt_c_api_cpu.h"
#include "xla/pjrt/c/pjrt_c_api.h"
#include "xla/pjrt/c/pjrt_c_api_cpu_internal.h"
const PJRT_Api* GetPjrtApi() { return pjrt::cpu_plugin::GetCpuPjrtApi(); } | #include "xla/pjrt/c/pjrt_c_api_cpu.h"
#include "xla/pjrt/c/pjrt_c_api_test.h"
#include "xla/pjrt/c/pjrt_c_api_wrapper_impl.h"
namespace pjrt {
namespace {
const bool kUnused = (RegisterPjRtCApiTestFactory([]() { return GetPjrtApi(); },
"cpu"),
true);
}
} | 2,212 |
#ifndef XLA_PJRT_DISTRIBUTED_TOPOLOGY_UTIL_H_
#define XLA_PJRT_DISTRIBUTED_TOPOLOGY_UTIL_H_
#include <string>
#include <string_view>
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/time/time.h"
#include "absl/types/span.h"
#include "xla/pjrt/distributed/key_value_store_interface.h"
#include "xla/pjrt/distributed/protocol.pb.h"
#include "xla/pjrt/gpu/gpu_topology.pb.h"
namespace xla {
absl::StatusOr<std::string> GetBootIdString();
absl::Status ExchangeTopologies(std::string_view platform, int node_id,
int num_nodes,
absl::Duration get_local_topology_timeout,
absl::Duration get_global_topology_timeout,
KeyValueStoreInterface* kv_store,
const LocalTopologyProto& local_topology,
GlobalTopologyProto* global_topology,
bool assign_global_device_ids);
GlobalTopologyProto BuildGlobalTopology(
absl::Span<LocalTopologyProto> local_topologies,
bool assign_global_device_ids);
absl::StatusOr<GpuTopologyProto> BuildGpuTopology(
const GlobalTopologyProto& global_topology);
}
#endif
#include "xla/pjrt/distributed/topology_util.h"
#include <algorithm>
#include <fstream>
#include <map>
#include <set>
#include <string>
#include <string_view>
#include <vector>
#include "absl/container/flat_hash_map.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/ascii.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_join.h"
#include "absl/synchronization/blocking_counter.h"
#include "absl/synchronization/mutex.h"
#include "absl/time/time.h"
#include "absl/types/span.h"
#include "xla/pjrt/distributed/key_value_store_interface.h"
#include "xla/pjrt/distributed/protocol.pb.h"
#include "xla/pjrt/pjrt_client.h"
#include "xla/pjrt/utils.h"
#include "xla/util.h"
#include "tsl/platform/env.h"
#include "tsl/platform/errors.h"
#include "tsl/platform/logging.h"
#include "tsl/platform/statusor.h"
#include "tsl/platform/threadpool.h"
namespace xla {
static constexpr char kBootIdPath[] = "/proc/sys/kernel/random/boot_id";
absl::StatusOr<std::string> GetBootIdString() {
std::string boot_id_str;
#ifdef __linux__
std::ifstream file(kBootIdPath);
if (!file) {
return NotFound("%s not found.", kBootIdPath);
}
std::string line;
while (std::getline(file, line)) {
absl::StripAsciiWhitespace(&line);
absl::StrAppend(&boot_id_str, line);
}
#endif
return boot_id_str;
}
static std::string GetLocalTopologyKey(std::string_view platform, int node_id) {
return absl::StrCat("local_topology/", platform, "/", node_id);
}
static std::string GetGlobalTopologyKey(std::string_view platform) {
return absl::StrCat("global_topology/", platform);
}
static absl::StatusOr<std::vector<LocalTopologyProto>> GetAllLocalTopologies(
std::string_view platform, int num_nodes, KeyValueStoreInterface* kv_store,
absl::Duration timeout) {
std::vector<absl::StatusOr<std::string>> local_topology_strs(num_nodes);
tsl::thread::ThreadPool thread_pool(
tsl::Env::Default(), "GetAllLocalTopologies", DefaultThreadPoolSize());
absl::BlockingCounter blocking_counter(num_nodes);
absl::Mutex mu;
for (int i = 0; i < num_nodes; i++) {
thread_pool.Schedule([&, i] {
absl::StatusOr<std::string> local_topology_str =
kv_store->Get(GetLocalTopologyKey(platform, i), timeout);
{
absl::MutexLock lock(&mu);
local_topology_strs[i] = local_topology_str;
}
blocking_counter.DecrementCount();
});
}
blocking_counter.Wait();
std::vector<std::string> error_messages;
std::vector<LocalTopologyProto> local_topologies;
int max_num_failed_message = 10;
int failed_count = 0;
for (const absl::StatusOr<std::string>& str : local_topology_strs) {
if (str.ok()) {
LocalTopologyProto local;
local.ParseFromString(*str);
local_topologies.push_back(local);
} else {
error_messages.push_back(
absl::StrCat("Error ", ++failed_count, ": ", str.status().message()));
if (failed_count > max_num_failed_message) {
break;
}
}
}
if (error_messages.empty()) {
return local_topologies;
}
return absl::InternalError(
absl::StrCat("Getting local topologies failed: ",
absl::StrJoin(error_messages, "\n\n")));
}
GlobalTopologyProto BuildGlobalTopology(
absl::Span<LocalTopologyProto> local_topologies,
bool assign_global_device_ids) {
GlobalTopologyProto global_topology;
int next_global_device_id = 0;
int next_slice_index = 0;
absl::flat_hash_map<std::string, int> boot_id_to_slice_index;
for (LocalTopologyProto& local : local_topologies) {
std::string_view boot_id = local.boot_id();
auto [it, inserted] =
boot_id_to_slice_index.try_emplace(boot_id, next_slice_index);
if (inserted) {
++next_slice_index;
}
for (DeviceProto& device : *local.mutable_devices()) {
if (assign_global_device_ids) {
device.set_global_device_id(next_global_device_id++);
}
device.set_slice_index(it->second);
}
global_topology.add_nodes()->Swap(&local);
}
if (VLOG_IS_ON(10)) {
for (auto it = boot_id_to_slice_index.begin();
it != boot_id_to_slice_index.end(); ++it) {
LOG(INFO) << "BuildGlobalTopology boot_id_to_slice_index " << it->first
<< "->" << it->second;
}
}
return global_topology;
}
absl::Status ExchangeTopologies(std::string_view platform, int node_id,
int num_nodes,
absl::Duration get_local_topology_timeout,
absl::Duration get_global_topology_timeout,
KeyValueStoreInterface* kv_store,
const LocalTopologyProto& local_topology,
GlobalTopologyProto* global_topology,
bool assign_global_device_ids) {
VLOG(3) << "Local Topology for platform" << platform << ":\n"
<< local_topology.DebugString();
if (num_nodes == 1) {
LocalTopologyProto* topology = global_topology->add_nodes();
*topology = local_topology;
for (DeviceProto& device : *topology->mutable_devices()) {
device.set_global_device_id(device.local_device_ordinal());
}
return absl::OkStatus();
}
CHECK(kv_store != nullptr);
TF_RETURN_IF_ERROR(kv_store->Set(GetLocalTopologyKey(platform, node_id),
local_topology.SerializeAsString()));
std::string global_topology_key = GetGlobalTopologyKey(platform);
if (node_id == 0) {
TF_ASSIGN_OR_RETURN(std::vector<LocalTopologyProto> local_topologies,
GetAllLocalTopologies(platform, num_nodes, kv_store,
get_local_topology_timeout));
*global_topology =
BuildGlobalTopology(absl::Span<LocalTopologyProto>(local_topologies),
assign_global_device_ids);
TF_RETURN_IF_ERROR(kv_store->Set(global_topology_key,
global_topology->SerializeAsString()));
} else {
TF_ASSIGN_OR_RETURN(
std::string global_topology_str,
kv_store->Get(global_topology_key, get_global_topology_timeout));
global_topology->ParseFromString(global_topology_str);
}
VLOG(3) << "Global topology for platform " << platform << ":\n"
<< global_topology->DebugString();
return absl::OkStatus();
}
bool IsGpuTopologySymmetric(
const std::map<int, std::set<int>>& slice_id_to_node_ids,
const std::map<int, int>& node_id_to_device_count) {
CHECK(!slice_id_to_node_ids.empty());
CHECK(!node_id_to_device_count.empty());
int num_hosts_per_slice = slice_id_to_node_ids.begin()->second.size();
int num_devices_per_host = node_id_to_device_count.begin()->second;
for (const auto& [slice_id, node_ids] : slice_id_to_node_ids) {
if (node_ids.size() != num_hosts_per_slice) {
LOG(INFO) << "GpuTopology is asymmetric as it has different number "
"of hosts per slice.";
return false;
}
}
for (const auto& [node_id, device_count] : node_id_to_device_count) {
if (device_count != num_devices_per_host) {
LOG(INFO) << "GpuTopology is asymmetric as it has different number "
"of devices per host.";
return false;
}
}
return true;
}
absl::StatusOr<GpuTopologyProto> BuildGpuTopology(
const GlobalTopologyProto& global_topology) {
GpuTopologyProto gpu_topology;
std::map<int, std::set<int>> slice_id_to_node_ids;
std::map<int, int> node_id_to_device_count;
std::vector<int> device_ids;
for (int i = 0; i < global_topology.nodes_size(); ++i) {
const LocalTopologyProto& local_topology = global_topology.nodes(i);
node_id_to_device_count[local_topology.node_id()] =
local_topology.devices_size();
for (const DeviceProto& device : local_topology.devices()) {
if (gpu_topology.platform_version().empty()) {
gpu_topology.set_platform_version(device.name());
}
slice_id_to_node_ids[device.slice_index()].insert(
local_topology.node_id());
device_ids.push_back(device.global_device_id());
}
}
if (IsGpuTopologySymmetric(slice_id_to_node_ids, node_id_to_device_count)) {
gpu_topology.set_num_slices(slice_id_to_node_ids.size());
gpu_topology.set_num_hosts_per_slice(
slice_id_to_node_ids.begin()->second.size());
gpu_topology.set_num_devices_per_host(
node_id_to_device_count.begin()->second);
} else {
gpu_topology.set_num_slices(-1);
gpu_topology.set_num_hosts_per_slice(-1);
gpu_topology.set_num_devices_per_host(-1);
}
std::sort(device_ids.begin(), device_ids.end());
gpu_topology.mutable_device_ids()->Add(device_ids.begin(), device_ids.end());
return gpu_topology;
}
} | #include "xla/pjrt/distributed/topology_util.h"
#include <string>
#include <string_view>
#include <vector>
#include "absl/time/time.h"
#include "absl/types/span.h"
#include "xla/pjrt/distributed/in_memory_key_value_store.h"
#include "xla/pjrt/distributed/protocol.pb.h"
#include "xla/test_helpers.h"
#include "tsl/lib/core/status_test_util.h"
#include "tsl/platform/env.h"
#include "tsl/platform/statusor.h"
#include "tsl/platform/test.h"
#include "tsl/platform/threadpool.h"
namespace xla {
namespace {
TEST(TopologyTest, BuildGlobalTopology) {
std::vector<LocalTopologyProto> locals(2);
DeviceProto* d0 = locals[0].add_devices();
d0->set_local_device_ordinal(0);
DeviceProto* d1 = locals[0].add_devices();
d1->set_local_device_ordinal(0);
DeviceProto* d2 = locals[1].add_devices();
d2->set_local_device_ordinal(0);
DeviceProto* d3 = locals[1].add_devices();
d3->set_local_device_ordinal(1);
GlobalTopologyProto global =
BuildGlobalTopology(absl::Span<LocalTopologyProto>(locals),
true);
EXPECT_EQ(global.nodes_size(), 2);
EXPECT_EQ(global.nodes()[0].devices_size(), 2);
EXPECT_EQ(global.nodes()[1].devices_size(), 2);
}
TEST(TopologyTest, ExchangeTopology) {
int num_nodes = 2;
std::vector<LocalTopologyProto> locals(num_nodes);
DeviceProto* d0 = locals[0].add_devices();
d0->set_local_device_ordinal(0);
DeviceProto* d1 = locals[0].add_devices();
d1->set_local_device_ordinal(0);
DeviceProto* d2 = locals[1].add_devices();
d2->set_local_device_ordinal(0);
DeviceProto* d3 = locals[1].add_devices();
d3->set_local_device_ordinal(1);
InMemoryKeyValueStore kv_store;
std::vector<GlobalTopologyProto> globals(num_nodes);
{
tsl::thread::ThreadPool thread_pool(tsl::Env::Default(), "TestPool",
num_nodes);
for (int i = 0; i < num_nodes; i++) {
thread_pool.Schedule([&, i] {
TF_ASSERT_OK(ExchangeTopologies(
"cuda", i, num_nodes,
absl::Seconds(10),
absl::Seconds(10), &kv_store, locals[i], &globals[i],
true));
});
}
}
for (const GlobalTopologyProto& global : globals) {
EXPECT_EQ(global.nodes_size(), 2);
EXPECT_EQ(global.nodes()[0].devices_size(), 2);
EXPECT_EQ(global.nodes()[1].devices_size(), 2);
}
}
TEST(TopologyTest, BuildGpuTopology) {
std::string slice_0_boot_id = "foo";
std::string slice_1_boot_id = "bar";
std::vector<LocalTopologyProto> locals(2);
locals[0].set_boot_id(slice_0_boot_id);
locals[1].set_boot_id(slice_1_boot_id);
locals[0].set_node_id(0);
locals[1].set_node_id(1);
DeviceProto* d0 = locals[0].add_devices();
d0->set_local_device_ordinal(0);
DeviceProto* d1 = locals[0].add_devices();
d1->set_local_device_ordinal(1);
DeviceProto* d2 = locals[1].add_devices();
d2->set_local_device_ordinal(0);
DeviceProto* d3 = locals[1].add_devices();
d3->set_local_device_ordinal(1);
GlobalTopologyProto global =
BuildGlobalTopology(absl::Span<LocalTopologyProto>(locals),
true);
TF_ASSERT_OK_AND_ASSIGN(auto gpu_topology, BuildGpuTopology(global));
EXPECT_EQ(gpu_topology.device_ids_size(), 4);
EXPECT_EQ(gpu_topology.num_slices(), 2);
EXPECT_EQ(gpu_topology.num_hosts_per_slice(), 1);
EXPECT_EQ(gpu_topology.num_devices_per_host(), 2);
}
TEST(TopologyTest, BuildGpuTopologyWithDifferentNumHostsPerSlice) {
std::string slice_0_boot_id = "foo";
std::string slice_1_boot_id = "bar";
std::vector<LocalTopologyProto> locals(3);
locals[0].set_boot_id(slice_0_boot_id);
locals[1].set_boot_id(slice_0_boot_id);
locals[2].set_boot_id(slice_1_boot_id);
locals[0].set_node_id(0);
locals[1].set_node_id(1);
locals[2].set_node_id(2);
DeviceProto* d0 = locals[0].add_devices();
d0->set_local_device_ordinal(0);
DeviceProto* d1 = locals[1].add_devices();
d1->set_local_device_ordinal(0);
DeviceProto* d2 = locals[2].add_devices();
d2->set_local_device_ordinal(0);
GlobalTopologyProto global =
BuildGlobalTopology(absl::Span<LocalTopologyProto>(locals),
true);
TF_ASSERT_OK_AND_ASSIGN(auto gpu_topology, BuildGpuTopology(global));
EXPECT_EQ(gpu_topology.device_ids_size(), 3);
EXPECT_EQ(gpu_topology.num_slices(), -1);
EXPECT_EQ(gpu_topology.num_hosts_per_slice(), -1);
EXPECT_EQ(gpu_topology.num_devices_per_host(), -1);
}
TEST(TopologyTest, BuildGpuTopologyWithDifferentNumDevicesPerHost) {
std::string slice_0_boot_id = "foo";
std::string slice_1_boot_id = "bar";
std::vector<LocalTopologyProto> locals(2);
locals[0].set_boot_id(slice_0_boot_id);
locals[1].set_boot_id(slice_1_boot_id);
locals[0].set_node_id(0);
locals[1].set_node_id(1);
DeviceProto* d0 = locals[0].add_devices();
d0->set_local_device_ordinal(0);
DeviceProto* d1 = locals[0].add_devices();
d1->set_local_device_ordinal(1);
DeviceProto* d2 = locals[1].add_devices();
d2->set_local_device_ordinal(0);
GlobalTopologyProto global =
BuildGlobalTopology(absl::Span<LocalTopologyProto>(locals),
true);
TF_ASSERT_OK_AND_ASSIGN(auto gpu_topology, BuildGpuTopology(global));
EXPECT_EQ(gpu_topology.device_ids_size(), 3);
EXPECT_EQ(gpu_topology.num_slices(), -1);
EXPECT_EQ(gpu_topology.num_hosts_per_slice(), -1);
EXPECT_EQ(gpu_topology.num_devices_per_host(), -1);
}
}
} | 2,213 |
#ifndef XLA_PJRT_CPU_CPU_TOPOLOGY_H_
#define XLA_PJRT_CPU_CPU_TOPOLOGY_H_
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "absl/types/span.h"
#include "xla/pjrt/cpu/cpu_topology.pb.h"
#include "xla/pjrt/pjrt_common.h"
namespace xla {
class CpuTopology {
public:
struct CpuDevice {
int process_id;
int local_device_id;
bool operator==(const CpuDevice& other) const {
return process_id == other.process_id &&
local_device_id == other.local_device_id;
}
};
explicit CpuTopology(std::vector<CpuDevice> cpu_devices,
std::vector<std::string> machine_attributes)
: cpu_devices_(std::move(cpu_devices)),
machine_attributes_(std::move(machine_attributes)) {}
int number_of_devices() const { return cpu_devices_.size(); }
absl::Span<const CpuDevice> devices() const { return cpu_devices_; }
absl::Span<const std::string> machine_attributes() const {
return machine_attributes_;
}
static std::unique_ptr<const CpuTopology> FromProto(
const CpuTopologyProto& proto);
CpuTopologyProto ToProto() const;
private:
const std::vector<CpuDevice> cpu_devices_;
const std::vector<std::string> machine_attributes_;
};
static const int kMaxCpuDevicesPerProcess = 1 << 17;
inline PjRtGlobalDeviceId PackCpuDeviceId(int process_index, int device_id) {
return PjRtGlobalDeviceId(kMaxCpuDevicesPerProcess * process_index +
device_id);
}
inline int UnpackCpuProcessIndex(PjRtGlobalDeviceId global_device_id) {
return global_device_id.value() / kMaxCpuDevicesPerProcess;
}
inline int UnpackCpuDeviceId(PjRtGlobalDeviceId global_device_id) {
return global_device_id.value() % kMaxCpuDevicesPerProcess;
}
}
#endif
#include "xla/pjrt/cpu/cpu_topology.h"
#include <cstddef>
#include <memory>
#include <string>
#include <utility>
#include <vector>
namespace xla {
std::unique_ptr<const CpuTopology> CpuTopology::FromProto(
const CpuTopologyProto& cpu_topology_proto) {
std::vector<CpuTopology::CpuDevice> devices;
devices.reserve(cpu_topology_proto.cpu_devices_size());
for (size_t i = 0; i < cpu_topology_proto.cpu_devices_size(); ++i) {
auto& cpu_device_proto = cpu_topology_proto.cpu_devices(i);
devices.push_back(CpuDevice{cpu_device_proto.process_index(),
cpu_device_proto.local_hardware_id()});
}
std::vector<std::string> machine_attributes;
machine_attributes.reserve(cpu_topology_proto.machine_attributes_size());
for (size_t i = 0; i < cpu_topology_proto.machine_attributes_size(); ++i) {
machine_attributes.push_back(cpu_topology_proto.machine_attributes(i));
}
return std::make_unique<CpuTopology>(std::move(devices),
std::move(machine_attributes));
}
CpuTopologyProto CpuTopology::ToProto() const {
CpuTopologyProto proto;
for (auto& cpu_device : cpu_devices_) {
auto* cpu_device_proto = proto.add_cpu_devices();
cpu_device_proto->set_process_index(cpu_device.process_id);
cpu_device_proto->set_local_hardware_id(cpu_device.local_device_id);
}
for (const std::string& machine_attribute : machine_attributes_) {
proto.add_machine_attributes(machine_attribute);
}
return proto;
}
} | #include "xla/pjrt/cpu/cpu_topology.h"
#include <memory>
#include "tsl/platform/protobuf.h"
#include "tsl/platform/test.h"
namespace xla {
namespace {
TEST(CpuTopology, FromProto) {
CpuTopologyProto msg;
ASSERT_TRUE(tsl::protobuf::TextFormat::ParseFromString(
R"pb(
cpu_devices:
[ { process_index: 2, local_hardware_id: 3 }]
machine_attributes: [ "x86_64", "Intel" ]
)pb",
&msg));
std::unique_ptr<const CpuTopology> cpu_topology = CpuTopology::FromProto(msg);
EXPECT_EQ(cpu_topology->devices().size(), 1);
EXPECT_EQ(cpu_topology->devices()[0].process_id, 2);
EXPECT_EQ(cpu_topology->devices()[0].local_device_id, 3);
EXPECT_EQ(cpu_topology->machine_attributes().size(), 2);
EXPECT_EQ(cpu_topology->machine_attributes()[0], "x86_64");
EXPECT_EQ(cpu_topology->machine_attributes()[1], "Intel");
}
TEST(CpuTopology, ToProto) {
CpuTopology cpu_topology({{2, 3}}, {"ab", "cd"});
CpuTopologyProto msg = cpu_topology.ToProto();
EXPECT_EQ(msg.cpu_devices_size(), 1);
EXPECT_EQ(msg.cpu_devices(0).process_index(), 2);
EXPECT_EQ(msg.cpu_devices(0).local_hardware_id(), 3);
EXPECT_EQ(msg.machine_attributes_size(), 2);
EXPECT_EQ(msg.machine_attributes(0), "ab");
EXPECT_EQ(msg.machine_attributes(1), "cd");
}
}
} | 2,214 |
#ifndef XLA_PJRT_CPU_CPU_CLIENT_H_
#define XLA_PJRT_CPU_CPU_CLIENT_H_
#include <cstddef>
#include <cstdint>
#include <functional>
#include <memory>
#include <optional>
#include <string>
#include <utility>
#include <vector>
#include "absl/base/thread_annotations.h"
#include "absl/container/flat_hash_map.h"
#include "absl/container/inlined_vector.h"
#include "absl/functional/any_invocable.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/string_view.h"
#include "absl/synchronization/mutex.h"
#include "absl/types/span.h"
#include "unsupported/Eigen/CXX11/Tensor"
#include "mlir/IR/BuiltinOps.h"
#include "xla/client/xla_computation.h"
#include "xla/executable_run_options.h"
#include "xla/hlo/ir/hlo_module.h"
#include "xla/layout.h"
#include "xla/literal.h"
#include "xla/pjrt/cpu/abstract_tfrt_cpu_buffer.h"
#include "xla/pjrt/cpu/cpu_topology.h"
#include "xla/pjrt/cpu/tracked_tfrt_cpu_device_buffer.h"
#include "xla/pjrt/pjrt_client.h"
#include "xla/pjrt/pjrt_common.h"
#include "xla/pjrt/pjrt_compiler.h"
#include "xla/pjrt/pjrt_device_description.h"
#include "xla/pjrt/pjrt_executable.h"
#include "xla/pjrt/pjrt_future.h"
#include "xla/pjrt/semaphore.h"
#include "xla/pjrt/transpose.h"
#include "xla/service/buffer_assignment.h"
#include "xla/service/computation_placer.h"
#include "xla/service/cpu/collectives_interface.h"
#include "xla/service/cpu/cpu_event.h"
#include "xla/service/executable.h"
#include "xla/service/hlo.pb.h"
#include "xla/service/hlo_cost_analysis.h"
#include "xla/shape.h"
#include "xla/tsl/concurrency/async_value_ref.h"
#include "xla/util.h"
#include "xla/xla_data.pb.h"
#include "tsl/platform/errors.h"
#include "tsl/platform/fingerprint.h"
#include "tsl/platform/threadpool.h"
namespace xla {
class TfrtCpuDevice;
class TfrtCpuDeviceDescription final : public PjRtDeviceDescription {
public:
explicit TfrtCpuDeviceDescription(int process_id, int local_device_id);
int id() const override { return id_.value(); }
int process_index() const override { return process_index_; }
int local_hardware_id() const { return local_hardware_id_; }
absl::string_view device_kind() const override;
absl::string_view DebugString() const override;
absl::string_view ToString() const override;
const absl::flat_hash_map<std::string, PjRtDeviceAttribute>& Attributes()
const override {
return attributes_;
}
private:
PjRtGlobalDeviceId id_;
int process_index_;
int local_hardware_id_;
std::string debug_string_;
std::string to_string_;
absl::flat_hash_map<std::string, PjRtDeviceAttribute> attributes_ = {};
};
class TfrtCpuTopologyDescription : public PjRtTopologyDescription {
public:
static TfrtCpuTopologyDescription Create(
PjRtPlatformId platform_id, absl::string_view platform_name,
absl::string_view platform_version,
absl::Span<const std::unique_ptr<TfrtCpuDevice>> devices,
absl::Span<const std::string> machine_attributes);
TfrtCpuTopologyDescription(
const PjRtPlatformId platform_id, const absl::string_view platform_name,
const absl::string_view platform_version,
const std::vector<CpuTopology::CpuDevice> cpu_devices,
absl::Span<const std::string> machine_attributes)
: platform_id_(platform_id),
platform_name_(platform_name),
platform_version_(platform_version),
cpu_topology_(std::move(cpu_devices),
std::vector<std::string>(machine_attributes.begin(),
machine_attributes.end())) {}
bool operator==(const TfrtCpuTopologyDescription& other) const {
return this->platform_id() == other.platform_id() &&
this->platform_name() == other.platform_name() &&
this->platform_version() == other.platform_version() &&
this->cpu_topology().devices() == other.cpu_topology().devices();
}
PjRtPlatformId platform_id() const override { return platform_id_; }
absl::string_view platform_name() const override { return platform_name_; }
absl::string_view platform_version() const override {
return platform_version_;
}
std::vector<std::unique_ptr<const PjRtDeviceDescription>> DeviceDescriptions()
const override;
const CpuTopology& cpu_topology() const { return cpu_topology_; }
const CpuTopology* cpu_topology_ptr() const { return &cpu_topology_; }
bool is_subslice_topology() const override { return false; }
absl::StatusOr<int> ProcessCount() const override { return 1; }
absl::StatusOr<int> CoreCountOfDefaultType() const override {
return cpu_topology_.number_of_devices();
}
absl::StatusOr<int> LogicalDeviceCountOfDefaultType() const override {
return cpu_topology_.number_of_devices();
}
absl::StatusOr<int> CoreCountOfDefaultTypePerProcess() const override {
return cpu_topology_.number_of_devices();
}
absl::StatusOr<int> CoreCountOfDefaultTypePerChip() const override {
return 1;
}
absl::StatusOr<std::string> Serialize() const override;
const absl::flat_hash_map<std::string, PjRtDeviceAttribute>& Attributes()
const override {
return attributes_;
}
absl::StatusOr<Layout> GetDefaultLayout(
PrimitiveType element_type,
absl::Span<const int64_t> dims) const override;
private:
const PjRtPlatformId platform_id_;
const std::string platform_name_;
const std::string platform_version_;
const CpuTopology cpu_topology_;
absl::flat_hash_map<std::string, xla::PjRtDeviceAttribute> attributes_;
};
class TfrtCpuDevice final : public PjRtDevice {
public:
explicit TfrtCpuDevice(int process_id, int local_device_id,
int max_inflight_computations = 32);
const TfrtCpuDeviceDescription& description() const override {
return description_;
}
void SetClient(PjRtClient* client) {
CHECK(client_ == nullptr);
client_ = client;
}
PjRtClient* client() const override { return client_; }
bool IsAddressable() const override {
return process_index() == client()->process_index();
}
int local_hardware_id() const override {
return local_hardware_id_typed().value();
}
PjRtLocalDeviceId local_device_id() const override {
return PjRtLocalDeviceId(local_hardware_id_typed().value());
}
PjRtLocalHardwareId local_hardware_id_typed() const override {
return PjRtLocalHardwareId(description_.local_hardware_id());
}
absl::Status TransferToInfeed(const LiteralSlice& literal) override;
absl::Status TransferFromOutfeed(MutableBorrowingLiteral literal) override;
void AttachMemorySpace(PjRtMemorySpace* memory_space);
absl::Span<PjRtMemorySpace* const> memory_spaces() const override;
absl::StatusOr<PjRtMemorySpace*> default_memory_space() const override;
absl::StatusOr<PjRtMemorySpace*> memory_space_by_kind(
absl::string_view memory_space_kind) const override;
absl::StatusOr<PjRtMemorySpace*> memory_space_by_kind_id(int id) const;
Semaphore& max_inflight_computations_semaphore() {
return max_inflight_computations_semaphore_;
}
std::unique_ptr<ScopedAsyncTrackingEvent> CreateAsyncTrackingEvent(
absl::string_view description) const override {
return nullptr;
}
private:
PjRtClient* client_ = nullptr;
TfrtCpuDeviceDescription description_;
absl::InlinedVector<PjRtMemorySpace*, 1> memory_spaces_;
absl::flat_hash_map<int, PjRtMemorySpace*> memory_spaces_by_id_;
Semaphore max_inflight_computations_semaphore_;
};
class TfrtCpuClient final : public PjRtClient {
public:
TfrtCpuClient(int process_index,
std::vector<std::unique_ptr<TfrtCpuDevice>> devices,
std::shared_ptr<cpu::CollectivesInterface> collectives,
size_t num_threads, bool asynchronous);
~TfrtCpuClient() override;
int process_index() const override { return process_index_; }
int device_count() const override { return devices_.size(); }
int addressable_device_count() const override {
return addressable_devices_.size();
}
absl::Span<PjRtDevice* const> devices() const override { return devices_; }
absl::Span<PjRtDevice* const> addressable_devices() const override {
return addressable_devices_;
}
absl::StatusOr<PjRtDevice*> LookupDevice(
PjRtGlobalDeviceId global_device_id) const override;
absl::StatusOr<PjRtDevice*> LookupAddressableDevice(
PjRtLocalDeviceId local_device_id) const override;
absl::Span<PjRtMemorySpace* const> memory_spaces() const override;
PjRtPlatformId platform_id() const override {
return tsl::Fingerprint64(CpuName());
}
absl::string_view platform_name() const override { return CpuName(); }
absl::string_view platform_version() const override { return "<unknown>"; }
PjRtRuntimeType runtime_type() const override { return kTfrt; }
absl::StatusOr<DeviceAssignment> GetDefaultDeviceAssignment(
int num_replicas, int num_partitions) const override;
absl::StatusOr<Layout> GetDefaultLayout(
PrimitiveType element_type, absl::Span<const int64_t> dims) override;
absl::StatusOr<std::unique_ptr<HloCostAnalysis>> GetHloCostAnalysis()
const override;
absl::StatusOr<std::unique_ptr<PjRtLoadedExecutable>> Compile(
const XlaComputation& computation, CompileOptions options) override;
absl::StatusOr<std::unique_ptr<PjRtLoadedExecutable>> Compile(
mlir::ModuleOp module, CompileOptions options) override;
absl::StatusOr<std::unique_ptr<PjRtLoadedExecutable>> DeserializeExecutable(
absl::string_view serialized,
std::optional<CompileOptions> options) override;
absl::StatusOr<std::unique_ptr<PjRtBuffer>> CreateErrorBuffer(
absl::Status error, const Shape& shape, PjRtDevice* device) override;
absl::StatusOr<std::unique_ptr<PjRtBuffer>> CreateErrorBuffer(
absl::Status error, const Shape& shape, PjRtMemorySpace* memory) override;
absl::StatusOr<std::unique_ptr<PjRtBuffer>> CreateUninitializedBuffer(
const Shape& shape, PjRtDevice* device) override;
absl::StatusOr<std::unique_ptr<PjRtClient::AsyncHostToDeviceTransferManager>>
CreateBuffersForAsyncHostToDevice(absl::Span<const Shape> shapes,
PjRtDevice* device) override;
absl::StatusOr<std::unique_ptr<PjRtClient::AsyncHostToDeviceTransferManager>>
CreateBuffersForAsyncHostToDevice(absl::Span<const Shape> shapes,
PjRtMemorySpace* memory_space) override;
absl::StatusOr<std::unique_ptr<PjRtBuffer>> BufferFromHostBuffer(
const void* data, PrimitiveType type, absl::Span<int64_t const> dims,
std::optional<absl::Span<int64_t const>> byte_strides,
HostBufferSemantics host_buffer_semantics,
absl::AnyInvocable<void() &&> on_done_with_host_buffer,
PjRtDevice* device) override;
absl::StatusOr<std::unique_ptr<PjRtBuffer>> BufferFromHostBuffer(
const void* data, PrimitiveType type, absl::Span<int64_t const> dims,
std::optional<absl::Span<int64_t const>> byte_strides,
HostBufferSemantics host_buffer_semantics,
absl::AnyInvocable<void() &&> on_done_with_host_buffer,
PjRtDevice* device, const Layout* device_layout) override;
absl::StatusOr<std::unique_ptr<PjRtBuffer>> BufferFromHostBuffer(
const void* data, PrimitiveType type, absl::Span<int64_t const> dims,
std::optional<absl::Span<int64_t const>> byte_strides,
HostBufferSemantics host_buffer_semantics,
absl::AnyInvocable<void() &&> on_done_with_host_buffer,
PjRtMemorySpace* memory_space, const Layout* device_layout) override;
absl::StatusOr<std::unique_ptr<PjRtBuffer>> BufferFromHostLiteral(
const LiteralSlice& literal, PjRtDevice* device) override;
absl::StatusOr<std::unique_ptr<PjRtBuffer>> BufferFromHostLiteral(
const LiteralSlice& literal, PjRtMemorySpace* memory_space) override;
absl::StatusOr<std::vector<std::unique_ptr<PjRtBuffer>>>
MakeCrossHostReceiveBuffers(absl::Span<const Shape> shapes,
PjRtDevice* device,
PjRtCrossHostRecvNotifier notifier) override {
return Unimplemented("MakeCrossHostReceiveBuffers not implemented.");
}
absl::StatusOr<std::vector<std::unique_ptr<PjRtBuffer>>>
MakeCrossHostReceiveBuffersForGather(
absl::Span<const Shape> shapes, std::vector<GatherDetails> gather_details,
PjRtDevice* device, PjRtCrossHostRecvNotifier notifier) override {
return Unimplemented(
"MakeCrossHostReceiveBuffersForGather not implemented.");
}
absl::StatusOr<std::unique_ptr<PjRtBuffer>> CreateViewOfDeviceBuffer(
void* device_ptr, const Shape& shape, PjRtDevice* device,
std::function<void()> on_delete_callback,
std::optional<std::intptr_t> stream) override;
absl::StatusOr<ChannelHandle> CreateChannelHandle() override {
return Unimplemented("CreateChannelHandle not implemented.");
}
absl::StatusOr<ChannelHandle> CreateDeviceToHostChannelHandle() override {
return Unimplemented("CreateDeviceToHostChannelHandle not implemented.");
}
absl::StatusOr<ChannelHandle> CreateHostToDeviceChannelHandle() override {
return Unimplemented("CreateHostToDeviceChannelHandle not implemented.");
}
absl::Status Defragment() override {
return Unimplemented("Defragment not implemented.");
}
tsl::thread::ThreadPool* pjrt_client_thread_pool() const {
return pjrt_client_thread_pool_.get();
}
AsyncWorkRunner* async_work_runner() const {
return async_work_runner_.get();
}
Eigen::ThreadPoolDevice* eigen_intraop_device() const {
return eigen_intraop_device_.get();
}
tsl::AsyncValueRef<CpuEvent> GetLastCollectiveLaunchEvent() {
absl::MutexLock lock(&mu_);
return last_collective_launch_event_.CopyRef();
}
void SetLastCollectiveLaunchEvent(tsl::AsyncValueRef<CpuEvent> event) {
absl::MutexLock lock(&mu_);
last_collective_launch_event_ = std::move(event);
}
tsl::AsyncValueRef<CpuEvent> GetLastEnqueueEvent() {
return last_enqueue_event_.CopyRef();
}
void SetLastEnqueueEvent(tsl::AsyncValueRef<CpuEvent> event) {
last_enqueue_event_ = std::move(event);
}
absl::StatusOr<const xla::PjRtTopologyDescription*> GetTopologyDescription()
const override {
return &topology_;
}
private:
friend class TfrtCpuExecutable;
int process_index_;
std::vector<std::unique_ptr<TfrtCpuDevice>> owned_devices_;
std::vector<PjRtDevice*> devices_;
absl::flat_hash_map<PjRtGlobalDeviceId, TfrtCpuDevice*> id_to_device_;
std::vector<PjRtDevice*> addressable_devices_;
std::unique_ptr<ComputationPlacer> computation_placer_;
std::vector<std::unique_ptr<PjRtMemorySpace>> owned_memory_spaces_;
std::vector<PjRtMemorySpace*> memory_spaces_;
std::unique_ptr<tsl::thread::ThreadPool> pjrt_client_thread_pool_;
std::unique_ptr<AsyncWorkRunner> async_work_runner_;
std::unique_ptr<tsl::thread::ThreadPool> eigen_intraop_pool_;
std::unique_ptr<Eigen::ThreadPoolDevice> eigen_intraop_device_;
mutable absl::Mutex mu_;
tsl::AsyncValueRef<CpuEvent> last_collective_launch_event_
ABSL_GUARDED_BY(mu_);
absl::Mutex transpose_mu_;
TransposePlanCache transpose_cache_ ABSL_GUARDED_BY(transpose_mu_);
std::shared_ptr<cpu::CollectivesInterface> collectives_;
xla::TfrtCpuTopologyDescription topology_;
bool asynchronous_;
inline static thread_local tsl::AsyncValueRef<CpuEvent> last_enqueue_event_ =
tsl::MakeAvailableAsyncValueRef<CpuEvent>();
};
class TfrtCpuBuffer final : public AbstractTfrtCpuBuffer {
public:
TfrtCpuBuffer(
Shape on_device_shape,
std::unique_ptr<TrackedTfrtCpuDeviceBuffer> tracked_device_buffer,
TfrtCpuClient* client, TfrtCpuDevice* device,
PjRtMemorySpace* memory_space);
TfrtCpuBuffer(const TfrtCpuBuffer&) = delete;
TfrtCpuBuffer(TfrtCpuBuffer&&) = delete;
TfrtCpuBuffer& operator=(const TfrtCpuBuffer&) = delete;
TfrtCpuBuffer& operator=(TfrtCpuBuffer&&) = delete;
PjRtMemorySpace* memory_space() const override { return memory_space_; }
TfrtCpuDevice* device() const override { return device_; }
TfrtCpuClient* client() const override { return client_; }
using PjRtBuffer::ToLiteralSync;
PjRtFuture<> ToLiteral(MutableLiteralBase* literal) override;
PjRtFuture<> LazyToLiteral(
absl::AnyInvocable<absl::StatusOr<MutableLiteralBase*>() &&> generator)
override;
absl::StatusOr<std::unique_ptr<PjRtBuffer>> CopyToDevice(
PjRtDevice* dst_device) override;
absl::StatusOr<std::unique_ptr<PjRtBuffer>> CopyToMemorySpace(
PjRtMemorySpace* dst_memory_space) override;
private:
absl::string_view buffer_name() const override { return "TfrtCpuBuffer"; }
TfrtCpuClient* client_;
TfrtCpuDevice* const device_;
PjRtMemorySpace* const memory_space_;
};
class TfrtCpuExecutable final : public PjRtLoadedExecutable {
public:
TfrtCpuExecutable(
int num_replicas, int num_partitions,
std::shared_ptr<DeviceAssignment> device_assignment,
bool parameter_is_tupled_arguments, CompileOptions compile_options,
std::unique_ptr<Executable> cpu_executable,
BufferAllocation::Index result_buffer_index,
absl::InlinedVector<BufferAllocation::Index, 4> result_buffer_indices,
std::vector<LogicalDeviceIds> addressable_device_logical_ids,
std::vector<PjRtDevice*> addressable_devices, TfrtCpuClient* client);
~TfrtCpuExecutable() override = default;
TfrtCpuClient* client() const override { return client_; }
absl::string_view name() const override {
return cpu_executable_->shared_module()->name();
}
int num_replicas() const override { return num_replicas_; }
int num_partitions() const override { return num_partitions_; }
int64_t SizeOfGeneratedCodeInBytes() const override {
return cpu_executable_->SizeOfGeneratedCodeInBytes();
}
const DeviceAssignment& device_assignment() const override {
return *device_assignment_;
}
absl::Span<const LogicalDeviceIds> addressable_device_logical_ids()
const override {
return addressable_device_logical_ids_;
}
absl::Span<PjRtDevice* const> addressable_devices() const override {
return addressable_devices_;
}
absl::StatusOr<std::vector<std::shared_ptr<HloModule>>> GetHloModules()
const override {
return std::vector<std::shared_ptr<HloModule>>{
cpu_executable_->shared_module()};
}
absl::StatusOr<std::vector<std::vector<absl::string_view>>>
GetOutputMemoryKinds() const override {
return Unimplemented("GetOutputMemoryKinds is not supported.");
}
absl::StatusOr<CompiledMemoryStats> GetCompiledMemoryStats() const override {
CompiledMemoryStats memory_stats = CompiledMemoryStats();
memory_stats.generated_code_size_in_bytes = SizeOfGeneratedCodeInBytes();
const HloProto* proto = cpu_executable_->hlo_proto();
if (!proto) {
return tsl::errors::FailedPrecondition(
"cpu_executable_ has no hlo_proto.");
}
memory_stats.serialized_hlo_proto = proto->SerializeAsString();
memory_stats.PopulateBufferStatsFromAllocations(
cpu_executable_.get()->GetAllocations());
return memory_stats;
}
using PjRtLoadedExecutable::Execute;
absl::StatusOr<std::vector<std::vector<std::unique_ptr<PjRtBuffer>>>> Execute(
absl::Span<const std::vector<PjRtBuffer*>> argument_handles,
const ExecuteOptions& options,
std::optional<std::vector<PjRtFuture<>>>& returned_futures) override;
using PjRtLoadedExecutable::ExecuteSharded;
absl::StatusOr<std::vector<std::unique_ptr<PjRtBuffer>>> ExecuteSharded(
absl::Span<PjRtBuffer* const> argument_handles, PjRtDevice* device,
const ExecuteOptions& options,
std::optional<PjRtFuture<>>& returned_future, bool fill_future) override;
using PjRtLoadedExecutable::ExecutePortable;
absl::StatusOr<std::vector<std::unique_ptr<PjRtBuffer>>> ExecutePortable(
absl::Span<PjRtBuffer* const> argument_handles, PjRtDevice* device,
const ExecuteOptions& options,
std::optional<PjRtFuture<>>& returned_future, bool fill_future) override;
void Delete() override;
bool IsDeleted() override;
absl::StatusOr<std::string> SerializeExecutable() const override;
bool IsReturnedFutureSupported() const override { return true; }
absl::StatusOr<std::optional<std::string>> Fingerprint() const;
std::shared_ptr<Executable> cpu_executable() const { return cpu_executable_; }
absl::StatusOr<std::string> FingerprintExecutable() const override {
return Unimplemented("Fingerprinting executable is not supported.");
}
absl::StatusOr<CompileOptions> GetCompileOptions() const override {
return compile_options_;
}
private:
friend class TfrtCpuClient;
absl::Status SetUpDonation(bool tuple_inputs);
absl::Status CheckBufferCompatibilities(
absl::Span<std::pair<bool, TrackedTfrtCpuDeviceBuffer*> const>
input_buffers) const;
absl::StatusOr<Result> ExecuteHelper(
absl::Span<PjRtBuffer* const> argument_handles, int replica,
int partition, const RunId& run_id, const ExecuteOptions& options,
tsl::AsyncValueRef<CpuEvent> last_collective_launch_event,
bool fill_future, TfrtCpuDevice* device = nullptr);
TfrtCpuClient* client_;
int num_replicas_;
int num_partitions_;
std::shared_ptr<DeviceAssignment> device_assignment_;
bool parameter_is_tupled_arguments_;
CompileOptions compile_options_;
std::shared_ptr<Executable> cpu_executable_;
BufferAllocation::Index result_buffer_index_;
absl::InlinedVector<BufferAllocation::Index, 4> result_buffer_indices_;
std::vector<int64_t> input_buffer_sizes_in_bytes_;
std::vector<int> parameters_that_must_be_donated_;
std::vector<LogicalDeviceIds> addressable_device_logical_ids_;
std::vector<PjRtDevice*> addressable_devices_;
bool cheap_computation_;
};
struct CpuClientOptions {
bool asynchronous = true;
std::optional<int> cpu_device_count = std::nullopt;
int max_inflight_computations_per_device = 32;
int process_id = 0;
std::shared_ptr<cpu::CollectivesInterface> collectives;
};
absl::StatusOr<std::unique_ptr<PjRtClient>> GetTfrtCpuClient(
const CpuClientOptions& options);
inline absl::StatusOr<std::unique_ptr<PjRtClient>> GetTfrtCpuClient(
bool asynchronous) {
CpuClientOptions options;
options.asynchronous = asynchronous;
return GetTfrtCpuClient(options);
}
inline absl::StatusOr<std::unique_ptr<PjRtClient>> GetTfrtCpuClient(
bool asynchronous, int cpu_device_count,
int max_inflight_computations_per_device = 32) {
CpuClientOptions options;
options.asynchronous = asynchronous;
options.cpu_device_count = cpu_device_count;
options.max_inflight_computations_per_device =
max_inflight_computations_per_device;
return GetTfrtCpuClient(options);
}
}
#endif
#include "xla/pjrt/cpu/cpu_client.h"
#define EIGEN_USE_THREADS
#include <algorithm>
#include <cfenv>
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <functional>
#include <limits>
#include <memory>
#include <optional>
#include <string>
#include <utility>
#include <vector>
#include "absl/algorithm/container.h"
#include "absl/base/dynamic_annotations.h"
#include "absl/container/flat_hash_map.h"
#include "absl/container/inlined_vector.h"
#include "absl/functional/any_invocable.h"
#include "absl/log/check.h"
#include "absl/log/log.h"
#include "absl/memory/memory.h"
#include "absl/status/status.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_format.h"
#include "absl/strings/string_view.h"
#include "absl/synchronization/mutex.h"
#include "absl/types/span.h"
#include "unsupported/Eigen/CXX11/Tensor"
#include "mlir/IR/BuiltinOps.h"
#include "xla/array.h"
#include "xla/client/executable_build_options.h"
#include "xla/client/xla_computation.h"
#include "xla/debug_options_flags.h"
#include "xla/executable_run_options.h"
#include "xla/hlo/ir/hlo_computation.h"
#include "xla/hlo/ir/hlo_instruction.h"
#include "xla/hlo/ir/hlo_module.h"
#include "xla/layout.h"
#include "xla/layout_util.h"
#include "xla/literal.h"
#include "xla/literal_util.h"
#include "xla/pjrt/compile_options.pb.h"
#include "xla/pjrt/cpu/abstract_tfrt_cpu_buffer.h"
#include "xla/pjrt/cpu/cpu_topology.h"
#include "xla/pjrt/cpu/tracked_tfrt_cpu_device_buffer.h"
#include "xla/pjrt/host_memory_spaces.h"
#include "xla/pjrt/mlir_to_hlo.h"
#include "xla/pjrt/pjrt_client.h"
#include "xla/pjrt/pjrt_common.h"
#include "xla/pjrt/pjrt_compiler.h"
#include "xla/pjrt/pjrt_device_description.h"
#include "xla/pjrt/pjrt_executable.h"
#include "xla/pjrt/pjrt_future.h"
#include "xla/pjrt/semaphore.h"
#include "xla/pjrt/transpose.h"
#include "xla/pjrt/utils.h"
#include "xla/service/buffer_assignment.h"
#include "xla/service/compiler.h"
#include "xla/service/computation_placer.h"
#include "xla/service/cpu/collectives_interface.h"
#include "xla/service/cpu/cpu_compiler.h"
#include "xla/service/cpu/cpu_event.h"
#include "xla/service/cpu/cpu_executable.h"
#include "xla/service/cpu/cpu_executable_run_options.h"
#include "xla/service/cpu/cpu_runtime.h"
#include "xla/service/cpu/cpu_xfeed.h"
#include "xla/service/cpu/runtime/buffer_allocations.h"
#include "xla/service/cpu/runtime/task.h"
#include "xla/service/cpu/runtime/thunk.h"
#include "xla/service/cpu/runtime/thunk_executor.h"
#include "xla/service/cpu/simple_orc_jit.h"
#include "xla/service/custom_call_status.h"
#include "xla/service/custom_call_status_internal.h"
#include "xla/service/dump.h"
#include "xla/service/executable.h"
#include "xla/service/hlo.pb.h"
#include "xla/service/hlo_cost_analysis.h"
#include "xla/service/hlo_module_config.h"
#include "xla/service/hlo_module_util.h"
#include "xla/service/hlo_value.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.h"
#include "xla/tsl/concurrency/async_value_ref.h"
#include "xla/tsl/concurrency/ref_count.h"
#include "xla/util.h"
#include "xla/xla.pb.h"
#include "xla/xla_data.pb.h"
#include "tsl/lib/strings/proto_serialization.h"
#include "tsl/platform/casts.h"
#include "tsl/platform/denormal.h"
#include "tsl/platform/env.h"
#include "tsl/platform/errors.h"
#include "tsl/platform/setround.h"
#include "tsl/platform/statusor.h"
#include "tsl/platform/threadpool.h"
#include "tsl/profiler/lib/connected_traceme.h"
#include "tsl/profiler/lib/context_types.h"
#include "tsl/profiler/lib/traceme.h"
namespace xla {
namespace {
absl::StatusOr<std::unique_ptr<TfrtCpuBuffer>> AllocateDestinationBuffer(
const Shape& on_device_shape,
absl::InlinedVector<tsl::AsyncValueRef<CpuEvent>, 4> definition_events,
TfrtCpuDevice* device, TfrtCpuClient* client) {
TF_ASSIGN_OR_RETURN(
std::unique_ptr<TrackedTfrtCpuDeviceBuffer> tracked_device_buffer,
AbstractTfrtCpuBuf | #include "xla/pjrt/cpu/cpu_client.h"
#ifndef _WIN32
#include <unistd.h>
#endif
#include <algorithm>
#include <cstdint>
#include <cstring>
#include <memory>
#include <optional>
#include <string>
#include <vector>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "absl/status/status.h"
#include "absl/synchronization/notification.h"
#include "xla/client/xla_computation.h"
#include "xla/ffi/ffi.h"
#include "xla/ffi/ffi_api.h"
#include "xla/literal.h"
#include "xla/literal_util.h"
#include "xla/pjrt/host_memory_spaces.h"
#include "xla/pjrt/pjrt_client.h"
#include "xla/pjrt/pjrt_executable.h"
#include "xla/service/hlo_parser.h"
#include "xla/shape.h"
#include "xla/shape_util.h"
#include "xla/tests/literal_test_util.h"
#include "xla/tests/test_utils.h"
#include "xla/util.h"
#include "tsl/lib/core/status_test_util.h"
#include "tsl/platform/env.h"
#include "tsl/platform/errors.h"
#include "tsl/platform/file_system.h"
#include "tsl/platform/status_matchers.h"
#include "tsl/platform/statusor.h"
#include "tsl/platform/test.h"
namespace xla {
namespace {
using ::testing::Each;
using ::testing::ElementsAre;
using ::testing::ElementsAreArray;
using ::testing::HasSubstr;
using ::testing::IsFalse;
using ::tsl::testing::IsOkAndHolds;
static absl::Status TestError(ffi::AnyBuffer, ffi::Result<ffi::AnyBuffer>,
ffi::Result<ffi::AnyBuffer>) {
return absl::InternalError("test error.");
}
XLA_FFI_DEFINE_HANDLER(kTestError, TestError,
ffi::Ffi::Bind()
.Arg<ffi::AnyBuffer>()
.Ret<ffi::AnyBuffer>()
.Ret<ffi::AnyBuffer>()
);
XLA_FFI_REGISTER_HANDLER(ffi::GetXlaFfiApi(), "__xla_test$$TestError", "Host",
kTestError);
TEST(TfrtCpuClientTest, MemorySpace) {
TF_ASSERT_OK_AND_ASSIGN(auto client, GetTfrtCpuClient(CpuClientOptions()));
ASSERT_GE(client->devices().size(), 1);
ASSERT_EQ(client->memory_spaces().size(),
client->addressable_devices().size());
for (auto* device : client->devices()) {
TF_ASSERT_OK_AND_ASSIGN(auto* memory_space, device->default_memory_space());
EXPECT_THAT(device->memory_spaces(), ElementsAre(memory_space));
EXPECT_EQ(memory_space->kind(), UnpinnedHostMemorySpace::kKind);
EXPECT_EQ(memory_space->kind_id(), UnpinnedHostMemorySpace::kKindId);
EXPECT_THAT(device->memory_space_by_kind(UnpinnedHostMemorySpace::kKind),
IsOkAndHolds(memory_space));
}
}
TEST(TfrtCpuClientTest, DonationWithExecutionError) {
constexpr char kProgram[] =
R"(
HloModule DonationWithExecutionError,
input_output_alias={ {}: (0, {}, must-alias) }
ENTRY DonationWithExecutionError() -> f32[2, 2] {
%input = f32[2, 2] parameter(0)
%custom-call = (f32[2, 2], u8[0]) custom-call(%input),
custom_call_target="__xla_test$$TestError",
api_version=API_VERSION_TYPED_FFI,
output_to_operand_aliasing={{0}: (0, {})}
ROOT %result = f32[2, 2] get-tuple-element(%custom-call), index=0
})";
TF_ASSERT_OK_AND_ASSIGN(auto client, GetTfrtCpuClient(CpuClientOptions()));
TF_ASSERT_OK_AND_ASSIGN(auto hlo_module,
ParseAndReturnUnverifiedModule(kProgram, {}));
XlaComputation xla_computation(hlo_module->ToProto());
TF_ASSERT_OK_AND_ASSIGN(auto pjrt_executable,
client->Compile(xla_computation, {}));
std::vector<float> data(4, 0);
Shape shape = ShapeUtil::MakeShape(F32, {2, 2});
TF_ASSERT_OK_AND_ASSIGN(
auto buffer,
client->BufferFromHostBuffer(
data.data(), shape.element_type(), shape.dimensions(),
std::nullopt,
PjRtClient::HostBufferSemantics::kImmutableOnlyDuringCall, nullptr,
client->addressable_devices()[0]));
auto result = pjrt_executable->Execute({{buffer.get()}},
{});
ASSERT_FALSE(result.ok());
EXPECT_THAT(result.status().message(), ::testing::HasSubstr("test error."));
result = pjrt_executable->Execute({{buffer.get()}},
{});
ASSERT_FALSE(result.ok());
EXPECT_THAT(result.status().message(),
::testing::HasSubstr("buffer has been deleted or donated."));
}
TEST(TfrtCpuClientTest, HloSnapshot) {
constexpr char kProgram[] = R"(
HloModule add
ENTRY add {
x = f32[3,2] parameter(0)
y = f32[3,2] parameter(1)
ROOT add = f32[3,2] add(x, y)
})";
CpuClientOptions cpu_options;
cpu_options.cpu_device_count = 1;
TF_ASSERT_OK_AND_ASSIGN(auto client, GetTfrtCpuClient(cpu_options));
TF_ASSERT_OK_AND_ASSIGN(auto hlo_module,
ParseAndReturnUnverifiedModule(kProgram, {}));
std::string dir = tsl::testing::TmpDir();
xla::CompileOptions options;
auto* debug_opts = options.executable_build_options.mutable_debug_options();
debug_opts->set_xla_dump_to(dir);
debug_opts->set_xla_dump_hlo_snapshots(true);
XlaComputation xla_computation(hlo_module->ToProto());
TF_ASSERT_OK_AND_ASSIGN(auto pjrt_executable,
client->Compile(xla_computation, options));
std::vector<float> data1{1.0, 2.0, 3.0, 4.0, 5.0, 6.0};
std::vector<float> data2{10.0, 20.0, 30.0, 40.0, 50.0, 60.0};
Shape shape = ShapeUtil::MakeShape(F32, {3, 2});
TF_ASSERT_OK_AND_ASSIGN(
auto buffer1,
client->BufferFromHostBuffer(
data1.data(), shape.element_type(), shape.dimensions(),
std::nullopt,
PjRtClient::HostBufferSemantics::kImmutableOnlyDuringCall, nullptr,
client->addressable_devices()[0]));
TF_ASSERT_OK_AND_ASSIGN(
auto buffer2,
client->BufferFromHostBuffer(
data2.data(), shape.element_type(), shape.dimensions(),
std::nullopt,
PjRtClient::HostBufferSemantics::kImmutableOnlyDuringCall, nullptr,
client->addressable_devices()[0]));
auto result = pjrt_executable->Execute(
{{buffer1.get(), buffer2.get()}},
{});
ASSERT_TRUE(result.ok());
tsl::FileSystem* fs;
ASSERT_TRUE(tsl::Env::Default()->GetFileSystemForFile(dir, &fs).ok());
std::vector<std::string> paths;
ASSERT_TRUE(fs->GetMatchingPaths(dir + "false,
[]() {}));
TF_ASSERT_OK(transfer_manager->TransferRawDataToSubBuffer(
0, raw_data_view.data(), raw_data_size - 1, 1, true,
[]() {}));
TF_ASSERT_OK_AND_ASSIGN(auto literal, buffer->ToLiteralSync());
ASSERT_EQ(literal->element_count(), 3 * 2);
EXPECT_THAT(literal->data<uint32_t>(), Each(0x42424242));
}
struct MemsetValue {
explicit MemsetValue(float value) : value(value) {}
float value;
};
static absl::Status MemsetFromValue(
ffi::Result<ffi::BufferR1<PrimitiveType::F32>> result,
MemsetValue* memset_value) {
for (size_t i = 0; i < result->dimensions.at(0); ++i) {
result->data.base()[i] = memset_value->value;
}
return absl::OkStatus();
}
XLA_FFI_DEFINE_HANDLER(kMemsetFromValue, MemsetFromValue,
ffi::Ffi::Bind()
.Ret<ffi::BufferR1<PrimitiveType::F32>>()
.Ctx<ffi::UserData<MemsetValue>>());
XLA_FFI_REGISTER_HANDLER(ffi::GetXlaFfiApi(), "MemsetFromValue", "HOST",
kMemsetFromValue);
TEST(TfrtCpuClientTest, ForwardUserDataToFfiHandler) {
static constexpr char const* kProgram = R"(
HloModule ffi_handler
ENTRY main {
ROOT %custom-call = f32[4] custom-call(),
custom_call_target="MemsetFromValue",
api_version=API_VERSION_TYPED_FFI
})";
TF_ASSERT_OK_AND_ASSIGN(auto client, GetTfrtCpuClient(CpuClientOptions()));
TF_ASSERT_OK_AND_ASSIGN(auto hlo_module,
ParseAndReturnUnverifiedModule(kProgram, {}));
XlaComputation xla_computation(hlo_module->ToProto());
TF_ASSERT_OK_AND_ASSIGN(auto executable,
client->Compile(xla_computation, {}));
ExecuteContext context;
TF_ASSERT_OK(context.ffi_context().Emplace<MemsetValue>(42.0f));
ExecuteOptions opts;
opts.context = &context;
auto result = executable->Execute({{}}, opts);
TF_ASSERT_OK_AND_ASSIGN(std::shared_ptr<xla::Literal> result_literal,
result->at(0).at(0)->ToLiteralSync());
EXPECT_TRUE(LiteralTestUtil::Equal(
LiteralUtil::CreateR1<float>({42.0f, 42.0f, 42.0f, 42.0f}),
*result_literal));
}
}
} | 2,215 |
#ifndef XLA_PJRT_CPU_GLOO_COLLECTIVES_H_
#define XLA_PJRT_CPU_GLOO_COLLECTIVES_H_
#include <cstddef>
#include <memory>
#include <optional>
#include <tuple>
#include <vector>
#include "absl/base/thread_annotations.h"
#include "absl/container/flat_hash_map.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/synchronization/mutex.h"
#include "absl/time/time.h"
#include "absl/types/span.h"
#include "third_party/gloo/gloo/context.h"
#include "third_party/gloo/gloo/rendezvous/store.h"
#include "third_party/gloo/gloo/transport/device.h"
#include "xla/service/collective_ops_utils.h"
#include "xla/service/cpu/collectives_interface.h"
#include "xla/service/global_device_id.h"
#include "xla/xla_data.pb.h"
namespace xla::cpu {
class GlooCollectivesCommunicator : public CollectivesCommunicator {
public:
explicit GlooCollectivesCommunicator(std::shared_ptr<gloo::Context> context);
~GlooCollectivesCommunicator() override;
absl::Status AllReduce(const RendezvousKey& key, ReductionKind reduction_kind,
PrimitiveType element_type, size_t num_elements,
const void* input_buffer, void* output_buffer,
absl::Duration timeout) override;
absl::Status CollectivePermute(const RendezvousKey& key, size_t num_bytes,
std::optional<int> source_rank,
absl::Span<int const> target_ranks,
const void* input_buffer, void* output_buffer,
absl::Duration timeout) override;
absl::Status AllToAll(const RendezvousKey& key, size_t chunk_bytes,
absl::Span<const void* const> input_buffers,
absl::Span<void* const> output_buffers,
absl::Duration timeout) override;
absl::Status AllGather(const RendezvousKey& key, size_t chunk_bytes,
const void* input_buffer, void* output_buffer,
absl::Duration timeout) override;
absl::Status ReduceScatter(const RendezvousKey& key,
ReductionKind reduction_kind,
PrimitiveType element_type, size_t chunk_elems,
const void* input_buffer, void* output_buffer,
absl::Duration timeout) override;
private:
std::shared_ptr<gloo::Context> context_;
};
class GlooCollectives : public CollectivesInterface {
public:
GlooCollectives(std::unique_ptr<gloo::rendezvous::Store> store,
std::shared_ptr<gloo::transport::Device> device);
~GlooCollectives() override;
absl::StatusOr<std::shared_ptr<CollectivesCommunicator>> GetCommunicator(
absl::Span<GlobalDeviceId const> devices, int rank) override;
private:
std::unique_ptr<gloo::rendezvous::Store> store_;
std::shared_ptr<gloo::transport::Device> device_;
absl::Mutex mu_;
absl::flat_hash_map<std::tuple<std::vector<GlobalDeviceId>, int>,
std::shared_ptr<GlooCollectivesCommunicator>>
contexts_ ABSL_GUARDED_BY(mu_);
};
}
#endif
#include "xla/pjrt/cpu/gloo_collectives.h"
#include <complex>
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <exception>
#include <memory>
#include <optional>
#include <string>
#include <tuple>
#include <utility>
#include <vector>
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_join.h"
#include "absl/synchronization/mutex.h"
#include "absl/time/clock.h"
#include "absl/time/time.h"
#include "absl/types/span.h"
#include "third_party/gloo/gloo/algorithm.h"
#include "third_party/gloo/gloo/allgather.h"
#include "third_party/gloo/gloo/allreduce.h"
#include "third_party/gloo/gloo/context.h"
#include "third_party/gloo/gloo/math.h"
#include "third_party/gloo/gloo/reduce_scatter.h"
#include "third_party/gloo/gloo/rendezvous/context.h"
#include "third_party/gloo/gloo/rendezvous/prefix_store.h"
#include "third_party/gloo/gloo/rendezvous/store.h"
#include "third_party/gloo/gloo/transport/device.h"
#include "third_party/gloo/gloo/transport/unbound_buffer.h"
#include "third_party/gloo/gloo/types.h"
#include "xla/primitive_util.h"
#include "xla/service/collective_ops_utils.h"
#include "xla/service/cpu/collectives_interface.h"
#include "xla/service/global_device_id.h"
#include "xla/status_macros.h"
#include "xla/types.h"
#include "xla/xla_data.pb.h"
#include "tsl/platform/errors.h"
#include "tsl/platform/logging.h"
namespace xla::cpu {
GlooCollectivesCommunicator::GlooCollectivesCommunicator(
std::shared_ptr<gloo::Context> context)
: context_(std::move(context)) {}
GlooCollectivesCommunicator::~GlooCollectivesCommunicator() = default;
template <typename T>
static absl::Status SetAllReduceOptions(ReductionKind reduction_kind,
const void* input_buffer,
void* output_buffer,
size_t num_elements,
gloo::AllreduceOptions& options) {
options.setInput(reinterpret_cast<T*>(const_cast<void*>(input_buffer)),
num_elements);
options.setOutput(reinterpret_cast<T*>(const_cast<void*>(output_buffer)),
num_elements);
using ReductionFn = void (*)(void*, const void*, const void*, size_t);
switch (reduction_kind) {
case ReductionKind::SUM:
options.setReduceFunction(static_cast<ReductionFn>(&gloo::sum<T>));
break;
case ReductionKind::PRODUCT:
options.setReduceFunction(static_cast<ReductionFn>(&gloo::product<T>));
break;
case ReductionKind::MIN:
if constexpr (!is_complex_v<T>) {
options.setReduceFunction(static_cast<ReductionFn>(&gloo::min<T>));
} else {
return absl::InvalidArgumentError(
"MIN reduction not supported for complex types");
}
break;
case ReductionKind::MAX:
if constexpr (!is_complex_v<T>) {
options.setReduceFunction(static_cast<ReductionFn>(&gloo::max<T>));
} else {
return absl::InvalidArgumentError(
"MAX reduction not supported for complex types");
}
break;
}
return absl::OkStatus();
}
absl::Status GlooCollectivesCommunicator::AllReduce(
const RendezvousKey& key, ReductionKind reduction_kind,
PrimitiveType element_type, size_t num_elements, const void* input_buffer,
void* output_buffer, absl::Duration timeout) {
gloo::AllreduceOptions options(context_);
switch (element_type) {
case S8:
TF_RETURN_IF_ERROR(SetAllReduceOptions<int8_t>(
reduction_kind, input_buffer, output_buffer, num_elements, options));
break;
case PRED:
case U8:
TF_RETURN_IF_ERROR(SetAllReduceOptions<uint8_t>(
reduction_kind, input_buffer, output_buffer, num_elements, options));
break;
case S16:
TF_RETURN_IF_ERROR(SetAllReduceOptions<int16_t>(
reduction_kind, input_buffer, output_buffer, num_elements, options));
break;
case U16:
TF_RETURN_IF_ERROR(SetAllReduceOptions<uint16_t>(
reduction_kind, input_buffer, output_buffer, num_elements, options));
break;
case S32:
TF_RETURN_IF_ERROR(SetAllReduceOptions<int32_t>(
reduction_kind, input_buffer, output_buffer, num_elements, options));
break;
case U32:
TF_RETURN_IF_ERROR(SetAllReduceOptions<uint32_t>(
reduction_kind, input_buffer, output_buffer, num_elements, options));
break;
case S64:
TF_RETURN_IF_ERROR(SetAllReduceOptions<int64_t>(
reduction_kind, input_buffer, output_buffer, num_elements, options));
break;
case U64:
TF_RETURN_IF_ERROR(SetAllReduceOptions<uint64_t>(
reduction_kind, input_buffer, output_buffer, num_elements, options));
break;
case F16:
TF_RETURN_IF_ERROR(SetAllReduceOptions<gloo::float16>(
reduction_kind, input_buffer, output_buffer, num_elements, options));
break;
case BF16:
TF_RETURN_IF_ERROR(SetAllReduceOptions<bfloat16>(
reduction_kind, input_buffer, output_buffer, num_elements, options));
break;
case F32:
TF_RETURN_IF_ERROR(SetAllReduceOptions<float>(
reduction_kind, input_buffer, output_buffer, num_elements, options));
break;
case F64:
TF_RETURN_IF_ERROR(SetAllReduceOptions<double>(
reduction_kind, input_buffer, output_buffer, num_elements, options));
break;
case C64:
TF_RETURN_IF_ERROR(SetAllReduceOptions<std::complex<float>>(
reduction_kind, input_buffer, output_buffer, num_elements, options));
break;
case C128:
TF_RETURN_IF_ERROR(SetAllReduceOptions<std::complex<double>>(
reduction_kind, input_buffer, output_buffer, num_elements, options));
break;
default:
return absl::InvalidArgumentError("Unknown datatype in allreduce");
}
options.setAlgorithm(gloo::AllreduceOptions::Algorithm::RING);
options.setTimeout(absl::ToChronoMilliseconds(timeout));
try {
gloo::allreduce(options);
} catch (std::exception& e) {
return absl::UnknownError(
absl::StrCat("Gloo all-reduce failed: ", e.what()));
}
return absl::OkStatus();
}
static constexpr uint8_t kCollectivePermuteSlotPrefix = 0x40;
absl::Status GlooCollectivesCommunicator::CollectivePermute(
const RendezvousKey& key, size_t num_bytes, std::optional<int> source_rank,
absl::Span<int const> target_ranks, const void* input_buffer,
void* output_buffer, absl::Duration timeout) {
uint32_t tag = 0;
const auto slot = gloo::Slot::build(kCollectivePermuteSlotPrefix, tag);
try {
std::unique_ptr<gloo::transport::UnboundBuffer> in;
std::unique_ptr<gloo::transport::UnboundBuffer> out;
for (int target : target_ranks) {
if (target != context_->rank) {
VLOG(1) << "send from " << context_->rank << " to " << target;
if (!in) {
in = context_->createUnboundBuffer(const_cast<void*>(input_buffer),
num_bytes);
}
in->send(target, slot);
}
}
if (source_rank) {
if (*source_rank == context_->rank) {
std::memcpy(output_buffer, input_buffer, num_bytes);
} else {
VLOG(1) << "recv at " << context_->rank << " from " << *source_rank;
out = context_->createUnboundBuffer(output_buffer, num_bytes);
out->recv(*source_rank, slot);
}
} else {
std::memset(output_buffer, 0, num_bytes);
}
VLOG(1) << "wait for send at " << context_->rank;
auto deadline = absl::ToChronoTime(absl::Now() + timeout);
if (in) {
in->waitSend(deadline);
}
VLOG(1) << "wait for recv at " << context_->rank;
if (out) {
out->waitRecv(deadline);
}
VLOG(1) << "done waiting at " << context_->rank;
} catch (std::exception& e) {
return absl::UnknownError(
absl::StrCat("Gloo collective permute failed: ", e.what()));
}
return absl::OkStatus();
}
absl::Status GlooCollectivesCommunicator::AllToAll(
const RendezvousKey& key, size_t chunk_bytes,
absl::Span<const void* const> input_buffers,
absl::Span<void* const> output_buffers, absl::Duration timeout) {
uint32_t tag = 0;
int my_rank = context_->rank;
int world_size = context_->size;
TF_RET_CHECK(world_size == input_buffers.size());
TF_RET_CHECK(world_size == output_buffers.size());
try {
const auto slot = gloo::Slot::build(gloo::kAlltoallSlotPrefix, tag);
std::vector<std::unique_ptr<gloo::transport::UnboundBuffer>> ins(
context_->size);
std::vector<std::unique_ptr<gloo::transport::UnboundBuffer>> outs(
context_->size);
for (size_t i = 0; i < world_size; ++i) {
if (i != my_rank) {
ins[i] = context_->createUnboundBuffer(
const_cast<void*>(input_buffers[i]), chunk_bytes);
outs[i] = context_->createUnboundBuffer(output_buffers[i], chunk_bytes);
}
}
for (int i = 1; i < world_size; i++) {
int send_rank = (my_rank + i) % world_size;
int recv_rank = (my_rank + world_size - i) % world_size;
ins[send_rank]->send(send_rank, slot);
outs[recv_rank]->recv(recv_rank, slot);
}
std::memcpy(output_buffers[my_rank], input_buffers[my_rank], chunk_bytes);
auto deadline = absl::ToChronoTime(absl::Now() + timeout);
for (int i = 0; i < world_size; i++) {
if (i != my_rank) {
ins[i]->waitSend(deadline);
outs[i]->waitRecv(deadline);
}
}
} catch (std::exception& e) {
return absl::UnknownError(
absl::StrCat("Gloo all-to-all failed: ", e.what()));
}
return absl::OkStatus();
}
absl::Status GlooCollectivesCommunicator::AllGather(const RendezvousKey& key,
size_t chunk_bytes,
const void* input_buffer,
void* output_buffer,
absl::Duration timeout) {
uint32_t tag = 0;
gloo::AllgatherOptions options(context_);
options.setTag(tag);
options.setTimeout(absl::ToChronoMilliseconds(timeout));
options.setInput(reinterpret_cast<char*>(const_cast<void*>(input_buffer)),
chunk_bytes);
options.setOutput(reinterpret_cast<char*>(output_buffer),
chunk_bytes * context_->size);
try {
gloo::allgather(options);
} catch (std::exception& e) {
return absl::UnknownError(
absl::StrCat("Gloo AllGather failed: ", e.what()));
}
return absl::OkStatus();
}
template <typename T>
absl::Status ReduceScatterHelper(std::shared_ptr<gloo::Context> context,
ReductionKind reduction_kind, void* buffer,
size_t chunk_elems) {
const gloo::ReductionFunction<T>* reduction_function = nullptr;
if constexpr (is_complex_v<T>) {
switch (reduction_kind) {
case ReductionKind::SUM:
reduction_function = gloo::ReductionFunction<T>::sum;
break;
case ReductionKind::PRODUCT:
reduction_function = gloo::ReductionFunction<T>::product;
break;
default:
return absl::InvalidArgumentError(absl::StrCat(
"Unsupported reduction kind: ", static_cast<int>(reduction_kind)));
}
} else {
switch (reduction_kind) {
case ReductionKind::SUM:
reduction_function = gloo::ReductionFunction<T>::sum;
break;
case ReductionKind::PRODUCT:
reduction_function = gloo::ReductionFunction<T>::product;
break;
case ReductionKind::MAX:
reduction_function = gloo::ReductionFunction<T>::max;
break;
case ReductionKind::MIN:
reduction_function = gloo::ReductionFunction<T>::min;
break;
default:
return absl::InvalidArgumentError(absl::StrCat(
"Unsupported reduction kind: ", static_cast<int>(reduction_kind)));
}
}
try {
std::vector<int> recv_elems(context->size, chunk_elems);
gloo::ReduceScatterHalvingDoubling<T> algorithm(
context, std::vector<T*>{reinterpret_cast<T*>(buffer)},
chunk_elems * context->size, recv_elems, reduction_function);
algorithm.run();
} catch (std::exception& e) {
return absl::UnknownError(
absl::StrCat("Gloo ReduceScatter failed: ", e.what()));
}
return absl::OkStatus();
}
absl::Status GlooCollectivesCommunicator::ReduceScatter(
const RendezvousKey& key, ReductionKind reduction_kind,
PrimitiveType element_type, size_t chunk_elems, const void* input_buffer,
void* output_buffer, absl::Duration timeout) {
size_t chunk_bytes = chunk_elems * primitive_util::ByteWidth(element_type);
std::unique_ptr<char[]> temp(new char[chunk_bytes * context_->size]);
std::memcpy(temp.get(), input_buffer, chunk_bytes * context_->size);
switch (element_type) {
case S8:
TF_RETURN_IF_ERROR(ReduceScatterHelper<int8_t>(context_, reduction_kind,
temp.get(), chunk_elems));
break;
case PRED:
case U8:
TF_RETURN_IF_ERROR(ReduceScatterHelper<uint8_t>(context_, reduction_kind,
temp.get(), chunk_elems));
break;
case S16:
TF_RETURN_IF_ERROR(ReduceScatterHelper<int16_t>(context_, reduction_kind,
temp.get(), chunk_elems));
break;
case U16:
TF_RETURN_IF_ERROR(ReduceScatterHelper<uint16_t>(
context_, reduction_kind, temp.get(), chunk_elems));
break;
case S32:
TF_RETURN_IF_ERROR(ReduceScatterHelper<int32_t>(context_, reduction_kind,
temp.get(), chunk_elems));
break;
case U32:
TF_RETURN_IF_ERROR(ReduceScatterHelper<uint32_t>(
context_, reduction_kind, temp.get(), chunk_elems));
break;
case S64:
TF_RETURN_IF_ERROR(ReduceScatterHelper<int64_t>(context_, reduction_kind,
temp.get(), chunk_elems));
break;
case U64:
TF_RETURN_IF_ERROR(ReduceScatterHelper<uint64_t>(
context_, reduction_kind, temp.get(), chunk_elems));
break;
case BF16:
TF_RETURN_IF_ERROR(ReduceScatterHelper<bfloat16>(
context_, reduction_kind, temp.get(), chunk_elems));
break;
case F16:
TF_RETURN_IF_ERROR(ReduceScatterHelper<gloo::float16>(
context_, reduction_kind, temp.get(), chunk_elems));
break;
case F32:
TF_RETURN_IF_ERROR(ReduceScatterHelper<float>(context_, reduction_kind,
temp.get(), chunk_elems));
break;
case F64:
TF_RETURN_IF_ERROR(ReduceScatterHelper<double>(context_, reduction_kind,
temp.get(), chunk_elems));
break;
case C64:
TF_RETURN_IF_ERROR(ReduceScatterHelper<std::complex<float>>(
context_, reduction_kind, temp.get(), chunk_elems));
break;
case C128:
TF_RETURN_IF_ERROR(ReduceScatterHelper<std::complex<double>>(
context_, reduction_kind, temp.get(), chunk_elems));
break;
default:
return absl::InvalidArgumentError("Unknown datatype in reducescatter");
}
std::memcpy(output_buffer, temp.get(), chunk_bytes);
return absl::OkStatus();
}
GlooCollectives::GlooCollectives(
std::unique_ptr<gloo::rendezvous::Store> store,
std::shared_ptr<gloo::transport::Device> device)
: store_(std::move(store)), device_(std::move(device)) {}
GlooCollectives::~GlooCollectives() = default;
absl::StatusOr<std::shared_ptr<CollectivesCommunicator>>
GlooCollectives::GetCommunicator(
absl::Span<GlobalDeviceId const> global_devices, int rank) {
absl::MutexLock lock(&mu_);
auto& context = contexts_[std::make_tuple(
std::vector<GlobalDeviceId>(global_devices.begin(), global_devices.end()),
rank)];
if (context) {
return context;
}
auto gloo_context =
std::make_shared<gloo::rendezvous::Context>(rank, global_devices.size());
auto prefix_store = gloo::rendezvous::PrefixStore(
absl::StrCat("gloo/",
absl::StrJoin(global_devices, ",",
[](std::string* out, GlobalDeviceId id) {
absl::StrAppend(out, id.value());
})),
*store_);
try {
gloo_context->connectFullMesh(prefix_store, device_);
} catch (std::exception& e) {
return absl::UnknownError(
absl::StrCat("Gloo context initialization failed: ", e.what()));
}
context =
std::make_shared<GlooCollectivesCommunicator>(std::move(gloo_context));
return context;
}
} | #include "xla/pjrt/cpu/gloo_collectives.h"
#include <unistd.h>
#include <cstddef>
#include <cstdint>
#include <memory>
#include <vector>
#include "absl/status/statusor.h"
#include "absl/time/time.h"
#include "absl/types/span.h"
#include "third_party/gloo/gloo/transport/tcp/attr.h"
#include "third_party/gloo/gloo/transport/tcp/device.h"
#include "xla/executable_run_options.h"
#include "xla/pjrt/cpu/gloo_kv_store.h"
#include "xla/pjrt/distributed/in_memory_key_value_store.h"
#include "xla/pjrt/distributed/key_value_store_interface.h"
#include "xla/service/collective_ops_utils.h"
#include "xla/service/cpu/collectives_interface.h"
#include "xla/service/global_device_id.h"
#include "xla/xla_data.pb.h"
#include "tsl/lib/core/status_test_util.h"
#include "tsl/platform/env.h"
#include "tsl/platform/errors.h"
#include "tsl/platform/statusor.h"
#include "tsl/platform/test.h"
#include "tsl/platform/threadpool.h"
namespace xla::cpu {
namespace {
using ::testing::Each;
using ::testing::Eq;
constexpr int kNumParticipants = 2;
constexpr size_t kBufferSize = 256;
constexpr absl::Duration kTimeout = absl::Seconds(5);
absl::StatusOr<std::shared_ptr<CollectivesCommunicator>> GetCommunicator(
size_t kNumParticipants, absl::Span<GlobalDeviceId const> global_devices,
const std::shared_ptr<xla::KeyValueStoreInterface>& kv_store, int rank) {
auto collectives = std::make_shared<cpu::GlooCollectives>(
std::make_unique<cpu::GlooKeyValueStore>(kv_store),
gloo::transport::tcp::CreateDevice(gloo::transport::tcp::attr()));
return collectives->GetCommunicator(global_devices, rank);
}
RendezvousKey MakeRendezvousKey(std::vector<GlobalDeviceId> global_devices) {
return RendezvousKey(RunId(0), global_devices, kNumParticipants,
RendezvousKey::CollectiveOpKind::kCrossModule,
0);
}
absl::StatusOr<std::vector<uint8_t>> AllReduce(
const std::shared_ptr<xla::KeyValueStoreInterface>& kv_store,
const std::vector<uint8_t>& input_buffer,
std::vector<GlobalDeviceId> global_devices, int rank) {
std::vector<uint8_t> output_buffer(kBufferSize);
RendezvousKey rendezvous_key = MakeRendezvousKey(global_devices);
TF_ASSIGN_OR_RETURN(
auto communicator,
GetCommunicator(kNumParticipants, global_devices, kv_store, rank));
TF_RETURN_IF_ERROR(communicator->AllReduce(
rendezvous_key, xla::ReductionKind::SUM, xla::PrimitiveType::U8,
kBufferSize, input_buffer.data(), output_buffer.data(), kTimeout));
return output_buffer;
}
TEST(GlooCollectives, AllReduce) {
std::vector<GlobalDeviceId> global_devices;
global_devices.reserve(kNumParticipants);
for (int rank = 0; rank < kNumParticipants; ++rank) {
global_devices.push_back(GlobalDeviceId(rank));
}
auto kv_store = std::make_shared<xla::InMemoryKeyValueStore>();
std::vector<absl::StatusOr<std::vector<uint8_t>>> output_buffers(
kNumParticipants);
{
tsl::thread::ThreadPool thread_pool(
tsl::Env::Default(), "AllReduceParticipants", kNumParticipants);
for (int rank = 0; rank < kNumParticipants; ++rank) {
thread_pool.Schedule(
[rank, &output_buffers, &kv_store, &global_devices]() {
std::vector<uint8_t> input_buffer(kBufferSize, rank + 1);
output_buffers[rank] =
AllReduce(kv_store, input_buffer, global_devices, rank);
});
}
}
for (int rank = 0; rank < kNumParticipants; ++rank) {
TF_ASSERT_OK(output_buffers[rank].status());
}
for (int rank = 0; rank < kNumParticipants; ++rank) {
EXPECT_THAT(output_buffers[rank].value(),
Each(Eq(kNumParticipants * (kNumParticipants + 1) / 2)));
}
}
}
} | 2,216 |
#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);
}
}
} | 2,217 |
#ifndef XLA_PJRT_GPU_SE_GPU_PJRT_COMPILER_H_
#define XLA_PJRT_GPU_SE_GPU_PJRT_COMPILER_H_
#include <memory>
#include <optional>
#include "absl/status/status.h"
#include "xla/pjrt/pjrt_compiler.h"
#include "xla/pjrt/pjrt_executable.h"
#include "xla/service/compiler.h"
namespace xla {
class StreamExecutorGpuCompiler : public PjRtCompiler {
public:
explicit StreamExecutorGpuCompiler() = default;
absl::StatusOr<std::unique_ptr<PjRtExecutable>> Compile(
CompileOptions options, const XlaComputation& computation,
const PjRtTopologyDescription& topology, PjRtClient* client) override;
absl::StatusOr<std::unique_ptr<PjRtExecutable>> Compile(
CompileOptions options, mlir::ModuleOp module,
const PjRtTopologyDescription& topology, PjRtClient* client) override;
};
}
#endif
#include "xla/pjrt/gpu/se_gpu_pjrt_compiler.h"
#include <memory>
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "xla/client/xla_computation.h"
#include "xla/pjrt/gpu/se_gpu_pjrt_client.h"
#include "xla/pjrt/pjrt_client.h"
#include "xla/pjrt/pjrt_compiler.h"
#include "xla/pjrt/pjrt_executable.h"
#include "xla/stream_executor/platform/initialize.h"
#include "tsl/platform/casts.h"
#include "tsl/platform/statusor.h"
#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM
#include "xla/client/local_client.h"
#include "xla/pjrt/mlir_to_hlo.h"
#include "xla/pjrt/stream_executor_executable.h"
#include "xla/pjrt/utils.h"
#include "xla/service/dump.h"
#include "xla/service/gpu/executable.pb.h"
#include "xla/service/gpu/gpu_compiler.h"
#include "xla/service/hlo_module_util.h"
#include "xla/service/hlo_proto_util.h"
#include "xla/service/local_service.h"
#include "xla/service/local_service_utils.h"
#endif
#if GOOGLE_CUDA
#include "xla/service/gpu/nvptx_compiler.h"
#include "xla/stream_executor/cuda/cuda_platform_id.h"
#elif TENSORFLOW_USE_ROCM
#include "xla/service/gpu/amdgpu_compiler.h"
#include "xla/stream_executor/rocm/rocm_platform_id.h"
#endif
namespace xla {
namespace {
bool IsGpuClient(const PjRtClient& client) {
return client.platform_id() == CudaId() || client.platform_id() == RocmId() ||
client.platform_id() == SyclId();
}
bool IsSameTopology(const PjRtTopologyDescription& topology1,
const PjRtTopologyDescription& topology2) {
const StreamExecutorGpuTopologyDescription& gpu_topology1 =
tensorflow::down_cast<const StreamExecutorGpuTopologyDescription&>(
topology1);
const StreamExecutorGpuTopologyDescription& gpu_topology2 =
tensorflow::down_cast<const StreamExecutorGpuTopologyDescription&>(
topology2);
return gpu_topology1 == gpu_topology2;
}
absl::Status IsValidTopologyAndClientForCompile(
const PjRtTopologyDescription& topology, PjRtClient* client) {
if (client == nullptr) {
return absl::UnimplementedError(
"SE:GPU compiler requires non-null client.");
}
if (!IsGpuClient(*client)) {
return absl::InvalidArgumentError(
"SE:GPU compiler requires a GPU PjRtClient.");
}
TF_ASSIGN_OR_RETURN(auto client_topology, client->GetTopologyDescription());
if (!IsSameTopology(topology, *client_topology)) {
return absl::UnimplementedError(
"SE:GPU compiler requires the topology same as the one in the client.");
}
return absl::OkStatus();
}
}
absl::StatusOr<std::unique_ptr<PjRtExecutable>>
StreamExecutorGpuCompiler::Compile(CompileOptions options,
const XlaComputation& computation,
const PjRtTopologyDescription& topology,
PjRtClient* client) {
#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM
#if GOOGLE_CUDA
auto gpu_compiler = gpu::NVPTXCompiler();
#else
auto gpu_compiler = gpu::AMDGPUCompiler();
#endif
CompileOptions input_options = options;
if (!options.target_config) {
if (client != nullptr) {
TF_RETURN_IF_ERROR(IsValidTopologyAndClientForCompile(topology, client));
return client->Compile(computation, options);
}
auto attr = topology.Attributes();
if (auto it = attr.find("target_config"); it != attr.end()) {
auto target_config_str = std::get<std::string>(it->second);
stream_executor::GpuTargetConfigProto gpu_target_config_proto;
if (!gpu_target_config_proto.ParseFromString(target_config_str)) {
return FailedPrecondition("Failed to parse GpuTargetConfigProto");
}
options.target_config.emplace(
Compiler::TargetConfig(gpu_target_config_proto));
} else {
return absl::UnimplementedError(
"Compilation without client and without target_config specified is "
"not implemented");
}
}
TF_RETURN_IF_ERROR(options.ApplyAllOptionOverrides());
std::vector<const Shape*> argument_layout_pointers;
TF_RETURN_IF_ERROR(DetermineArgumentLayoutsFromCompileOptions(
computation,
[](Shape shape) { return LayoutUtil::GetWithDefaultLayout(shape); },
options.argument_layouts, &options.executable_build_options,
&argument_layout_pointers));
TF_ASSIGN_OR_RETURN(std::unique_ptr<HloModuleConfig> hlo_config,
GetHloModuleConfig(computation, argument_layout_pointers,
options.executable_build_options));
HloModuleProto hlo_module_proto = computation.proto();
TF_ASSIGN_OR_RETURN(
std::unique_ptr<HloModule> hlo_module,
HloModule::CreateFromProto(hlo_module_proto, *hlo_config));
UpdateEntryComputationLayout(
hlo_module.get(), std::bind(&Compiler::DefaultDeviceShapeRepresentation,
&gpu_compiler, std::placeholders::_1));
DumpHloModuleIfEnabled(*hlo_module, kBeforeOptimizationsDumpName);
Compiler::CompileOptions opts;
opts.target_config = options.target_config;
AotCompilationOptions aot_options(gpu_compiler.PlatformId());
aot_options.set_target_config(*options.target_config);
aot_options.set_run_backend_only(
options.executable_build_options.run_backend_only());
const int num_replicas = hlo_module->config().replica_count();
const int num_partitions = hlo_module->config().num_partitions();
const std::string name = hlo_module->name();
const std::string fingerprint = hlo_module->GetFingerprint128();
const int num_outputs = hlo_module->result_shape().IsTuple()
? hlo_module->result_shape().tuple_shapes_size()
: 1;
auto unique_module_group =
std::make_unique<HloModuleGroup>(std::move(hlo_module));
TF_ASSIGN_OR_RETURN(
std::vector<std::unique_ptr<AotCompilationResult>> aot_results,
gpu_compiler.CompileAheadOfTime(std::move(unique_module_group),
aot_options));
std::vector<std::vector<absl::string_view>> output_memory_kinds(1);
output_memory_kinds[0].resize(num_outputs,
StreamExecutorGpuHbmMemorySpace::kKind);
return std::make_unique<StreamExecutorExecutable>(
std::move(input_options), std::move(aot_results), num_replicas,
num_partitions, name, fingerprint, std::move(output_memory_kinds));
#else
return absl::InternalError(
"GPU Compilation requires the target to be built with CUDA or "
"ROCm.");
#endif
}
absl::StatusOr<std::unique_ptr<PjRtExecutable>>
StreamExecutorGpuCompiler::Compile(CompileOptions options,
mlir::ModuleOp module,
const PjRtTopologyDescription& topology,
PjRtClient* client) {
#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM
CompileOptions input_options = options;
XlaComputation xla_computation;
TF_RETURN_IF_ERROR(MlirToXlaComputation(
module, xla_computation,
options.parameter_is_tupled_arguments,
false));
return Compile(std::move(input_options), xla_computation, topology, client);
#else
return absl::InternalError(
"GPU AOT compilation requires the target to be built with CUDA or "
"ROCm.");
#endif
}
STREAM_EXECUTOR_REGISTER_MODULE_INITIALIZER(pjrt_register_se_gpu_compiler, {
PjRtRegisterCompiler(
#if TENSORFLOW_USE_ROCM
RocmName(),
#else
CudaName(),
#endif
std::make_unique<StreamExecutorGpuCompiler>());
});
} | #include "xla/pjrt/gpu/se_gpu_pjrt_compiler.h"
#include <memory>
#include <vector>
#include <gmock/gmock.h>
#include "absl/status/status.h"
#include "mlir/Dialect/Func/IR/FuncOps.h"
#include "mlir/Parser/Parser.h"
#include "xla/client/xla_computation.h"
#include "xla/mlir_hlo/mhlo/IR/hlo_ops.h"
#include "xla/pjrt/gpu/gpu_topology.h"
#include "xla/pjrt/gpu/se_gpu_pjrt_client.h"
#include "xla/pjrt/pjrt_client.h"
#include "xla/pjrt/pjrt_compiler.h"
#include "xla/service/hlo_parser.h"
#include "xla/test.h"
#include "xla/tests/literal_test_util.h"
#include "tsl/platform/status_matchers.h"
#include "tsl/platform/statusor.h"
namespace xla {
namespace {
using ::tsl::testing::StatusIs;
constexpr absl::string_view kProgram = R"(HloModule Computation
ENTRY Computation() -> s32[] {
ROOT result = s32[] constant(2)
})";
constexpr absl::string_view mlir_str = R"mlir(
module {
func.func @main() -> tensor<i32> {
%0 = mhlo.constant dense<2> : tensor<i32>
return %0 : tensor<i32>
}
})mlir";
absl::StatusOr<xla::XlaComputation> GetXlaComputation(
absl::string_view program) {
TF_ASSIGN_OR_RETURN(auto hlo_module,
xla::ParseAndReturnUnverifiedModule(program, {}));
return XlaComputation(hlo_module->ToProto());
}
std::shared_ptr<xla::GpuTopology> GetGpuTopology(
std::vector<int> device_ids, absl::string_view platform_version,
int num_slices, int num_hosts_per_slice, int num_devices_per_host) {
return std::make_shared<xla::GpuTopology>(device_ids, platform_version,
num_slices, num_hosts_per_slice,
num_devices_per_host);
}
TEST(StreamExecutorGpuCompilerTest, NoClientXla) {
StreamExecutorGpuCompiler compiler;
StreamExecutorGpuTopologyDescription topology(
CudaId(), CudaName(), GetGpuTopology({0, 1}, "Fake_device", 1, 1, 2));
TF_ASSERT_OK_AND_ASSIGN(auto computation, GetXlaComputation(kProgram));
EXPECT_THAT(compiler.Compile(xla::CompileOptions(), computation, topology,
nullptr),
StatusIs(absl::StatusCode::kUnimplemented));
}
TEST(StreamExecutorGpuCompilerTest, TopologyNotSameXla) {
StreamExecutorGpuCompiler compiler;
StreamExecutorGpuTopologyDescription topology(
CudaId(), CudaName(), GetGpuTopology({0, 1}, "Fake_device", 1, 1, 2));
TF_ASSERT_OK_AND_ASSIGN(auto client,
GetStreamExecutorGpuClient(GpuClientOptions()));
TF_ASSERT_OK_AND_ASSIGN(auto computation, GetXlaComputation(kProgram));
EXPECT_THAT(compiler.Compile(xla::CompileOptions(), computation, topology,
client.get()),
StatusIs(absl::StatusCode::kUnimplemented));
}
TEST(StreamExecutorGpuCompilerTest, SuccessXla) {
StreamExecutorGpuCompiler compiler;
TF_ASSERT_OK_AND_ASSIGN(auto client,
GetStreamExecutorGpuClient(GpuClientOptions()));
TF_ASSERT_OK_AND_ASSIGN(auto computation, GetXlaComputation(kProgram));
TF_ASSERT_OK_AND_ASSIGN(auto topology, client->GetTopologyDescription());
TF_ASSERT_OK_AND_ASSIGN(auto executable,
compiler.Compile(xla::CompileOptions(), computation,
*topology, client.get()));
const LoadOptions load_options;
TF_ASSERT_OK_AND_ASSIGN(auto loaded_executable,
client->Load(std::move(executable), load_options));
TF_ASSERT_OK_AND_ASSIGN(
auto result, loaded_executable->Execute({{}}, {}));
ASSERT_EQ(result.size(), 1);
std::vector<std::unique_ptr<xla::PjRtBuffer>>& result_buffers = result[0];
ASSERT_EQ(result_buffers.size(), 1);
TF_ASSERT_OK_AND_ASSIGN(std::shared_ptr<xla::Literal> result_literal,
result_buffers[0]->ToLiteralSync());
EXPECT_TRUE(
LiteralTestUtil::Equal(LiteralUtil::CreateR0(2), *result_literal));
}
TEST(StreamExecutorGpuCompilerTest, NoClientMlir) {
StreamExecutorGpuCompiler compiler;
mlir::MLIRContext context;
context.loadDialect<mlir::mhlo::MhloDialect, mlir::func::FuncDialect>();
auto mlir_module =
mlir::parseSourceString<mlir::ModuleOp>(mlir_str, &context);
StreamExecutorGpuTopologyDescription topology(
CudaId(), CudaName(), GetGpuTopology({0, 1}, "Fake_device", 1, 1, 2));
EXPECT_THAT(
compiler.Compile(xla::CompileOptions(), mlir_module.get(), topology,
nullptr),
StatusIs(absl::StatusCode::kUnimplemented));
}
TEST(StreamExecutorGpuCompilerTest, TopologyNotSameMlir) {
StreamExecutorGpuCompiler compiler;
mlir::MLIRContext context;
context.loadDialect<mlir::mhlo::MhloDialect, mlir::func::FuncDialect>();
auto mlir_module =
mlir::parseSourceString<mlir::ModuleOp>(mlir_str, &context);
StreamExecutorGpuTopologyDescription topology(
CudaId(), CudaName(), GetGpuTopology({0, 1}, "Fake_device", 1, 1, 2));
TF_ASSERT_OK_AND_ASSIGN(auto client,
GetStreamExecutorGpuClient(GpuClientOptions()));
EXPECT_THAT(compiler.Compile(xla::CompileOptions(), mlir_module.get(),
topology, client.get()),
StatusIs(absl::StatusCode::kUnimplemented));
}
TEST(StreamExecutorGpuCompilerTest, SuccessMlir) {
StreamExecutorGpuCompiler compiler;
mlir::MLIRContext context;
context.loadDialect<mlir::mhlo::MhloDialect, mlir::func::FuncDialect>();
auto mlir_module =
mlir::parseSourceString<mlir::ModuleOp>(mlir_str, &context);
TF_ASSERT_OK_AND_ASSIGN(auto client,
GetStreamExecutorGpuClient(GpuClientOptions()));
TF_ASSERT_OK_AND_ASSIGN(auto topology, client->GetTopologyDescription());
TF_ASSERT_OK_AND_ASSIGN(
auto executable,
compiler.Compile(xla::CompileOptions(), mlir_module.get(), *topology,
client.get()));
const LoadOptions load_options;
TF_ASSERT_OK_AND_ASSIGN(auto loaded_executable,
client->Load(std::move(executable), load_options));
TF_ASSERT_OK_AND_ASSIGN(
auto result, loaded_executable->Execute({{}}, {}));
ASSERT_EQ(result.size(), 1);
std::vector<std::unique_ptr<xla::PjRtBuffer>>& result_buffers = result[0];
ASSERT_EQ(result_buffers.size(), 1);
TF_ASSERT_OK_AND_ASSIGN(std::shared_ptr<xla::Literal> result_literal,
result_buffers[0]->ToLiteralSync());
EXPECT_TRUE(
LiteralTestUtil::Equal(LiteralUtil::CreateR0(2), *result_literal));
}
}
} | 2,218 |
#ifndef XLA_PJRT_GPU_SE_GPU_PJRT_CLIENT_H_
#define XLA_PJRT_GPU_SE_GPU_PJRT_CLIENT_H_
#include <cstdint>
#include <map>
#include <memory>
#include <optional>
#include <set>
#include <string>
#include <utility>
#include <vector>
#include "absl/container/flat_hash_map.h"
#include "absl/memory/memory.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/string_view.h"
#include "absl/time/time.h"
#include "absl/types/span.h"
#include "xla/client/local_client.h"
#include "xla/client/xla_computation.h"
#include "xla/layout.h"
#include "xla/pjrt/distributed/key_value_store_interface.h"
#include "xla/pjrt/gpu/gpu_helpers.h"
#include "xla/pjrt/gpu/gpu_topology.h"
#include "xla/pjrt/gpu/gpu_topology.pb.h"
#include "xla/pjrt/local_device_state.h"
#include "xla/pjrt/pjrt_client.h"
#include "xla/pjrt/pjrt_compiler.h"
#include "xla/pjrt/pjrt_device_description.h"
#include "xla/pjrt/pjrt_executable.h"
#include "xla/pjrt/pjrt_future.h"
#include "xla/pjrt/pjrt_stream_executor_client.h"
#include "xla/service/computation_placer.h"
#include "xla/service/gpu/gpu_executable_run_options.h"
#include "xla/shape.h"
#include "xla/stream_executor/device_memory_allocator.h"
#include "xla/tsl/framework/allocator.h"
#include "tsl/platform/casts.h"
#include "tsl/platform/fingerprint.h"
namespace stream_executor {
class MultiDeviceAdapter;
}
namespace xla {
using DeviceTopologyPair =
std::pair<std::vector<std::unique_ptr<PjRtStreamExecutorDevice>>,
GpuTopologyProto>;
class StreamExecutorGpuTopologyDescription : public PjRtTopologyDescription {
public:
static StreamExecutorGpuTopologyDescription Create(
const PjRtPlatformId platform_id, const absl::string_view platform_name,
std::shared_ptr<const GpuTopology> gpu_topology) {
return StreamExecutorGpuTopologyDescription(platform_id, platform_name,
gpu_topology);
}
StreamExecutorGpuTopologyDescription(
const PjRtPlatformId platform_id, const absl::string_view platform_name,
std::shared_ptr<const GpuTopology> gpu_topology,
const absl::flat_hash_map<std::string, PjRtDeviceAttribute>& attributes =
{})
: platform_id_(platform_id),
platform_name_(platform_name),
gpu_topology_(std::move(gpu_topology)),
attributes_(attributes) {}
bool operator==(const StreamExecutorGpuTopologyDescription& other) const {
return this->platform_id() == other.platform_id() &&
this->platform_name() == other.platform_name() &&
this->platform_version() == other.platform_version() &&
this->gpu_topology() == other.gpu_topology();
}
PjRtPlatformId platform_id() const override { return platform_id_; }
absl::string_view platform_name() const override { return platform_name_; }
absl::string_view platform_version() const override {
return gpu_topology_->platform_version();
}
std::vector<std::unique_ptr<const PjRtDeviceDescription>> DeviceDescriptions()
const override {
std::vector<std::unique_ptr<const PjRtDeviceDescription>> devices;
devices.reserve(gpu_topology_->number_of_devices());
for (const int device_id : gpu_topology_->device_ids()) {
devices.push_back(std::make_unique<PjRtStreamExecutorDeviceDescription>(
device_id, std::string(platform_version())));
}
return devices;
}
const GpuTopology& gpu_topology() const { return *gpu_topology_; }
const GpuTopology* gpu_topology_ptr() const { return gpu_topology_.get(); }
bool is_subslice_topology() const override { return false; }
absl::StatusOr<int> ProcessCount() const override {
return gpu_topology_->number_of_hosts();
}
absl::StatusOr<int> CoreCountOfDefaultType() const override {
return gpu_topology_->number_of_devices();
}
absl::StatusOr<int> LogicalDeviceCountOfDefaultType() const override {
return gpu_topology_->number_of_devices();
}
absl::StatusOr<int> CoreCountOfDefaultTypePerProcess() const override {
return gpu_topology_->number_of_devices();
}
absl::StatusOr<int> CoreCountOfDefaultTypePerChip() const override {
return 1;
}
absl::StatusOr<std::string> Serialize() const override;
const absl::flat_hash_map<std::string, PjRtDeviceAttribute>& Attributes()
const override {
return attributes_;
}
absl::StatusOr<Layout> GetDefaultLayout(
PrimitiveType element_type,
absl::Span<const int64_t> dims) const override;
private:
const PjRtPlatformId platform_id_;
const std::string platform_name_;
std::shared_ptr<const GpuTopology> gpu_topology_;
absl::flat_hash_map<std::string, xla::PjRtDeviceAttribute> attributes_;
};
class StreamExecutorGpuDevice : public PjRtStreamExecutorDevice {
public:
StreamExecutorGpuDevice(int id,
std::unique_ptr<LocalDeviceState> local_device_state,
std::string device_kind, std::string device_vendor,
std::string compute_capability, int core_count,
int node_id, int slice_index = 0);
int slice_index() const;
absl::string_view device_vendor() const;
absl::StatusOr<tsl::AllocatorStats> GetAllocatorStats() const override;
absl::Span<int const> coords() const;
int core_on_chip() const;
absl::StatusOr<PjRtMemorySpace*> default_memory_space() const override;
private:
std::string device_vendor_;
int slice_index_;
};
class StreamExecutorGpuHbmMemorySpace : public PjRtStreamExecutorMemorySpace {
public:
static constexpr absl::string_view kKind = "device";
static const int kKindId;
StreamExecutorGpuHbmMemorySpace(int id, PjRtDevice* device);
};
class StreamExecutorGpuClient : public xla::PjRtStreamExecutorClient {
public:
using xla::PjRtStreamExecutorClient::PjRtStreamExecutorClient;
StreamExecutorGpuClient(
std::string platform_name, LocalClient* client,
std::vector<std::unique_ptr<PjRtStreamExecutorDevice>> devices,
int process_index, std::unique_ptr<se::DeviceMemoryAllocator> allocator,
std::unique_ptr<tsl::Allocator> host_memory_allocator,
bool should_stage_host_to_device_transfers,
std::unique_ptr<gpu::GpuExecutableRunOptions> gpu_run_options,
std::shared_ptr<KeyValueStoreInterface> kv_store,
std::shared_ptr<const GpuTopology> gpu_topology);
absl::StatusOr<xla::DeviceAssignment> GetDefaultDeviceAssignment(
int num_replicas, int num_partitions) const override;
absl::string_view platform_version() const override;
absl::StatusOr<std::unique_ptr<PjRtClient::AsyncHostToDeviceTransferManager>>
CreateBuffersForAsyncHostToDevice(absl::Span<const Shape> shapes,
PjRtDevice* device) override;
absl::StatusOr<std::unique_ptr<PjRtClient::AsyncHostToDeviceTransferManager>>
CreateBuffersForAsyncHostToDevice(absl::Span<const Shape> shapes,
PjRtMemorySpace* memory_space) override;
PjRtFuture<> CopyRawSubBufferToHost(PjRtBuffer* buffer, PjRtFuture<void*> dst,
int64_t offset,
int64_t transfer_size) override;
absl::StatusOr<const xla::PjRtTopologyDescription*> GetTopologyDescription()
const override {
return &topology_;
}
absl::StatusOr<std::unique_ptr<PjRtLoadedExecutable>> Load(
std::unique_ptr<PjRtExecutable> executable,
const LoadOptions& load_options) override {
return absl::WrapUnique<PjRtLoadedExecutable>(
tensorflow::down_cast<PjRtLoadedExecutable*>(executable.release()));
}
absl::StatusOr<std::unique_ptr<PjRtLoadedExecutable>> Load(
std::unique_ptr<PjRtExecutable> executable);
absl::StatusOr<std::unique_ptr<PjRtLoadedExecutable>> LoadSerialized(
absl::string_view serialized, std::optional<CompileOptions> options,
const LoadOptions& load_options);
absl::StatusOr<std::unique_ptr<PjRtLoadedExecutable>> Compile(
const XlaComputation& computation, CompileOptions options) override;
private:
xla::StreamExecutorGpuTopologyDescription topology_;
std::shared_ptr<KeyValueStoreInterface> kv_store_;
};
std::vector<std::unique_ptr<PjRtStreamExecutorDevice>> BuildLocalDevices(
std::map<int, std::unique_ptr<LocalDeviceState>> local_device_states,
int node_id);
std::string MakeComputeCapabilityString(const se::DeviceDescription* desc);
absl::StatusOr<DeviceTopologyPair> BuildDistributedDevices(
std::string_view platform_name,
std::map<int, std::unique_ptr<LocalDeviceState>> local_device_states,
int node_id, int num_nodes,
gpu::GpuExecutableRunOptions* gpu_executable_run_options,
std::shared_ptr<KeyValueStoreInterface> kv_store, bool enable_mock_nccl,
absl::Duration get_local_topology_timeout = absl::Minutes(2),
absl::Duration get_global_topology_timeout = absl::Minutes(5));
struct GpuClientOptions {
GpuAllocatorConfig allocator_config;
int node_id = 0;
int num_nodes = 1;
std::optional<std::set<int>> allowed_devices = std::nullopt;
std::optional<std::string> platform_name = std::nullopt;
bool should_stage_host_to_device_transfers = true;
std::shared_ptr<KeyValueStoreInterface> kv_store = nullptr;
bool enable_mock_nccl = false;
};
absl::StatusOr<std::unique_ptr<PjRtClient>> GetStreamExecutorGpuClient(
const GpuClientOptions& options);
}
#endif
#include "xla/pjrt/gpu/se_gpu_pjrt_client.h"
#include <array>
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <map>
#include <memory>
#include <optional>
#include <string>
#include <string_view>
#include <utility>
#include <variant>
#include <vector>
#include "absl/algorithm/container.h"
#include "absl/base/thread_annotations.h"
#include "absl/container/flat_hash_map.h"
#include "absl/container/inlined_vector.h"
#include "absl/functional/any_invocable.h"
#include "absl/functional/bind_front.h"
#include "absl/log/check.h"
#include "absl/log/log.h"
#include "absl/memory/memory.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_format.h"
#include "absl/strings/string_view.h"
#include "absl/synchronization/mutex.h"
#include "absl/time/time.h"
#include "absl/types/span.h"
#include "xla/client/local_client.h"
#include "xla/client/xla_computation.h"
#include "xla/layout.h"
#include "xla/layout_util.h"
#include "xla/literal.h"
#include "xla/pjrt/distributed/in_memory_key_value_store.h"
#include "xla/pjrt/distributed/key_value_store_interface.h"
#include "xla/pjrt/distributed/topology_util.h"
#include "xla/pjrt/event_pool.h"
#include "xla/pjrt/gpu/gpu_helpers.h"
#include "xla/pjrt/gpu/gpu_topology.h"
#include "xla/pjrt/gpu/gpu_topology.pb.h"
#include "xla/pjrt/host_memory_spaces.h"
#include "xla/pjrt/local_device_state.h"
#include "xla/pjrt/pjrt_client.h"
#include "xla/pjrt/pjrt_compiler.h"
#include "xla/pjrt/pjrt_device_description.h"
#include "xla/pjrt/pjrt_executable.h"
#include "xla/pjrt/pjrt_future.h"
#include "xla/pjrt/pjrt_stream_executor_client.h"
#include "xla/pjrt/stream_executor_executable.h"
#include "xla/pjrt/tracked_device_buffer.h"
#include "xla/service/compiler.h"
#include "xla/service/computation_placer.h"
#include "xla/service/global_device_id.h"
#include "xla/service/shaped_buffer.h"
#include "xla/service/transfer_manager.h"
#include "xla/shape.h"
#include "xla/shape_util.h"
#include "xla/status_macros.h"
#include "xla/stream_executor/device_description.h"
#include "xla/stream_executor/device_memory.h"
#include "xla/stream_executor/device_memory_allocator.h"
#include "xla/stream_executor/platform.h"
#include "xla/stream_executor/stream.h"
#include "xla/stream_executor/stream_executor.h"
#include "xla/tsl/framework/allocator.h"
#include "tsl/lib/strings/proto_serialization.h"
#include "tsl/platform/casts.h"
#include "tsl/platform/errors.h"
#include "tsl/platform/fingerprint.h"
#include "tsl/platform/status.h"
#include "tsl/platform/statusor.h"
#include "tsl/platform/threadpool.h"
#include "tsl/profiler/lib/connected_traceme.h"
#include "tsl/profiler/lib/traceme.h"
#if defined(GOOGLE_CUDA) || defined(TENSORFLOW_USE_ROCM)
#include "xla/debug_options_flags.h"
#include "xla/pjrt/compile_options.pb.h"
#include "xla/pjrt/gpu/gpu_metrics.h"
#include "xla/pjrt/gpu/nccl_id_store.h"
#include "xla/pjrt/stream_executor_executable.pb.h"
#include "xla/service/gpu/gpu_compiler.h"
#include "xla/service/gpu/gpu_memory_space_assignment.h"
#include "xla/xla.pb.h"
#endif
#if GOOGLE_CUDA
#include "third_party/gpus/cuda/include/cuda.h"
#include "third_party/gpus/cuda/include/cuda_runtime_api.h"
#include "xla/stream_executor/gpu/gpu_cudamallocasync_allocator.h"
#elif TENSORFLOW_USE_ROCM
#include "rocm/rocm_config.h"
#endif
#include "xla/service/gpu/gpu_executable_run_options.h"
#include "xla/stream_executor/integrations/device_mem_allocator.h"
#include "xla/stream_executor/integrations/tf_allocator_adapter.h"
#include "xla/util.h"
namespace xla {
class AsyncHostToDeviceTransferManager
: public xla::PjRtClient::AsyncHostToDeviceTransferManager {
public:
static absl::StatusOr<std::unique_ptr<AsyncHostToDeviceTransferManager>>
Create(absl::Span<const Shape> shapes, PjRtStreamExecutorDevice* device,
PjRtStreamExecutorClient* client) {
absl::InlinedVector<std::unique_ptr<PjRtBuffer>, 4> buffers;
absl::InlinedVector<std::shared_ptr<TrackedDeviceBuffer>, 4> buffer_ptrs;
absl::InlinedVector<std::shared_ptr<BufferSequencingEvent>, 4>
definition_events;
buffers.reserve(shapes.size());
buffer_ptrs.reserve(shapes.size());
definition_events.reserve(shapes.size());
for (const auto& shape : shapes) {
if (shape.IsTuple()) {
return Unimplemented(
"Async buffer transfer of tuples not implemented.");
}
definition_events.push_back(
std::make_shared<BufferSequencingEvent>(client->thread_pool()));
TF_ASSIGN_OR_RETURN(Shape compact_shape,
client->client()
->backend()
.transfer_manager()
->ChooseCompactLayoutForShape(shape));
LocalDeviceState* local_device = device->local_device_state();
se::Stream* h2d_stream = local_device->host_to_device_stream();
TF_ASSIGN_OR_RETURN(auto buffer,
AllocateDestinationBuffer(
compact_shape, device, local_device, h2d_stream,
true, client,
definition_events.back()));
auto* se_buffer =
tensorflow::down_cast<PjRtStreamExecutorBuffer*>(buffer.get());
DCHECK(se_buffer);
auto hold = se_buffer->GetBufferWithUsageHold();
buffer_ptrs.push_back(hold.buffer());
buffers.push_back(std::move(buffer));
}
return std::make_unique<AsyncHostToDeviceTransferManager>(
std::move(buffers), std::move(buffer_ptrs),
std::move(definition_events), device);
}
AsyncHostToDeviceTransferManager(
absl::InlinedVector<std::unique_ptr<PjRtBuffer>, 4> buffers,
absl::InlinedVector<std::shared_ptr<TrackedDeviceBuffer>, 4> buffer_ptrs,
absl::InlinedVector<std::shared_ptr<BufferSequencingEvent>, 4>
definition_events,
PjRtStreamExecutorDevice* device)
: buffers_(std::move(buffers)),
buffer_ptrs_(std::move(buffer_ptrs)),
definition_events_(std::move(definition_events)),
remaining_buffer_count_(buffer_ptrs_.size()),
transfers_in_flight_(0),
device_(device) {
buffer_sizes_.reserve(buffer_ptrs_.size());
for (const auto& ptr : buffer_ptrs_) {
DCHECK_EQ(ptr->device_memory().size(), 1);
buffer_sizes_.push_back(ptr->device_memory()[0].size());
}
last_transfer_started_.resize(buffer_ptrs_.size(), false);
}
~AsyncHostToDeviceTransferManager() override {
auto transfers_finished = [this]() {
mu_.AssertHeld();
return transfers_in_flight_ == 0;
};
{
absl::MutexLock l(&mu_);
mu_.Await(absl::Condition(&transfers_finished));
}
}
size_t buffer_count() const override { return buffers_.size(); };
size_t buffer_size(int buffer_index) const override {
DCHECK_LT(buffer_index, buffer_sizes_.size());
return buffer_sizes_[buffer_index];
}
PjRtDevice* device() const override { return device_; }
std::unique_ptr<PjRtBuffer> RetrieveBuffer(int buffer_index) override {
DCHECK_LT(buffer_index, buffers_.size());
return std::move(buffers_[buffer_index]);
};
absl::Status TransferLiteralToBuffer(
int buffer_index, const LiteralSlice& literal,
absl::AnyInvocable<void() &&> on_done) override {
tsl::profiler::TraceMe traceme(
"AsyncHostToDeviceTransferManager::TransferLiteralToBuffer");
auto* stream = device_->local_device_state()->host_to_device_stream();
auto* se_client =
tensorflow::down_cast<PjRtStreamExecutorClient*>(device_->client());
DCHECK(se_client);
TransferManager* transfer_manager =
se_client->client()->backend().transfer_manager();
TF_ASSIGN_OR_RETURN(
Shape compact_shape,
transfer_manager->ChooseCompactLayoutForShape(literal.shape()));
std::shared_ptr<TrackedDeviceBuffer> buffer;
{
absl::MutexLock l(&mu_);
DCHECK_LT(buffer_index, buffer_ptrs_.size());
if (last_transfer_started_[buffer_index]) {
return InvalidArgument(
"TransferLiteralToBuffer requested for buffer index %d which has "
"already been fully transferred",
buffer_index);
}
last_transfer_started_[buffer_index] = true;
buffer = buffer_ptrs_[buffer_index];
DCHECK(buffer);
if (buffer->device_memory().empty()) {
return InvalidArgument(
"TransferLiteralToBuffer requested for buffer index %d which has "
"been donated. Async transfer of donated buffers is not supported "
"in SE:GPU",
buffer_index);
}
DCHECK_EQ(buffer->device_memory().size(), 1);
auto& buffer_memory = buffer->device_memory()[0];
if (transfer_manager->GetByteSizeRequirement(compact_shape) !=
buffer_memory.size()) {
return InvalidArgument(
"TransferLiteralToBuffer shape %s has size %lld "
"but buffer has size %lld",
ShapeUtil::HumanStringWithLayout(compact_shape),
transfer_manager->GetByteSizeRequirement(compact_shape),
buffer_memory.size());
}
++transfers_in_flight_;
}
auto transfer_h2d = [this, buffer_index, stream, transfer_manager, literal,
device_buffer = buffer.get(), compact_shape,
local_device =
std::move(device_->local_device_state()),
on_done = std::move(on_done)]() mutable {
tsl::profiler::TraceMe traceme(
"AsyncHostToDeviceTransferManager::TransferLiteralToBuffer::transfer_"
"h2d");
auto event = local_device->event_pool().AllocateEvent(stream->parent());
ShapedBuffer buffer = device_buffer->AsShapedBuffer(compact_shape);
TF_CHECK_OK(transfer_manager->TransferLiteralToDeviceAsync(
stream, literal, buffer));
local_device->event_pool().ThenRecordEvent(stream, event.value());
auto cleanup = [this, buffer_index, stream, on_done = std::move(on_done),
event = std::move(event).value()]() mutable {
CleanUp(buffer_index, std::move(event), stream,
true, std::move(on_done));
};
auto status = stream->DoHostCallback(std::move(cleanup));
if (!status.ok()) {
LOG(ERROR) << "DoHostCallback failed: " << status;
}
};
se_client->thread_pool()->Schedule(
([ptr = new absl::AnyInvocable<void()>(std::move(transfer_h2d))]() {
(*ptr)();
delete ptr;
}));
return absl::OkStatus();
}
absl::Status TransferRawDataToBuffer(
int buffer_index, absl::string_view data,
absl::AnyInvocable<void() &&> on_done) override {
return TransferRawDataToSubBuffer(buffer_index, data.data(),
0, data.size(),
true,
std::move(on_done));
}
absl::Status TransferRawDataToSubBuffer(
int buffer_index, const void* data, int64_t offset, int64_t transfer_size,
bool is_last_transfer, absl::AnyInvocable<void() &&> on_done) override {
auto* stream = device_->local_device_state()->host_to_device_stream();
auto* client =
tensorflow::down_cast<PjRtStreamExecutorClient*>(device_->client());
bool should_stage_host_to_device_transfers =
client->should_stage_host_to_device_transfers();
std::shared_ptr<void> staging_buffer;
if (should_stage_host_to_device_transfers) {
auto* host_memory_allocator = client->host_memory_allocator();
if (host_memory_allocator == nullptr) {
return InvalidArgument(
"host_memory_allocator should be initialized for staging buffer "
"transfer.");
}
void* ptr = host_memory_allocator->AllocateRaw(
tsl::Allocator::kAllocatorAlignment, transfer_size);
staging_buffer = std::shared_ptr<void>(
ptr, [host_memory_allocator = host_memory_allocator](void* ptr) {
host_memory_allocator->DeallocateRaw(ptr);
});
}
absl::ReleasableMutexLock l(&mu_);
DCHECK_LT(buffer_index, buffer_ptrs_.size());
if (last_transfer_started_[buffer_index]) {
return InvalidArgument(
"TransferRawData requested for buffer index %d which has "
"already been fully transferred",
buffer_index);
}
if (is_last_transfer) {
last_transfer_started_[buffer_index] = true;
}
DCHECK(buffer_ptrs_[buffer_index]);
if (buffer_ptrs_[buffer_index]->device_memory().empty()) {
return InvalidArgument(
"TransferRawDataToSubBuffer requested for buffer index %d which has "
"been donated. Async transfer of donated buffers is not supported "
"in SE:GPU",
buffer_index);
}
DCHECK_EQ(buffer_ptrs_[buffer_index]->device_memory().size(), 1);
auto& buffer_memory = buffer_ptrs_[buffer_index]->device_memory()[0];
se::DeviceMemoryBase sub_buffer;
CHECK_LE(offset, buffer_memory.size());
CHECK_LE(transfer_size, buffer_memory.size() - offset);
if (transfer_size < buffer_memory.size()) {
sub_buffer = buffer_memory.GetByteSlice(offset, transfer_size);
} else {
sub_buffer = buffer_memory;
}
++transfers_in_flight_;
l.Release();
auto event = device_->local_device_state()->event_pool().AllocateEvent(
stream->parent());
if (transfer_size != 0) {
if (staging_buffer != nullptr) {
auto copy_to_staging_buffer = [data, transfer_size,
staging_buffer]() mutable {
std::memcpy(staging_buffer.get(), data, transfer_size);
};
if (auto status =
stream->DoHostCallback(std::move(copy_to_staging_buffer));
!status.ok()) {
return status;
}
if (auto status = stream->Memcpy(&sub_buffer, staging_buffer.get(),
transfer_size);
!status.ok()) {
return status;
}
} else if (auto status = stream->Memcpy(&sub_buffer, data, transfer_size);
!status.ok()) {
return status;
}
}
device_->local_device_state()->event_pool().ThenRecordEvent(stream,
event.value());
auto cleanup = [this, buffer_index, event = std::move(event).value(),
stream, is_last_transfer, on_done = std::move(on_done),
staging_buffer = std::move(staging_buffer)]() mutable {
CleanUp(buffer_index, std::move(event), stream, is_last_transfer,
std::move(on_done));
};
return stream->DoHostCallback(std::move(cleanup));
}
void SetBufferError(int buffer_index, absl::Status error) override {
{
absl::MutexLock l(&mu_);
CHECK(!definition_events_[buffer_index]->IsDefined());
definition_events_[buffer_index]->SetDefinedStatus(error);
}
VLOG(1) << "SetBufferError sets the " << buffer_index
<< "th buffer error: " << error;
}
void AddTransferMetadata(const TransferMetadata& meta) override {}
private:
absl::Mutex mu_;
absl::InlinedVector<std::unique_ptr<PjRtBuffer>, 4> buffers_;
absl::InlinedVector<size_t, 4> buffer_sizes_;
absl::InlinedVector<std::shared_ptr<TrackedDeviceBuffer>, 4> buffer_ptrs_
ABSL_GUARDED_BY(mu_);
absl::InlinedVector<bool, 4> last_transfer_started_ ABSL_GUARDED_BY(mu_);
absl::InlinedVector<std::shared_ptr<BufferSequencingEvent>, 4>
definition_events_ ABSL_GUARDED_BY(mu_);
size_t remaining_buffer_count_ ABSL_GUARDED_BY(mu_);
int transfers_in_flight_ ABSL_GUARDED_BY(mu_);
PjRtStreamExecutorDevice* device_;
void CleanUp(int buffer_index, EventPool::Handle event, se::Stream* stream,
bool is_last_transfer, absl::AnyInvocable<void() &&> on_done) {
{
absl::MutexLock l(&mu_);
CHECK_GT(transfers_in_flight_, 0);
--transfers_in_flight_;
if (is_last_transfer) {
CHECK(buffer_ptrs_[buffer_index]);
buffer_ptrs_[buffer_index] = nullptr;
CHECK_GT(remaining_buffer_count_, 0);
--remaining_buffer_count_;
definition_events_[buffer_index]->SetSequencingEvent(std::move(event),
stream);
if (remaining_buffer_count_ == 0) {
VLOG(1) << "TransferLiteralToBuffer for all buffers is done.";
}
}
}
std::move(on_done)();
}
};
StreamExecutorGpuClient::StreamExecutorGpuClient(
std::string platform_name, LocalClient* client,
std::vector<std::unique_ptr<PjRtStreamExecutorDevice>> devices,
int process_index, std::unique_ptr<se::DeviceMemoryAllocator> allocator,
std::unique_ptr<tsl::Allocator> host_memory_allocator,
bool should_stage_host_to_device_transfers,
std::unique_ptr<gpu::GpuExecutableRunOptions> gpu_run_options,
std::shared_ptr<KeyValueStoreInterface> kv_store,
std::shared_ptr<const GpuTopology> gpu_topology)
: xla::PjRtStreamExecutorClient(
platform_name, client, std::move(devices), process_index,
std::move(allocator), std::move(host_memory_allocator),
should_stage_host_to_device_transfers, std::move(gpu_run_options)),
topology_(xla::StreamExecutorGpuTopologyDescription::Create(
tsl::Fingerprint64(platform_name), platform_name,
std::move(gpu_topology))),
kv_store_(std::move(kv_store)) {
for (auto* device : addressable_devices()) {
const int id = device->id();
auto memory_space =
std::make_unique<StreamExecutorGpuHbmMemorySpace>(id, device);
tensorflow::down_cast<PjRtStreamExecutorDevice*>(device)->AttachMemorySpace(
memory_space.get());
owned_memory_spaces_.push_back(std::move(memory_space));
const size_t basePinnedId = devices.size();
auto pinned = std::make_unique<PinnedHostMemorySpace>(basePinnedId, device);
tensorflow::down_cast<PjRtStreamExecutorDevice*>(device)->AttachMemorySpace(
pinned.get());
owned_memory_spaces_.push_back(std::move(pinned));
}
for (const std::unique_ptr<PjRtMemorySpace>& memory_space :
owned_memory_spaces_) {
memory_spaces_.push_back(memory_space.get());
}
absl::c_sort(memory_spaces_,
[](const PjRtMemorySpace* a, const PjRtMemorySpace* b) {
return a->id() < b->id();
});
}
absl::string_view StreamExecutorGpuClient::platform_version() const {
#define STRINGIFY2(X) #X
#define STRINGIFY(X) STRINGIFY2(X)
#if TENSORFLO | #include "xla/pjrt/gpu/se_gpu_pjrt_client.h"
#include <stdlib.h>
#include <array>
#include <cstdint>
#include <cstring>
#include <memory>
#include <numeric>
#include <optional>
#include <string>
#include <utility>
#include <vector>
#include "absl/log/check.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/match.h"
#include "absl/strings/string_view.h"
#include "absl/synchronization/mutex.h"
#include "absl/time/clock.h"
#include "absl/time/time.h"
#include "xla/client/xla_computation.h"
#include "xla/ffi/ffi.h"
#include "xla/ffi/ffi_api.h"
#include "xla/literal.h"
#include "xla/literal_util.h"
#include "xla/pjrt/distributed/in_memory_key_value_store.h"
#include "xla/pjrt/gpu/gpu_topology.h"
#include "xla/pjrt/host_memory_spaces.h"
#include "xla/pjrt/pjrt_client.h"
#include "xla/pjrt/pjrt_executable.h"
#include "xla/pjrt/pjrt_future.h"
#include "xla/pjrt/pjrt_stream_executor_client.h"
#include "xla/service/hlo_parser.h"
#include "xla/service/platform_util.h"
#include "xla/shape.h"
#include "xla/shape_util.h"
#include "xla/status_macros.h"
#include "xla/stream_executor/stream.h"
#include "xla/test.h"
#include "xla/tests/literal_test_util.h"
#include "xla/xla_data.pb.h"
#include "tsl/lib/core/status_test_util.h"
#include "tsl/platform/env.h"
#include "tsl/platform/errors.h"
#include "tsl/platform/status.h"
#include "tsl/platform/status_matchers.h"
#include "tsl/platform/statusor.h"
#include "tsl/platform/threadpool.h"
namespace xla {
namespace {
using ::testing::ElementsAre;
using ::testing::HasSubstr;
using ::tsl::testing::IsOkAndHolds;
using ::tsl::testing::StatusIs;
absl::StatusOr<std::unique_ptr<xla::PjRtLoadedExecutable>> CompileExecutable(
absl::string_view program, xla::PjRtClient& client,
xla::CompileOptions compile_options = xla::CompileOptions()) {
TF_ASSIGN_OR_RETURN(auto hlo_module,
ParseAndReturnUnverifiedModule(program, {}));
xla::XlaComputation xla_computation(hlo_module->ToProto());
return client.Compile(xla_computation, compile_options);
}
absl::StatusOr<std::shared_ptr<xla::Literal>> ExtractSingleResult(
absl::StatusOr<std::vector<std::vector<std::unique_ptr<xla::PjRtBuffer>>>>&
result) {
TF_RETURN_IF_ERROR(result.status());
TF_RET_CHECK(result->size() == 1);
std::vector<std::unique_ptr<xla::PjRtBuffer>>& result_buffers = (*result)[0];
TF_RET_CHECK(result_buffers.size() == 1);
auto literal_or = result_buffers[0]->ToLiteralSync();
if (!literal_or.status().ok()) return literal_or.status();
return *literal_or;
}
static constexpr char const* kProgram = R"(HloModule HostTransfer
ENTRY SendRecvSynchronous() -> f32[2] {
in_chain = token[] after-all()
data = f32[2] constant({2, 3})
send = (f32[2], u32[], token[]) send(data, in_chain),
channel_id=1,
is_host_transfer=true,
frontend_attributes={
_xla_host_transfer_handler_name="undef",
_xla_host_transfer_rendezvous="undef"
}
send-done = token[] send-done(send),
channel_id=1, is_host_transfer=true
recv = (f32[2], u32[], token[]) recv(send-done),
channel_id=2,
is_host_transfer=true,
frontend_attributes={
_xla_host_transfer_handler_name="undef",
_xla_host_transfer_rendezvous="undef"
}
recv-done = (f32[2], token[]) recv-done(recv),
channel_id=2, is_host_transfer=true
ROOT result = f32[2] get-tuple-element(recv-done), index=0
})";
TEST(StreamExecutorGpuClientTest, MemorySpace) {
TF_ASSERT_OK_AND_ASSIGN(auto client,
GetStreamExecutorGpuClient(GpuClientOptions()));
ASSERT_GE(client->devices().size(), 1);
for (auto* device : client->devices()) {
TF_ASSERT_OK_AND_ASSIGN(auto* memory_space, device->default_memory_space());
EXPECT_EQ(memory_space->kind(), StreamExecutorGpuHbmMemorySpace::kKind);
EXPECT_EQ(memory_space->kind_id(),
StreamExecutorGpuHbmMemorySpace::kKindId);
EXPECT_THAT(
device->memory_space_by_kind(StreamExecutorGpuHbmMemorySpace::kKind),
IsOkAndHolds(memory_space));
EXPECT_EQ(device->memory_spaces().size(), 2);
auto* pinned = device->memory_spaces()[1];
EXPECT_EQ(pinned->kind_id(), PinnedHostMemorySpace::kKindId);
EXPECT_THAT(device->memory_space_by_kind(PinnedHostMemorySpace::kKind),
IsOkAndHolds(pinned));
}
}
TEST(StreamExecutorGpuClientTest, PropagateError) {
TF_ASSERT_OK_AND_ASSIGN(auto client,
GetStreamExecutorGpuClient(GpuClientOptions()));
auto shape = xla::ShapeUtil::MakeScalarShape(xla::F32);
absl::Status input_error = absl::InvalidArgumentError("input error");
TF_ASSERT_OK_AND_ASSIGN(
auto buffer,
client->CreateErrorBuffer(
input_error, shape,
*client->addressable_devices()[0]->default_memory_space()));
static constexpr char const* kAddProgram =
R"(
HloModule Add.6, entry_computation_layout={(f32[], f32[])->(f32[], f32[])}
ENTRY %Add.6 (a.1: f32[], b.2: f32[]) -> (f32[], f32[]) {
%a.1 = f32[] parameter(0)
%b.2 = f32[] parameter(1)
%add.3 = f32[] add(f32[] %a.1, f32[] %b.2)
%add.4 = f32[] add(f32[] %add.3, f32[] %add.3)
ROOT %tuple.5 = (f32[], f32[]) tuple(f32[] %add.3, f32[] %add.4)
}
)";
TF_ASSERT_OK_AND_ASSIGN(auto executable,
CompileExecutable(kAddProgram, *client));
TF_ASSERT_OK_AND_ASSIGN(
auto result,
executable->Execute({{buffer.get(), buffer.get()}}, {}));
ASSERT_EQ(result.size(), 1);
ASSERT_EQ(result[0].size(), 1);
EXPECT_EQ(result[0][0]->GetReadyFuture().Await(), input_error);
}
TEST(StreamExecutorGpuClientTest, SendRecvChunked) {
TF_ASSERT_OK_AND_ASSIGN(auto client,
GetStreamExecutorGpuClient(GpuClientOptions()));
TF_ASSERT_OK_AND_ASSIGN(auto executable,
CompileExecutable(kProgram, *client));
std::array<float, 2> sent_value = {0.0f, 0.0f};
SendCallback send_callback = {
1, [&](const PjRtTransferMetadata& m, PjRtChunk chunk,
int64_t total_size_in_bytes, bool done) {
float* data = reinterpret_cast<float*>(chunk.data());
sent_value[0] = data[0];
sent_value[1] = data[1];
return absl::OkStatus();
}};
RecvCallback recv_callback = {
2, [&](const PjRtTransferMetadata& m,
std::unique_ptr<CopyToDeviceStream> stream) {
auto chunk0 = PjRtChunk::AllocateDefault(sizeof(float));
*reinterpret_cast<float*>(chunk0.data()) = 5.0f;
TF_CHECK_OK(stream->AddChunk(std::move(chunk0)).Await());
auto chunk1 = PjRtChunk::AllocateDefault(sizeof(float));
*reinterpret_cast<float*>(chunk1.data()) = 6.0f;
TF_CHECK_OK(stream->AddChunk(std::move(chunk1)).Await());
return absl::OkStatus();
}};
std::vector<std::vector<SendCallback>> send_callbacks = {{send_callback}};
std::vector<std::vector<RecvCallback>> recv_callbacks = {{recv_callback}};
ExecuteOptions opts;
opts.send_callbacks = send_callbacks;
opts.recv_callbacks = recv_callbacks;
auto result = executable->Execute({{}}, opts);
TF_ASSERT_OK_AND_ASSIGN(std::shared_ptr<xla::Literal> result_literal,
ExtractSingleResult(result));
EXPECT_EQ(sent_value[0], 2.0f);
EXPECT_EQ(sent_value[1], 3.0f);
EXPECT_TRUE(LiteralTestUtil::Equal(LiteralUtil::CreateR1<float>({5.0f, 6.0f}),
*result_literal));
}
TEST(StreamExecutorGpuClientTest, SendErrorNoDeadLock) {
TF_ASSERT_OK_AND_ASSIGN(auto client,
GetStreamExecutorGpuClient(GpuClientOptions()));
TF_ASSERT_OK_AND_ASSIGN(auto executable,
CompileExecutable(kProgram, *client));
SendCallback send_callback = {
1,
[&](const PjRtTransferMetadata&, PjRtChunk, int64_t, bool) {
return Internal("Uh-oh, can send chunk to host");
}};
RecvCallback recv_callback = {
2, [&](const PjRtTransferMetadata& m,
std::unique_ptr<CopyToDeviceStream> stream) {
return absl::OkStatus();
}};
std::vector<std::vector<SendCallback>> send_callbacks = {{send_callback}};
std::vector<std::vector<RecvCallback>> recv_callbacks = {{recv_callback}};
ExecuteOptions opts;
opts.send_callbacks = send_callbacks;
opts.recv_callbacks = recv_callbacks;
auto result = executable->Execute({{}}, opts);
EXPECT_TRUE(absl::StrContains(result.status().message(),
"Uh-oh, can send chunk to host"));
}
TEST(StreamExecutorGpuClientTest, RecvErrorNoDeadLock) {
TF_ASSERT_OK_AND_ASSIGN(auto client,
GetStreamExecutorGpuClient(GpuClientOptions()));
TF_ASSERT_OK_AND_ASSIGN(auto executable,
CompileExecutable(kProgram, *client));
SendCallback send_callback = {
1, [&](const PjRtTransferMetadata&, PjRtChunk, int64_t,
bool) { return absl::OkStatus(); }};
RecvCallback recv_callback = {
2, [&](const PjRtTransferMetadata& m,
std::unique_ptr<CopyToDeviceStream> stream) {
auto chunk = PjRtChunk::AllocateDefault(10 * sizeof(float));
stream->AddChunk(std::move(chunk)).Await().IgnoreError();
return absl::OkStatus();
}};
std::vector<std::vector<SendCallback>> send_callbacks = {{send_callback}};
std::vector<std::vector<RecvCallback>> recv_callbacks = {{recv_callback}};
ExecuteOptions opts;
opts.send_callbacks = send_callbacks;
opts.recv_callbacks = recv_callbacks;
auto result = executable->Execute({{}}, opts);
EXPECT_TRUE(absl::StrContains(result.status().message(),
"Adding chunk of size 40 would overflow buffer "
"of size 8 (0 already transferred)"));
}
struct MemsetValue {
explicit MemsetValue(float value) : value(value) {}
float value;
};
static absl::Status MemsetFromValue(
se::Stream* stream, ffi::Result<ffi::BufferR1<PrimitiveType::F32>> result,
MemsetValue* memset_value) {
uint32_t pattern;
std::memcpy(&pattern, &memset_value->value, sizeof(pattern));
se::DeviceMemoryBase base = result->data;
return stream->Memset32(&base, pattern, result->data.size());
}
XLA_FFI_DEFINE_HANDLER(kMemsetFromValue, MemsetFromValue,
ffi::Ffi::Bind()
.Ctx<ffi::Stream>()
.Ret<ffi::BufferR1<PrimitiveType::F32>>()
.Ctx<ffi::UserData<MemsetValue>>());
XLA_FFI_REGISTER_HANDLER(ffi::GetXlaFfiApi(), "MemsetFromValue",
PlatformUtil::CanonicalPlatformName("GPU").value(),
kMemsetFromValue);
TEST(StreamExecutorGpuClientTest, ForwardUserDataToFfiHandler) {
static constexpr char const* kProgram = R"(
HloModule ffi_handler
ENTRY main {
ROOT %custom-call = f32[4] custom-call(),
custom_call_target="MemsetFromValue",
api_version=API_VERSION_TYPED_FFI
})";
TF_ASSERT_OK_AND_ASSIGN(auto client,
GetStreamExecutorGpuClient(GpuClientOptions()));
TF_ASSERT_OK_AND_ASSIGN(auto executable,
CompileExecutable(kProgram, *client));
ExecuteContext context;
TF_ASSERT_OK(context.ffi_context().Emplace<MemsetValue>(42.0f));
ExecuteOptions opts;
opts.context = &context;
auto result = executable->Execute({{}}, opts);
TF_ASSERT_OK_AND_ASSIGN(std::shared_ptr<xla::Literal> result_literal,
ExtractSingleResult(result));
EXPECT_TRUE(LiteralTestUtil::Equal(
LiteralUtil::CreateR1<float>({42.0f, 42.0f, 42.0f, 42.0f}),
*result_literal));
}
TEST(StreamExecutorGpuClientTest, ToLiteralAsync) {
TF_ASSERT_OK_AND_ASSIGN(auto client,
GetStreamExecutorGpuClient(GpuClientOptions()));
ASSERT_GE(client->addressable_devices().size(), 1);
auto src_literal = LiteralUtil::CreateR1<float>({41.0f, 42.0f, 43.0f, 44.0f});
TF_ASSERT_OK_AND_ASSIGN(
auto transfer_manager,
client->CreateBuffersForAsyncHostToDevice(
{src_literal.shape()}, client->addressable_devices()[0]));
auto buffer = transfer_manager->RetrieveBuffer(0);
absl::Mutex mu;
auto literal = std::make_shared<Literal>(
ShapeUtil::DeviceShapeToHostShape(buffer->on_device_shape()));
bool got_literal = false;
TF_ASSERT_OK(
transfer_manager->TransferLiteralToBuffer(0, src_literal, [&]() {}));
buffer->ToLiteral(literal.get()).OnReady([&](absl::Status s) {
absl::MutexLock l(&mu);
TF_ASSERT_OK(s);
got_literal = true;
});
buffer.reset();
{
absl::MutexLock l(&mu);
mu.Await(absl::Condition(&got_literal));
}
ASSERT_TRUE(ShapeUtil::Compatible(src_literal.shape(), literal->shape()));
ASSERT_EQ(src_literal.data<float>(),
literal->Relayout(src_literal.shape().layout()).data<float>());
}
TEST(StreamExecutorGpuClientTest, ToLiteralAsyncBeforeBufferReady) {
TF_ASSERT_OK_AND_ASSIGN(auto client,
GetStreamExecutorGpuClient(GpuClientOptions()));
ASSERT_GE(client->addressable_devices().size(), 1);
auto src_literal = LiteralUtil::CreateR1<float>({41.0f, 42.0f, 43.0f, 44.0f});
TF_ASSERT_OK_AND_ASSIGN(
auto transfer_manager,
client->CreateBuffersForAsyncHostToDevice(
{src_literal.shape()}, client->addressable_devices()[0]));
auto buffer = transfer_manager->RetrieveBuffer(0);
absl::Mutex mu;
auto literal = std::make_shared<Literal>(
ShapeUtil::DeviceShapeToHostShape(buffer->on_device_shape()));
bool got_literal = false;
buffer->ToLiteral(literal.get()).OnReady([&](absl::Status s) {
absl::MutexLock l(&mu);
TF_ASSERT_OK(s);
got_literal = true;
});
absl::SleepFor(absl::Milliseconds(10));
ASSERT_FALSE(got_literal);
TF_ASSERT_OK(
transfer_manager->TransferLiteralToBuffer(0, src_literal, [&]() {}));
buffer.reset();
{
absl::MutexLock l(&mu);
mu.Await(absl::Condition(&got_literal));
}
ASSERT_TRUE(ShapeUtil::Compatible(src_literal.shape(), literal->shape()));
ASSERT_EQ(src_literal.data<float>(),
literal->Relayout(src_literal.shape().layout()).data<float>());
}
TEST(StreamExecutorGpuClientTest, FromHostAsync) {
TF_ASSERT_OK_AND_ASSIGN(auto client,
GetStreamExecutorGpuClient(GpuClientOptions()));
ASSERT_GE(client->addressable_devices().size(), 1);
std::vector<Literal> src_literals;
std::vector<Shape> src_shapes;
for (int i = 0; i < 4; ++i) {
std::vector<float> data(i + 1);
std::iota(data.begin(), data.end(), static_cast<float>(i + 10));
src_literals.emplace_back(LiteralUtil::CreateR1<float>(data));
src_shapes.push_back(src_literals.back().shape());
}
TF_ASSERT_OK_AND_ASSIGN(auto transfer_manager,
client->CreateBuffersForAsyncHostToDevice(
src_shapes, client->addressable_devices()[0]));
std::vector<std::unique_ptr<PjRtBuffer>> buffers;
for (int i = 0; i < src_shapes.size(); ++i) {
buffers.emplace_back(transfer_manager->RetrieveBuffer(i));
}
for (int i = 0; i < src_shapes.size(); ++i) {
TF_ASSERT_OK(transfer_manager->TransferRawDataToBuffer(
i,
absl::string_view(static_cast<char*>(src_literals[i].untyped_data()),
src_literals[i].size_bytes()),
[&]() {}));
}
absl::Mutex mu;
std::vector<std::shared_ptr<Literal>> literals;
int got_literal_count = 0;
int got_callback_count = 0;
for (auto& buffer : buffers) {
literals.push_back(std::make_shared<Literal>(
ShapeUtil::DeviceShapeToHostShape(buffer->on_device_shape())));
buffer->ToLiteral(literals.back().get()).OnReady([&](absl::Status s) {
absl::MutexLock l(&mu);
TF_ASSERT_OK(s);
++got_literal_count;
});
buffer->GetReadyFuture().OnReady([&](absl::Status s) {
absl::MutexLock l(&mu);
TF_ASSERT_OK(s);
++got_callback_count;
});
buffer.reset();
}
{
auto done = [&]() {
return got_literal_count == src_literals.size() &&
got_callback_count == src_literals.size();
};
absl::MutexLock l(&mu);
mu.Await(absl::Condition(&done));
}
for (int i = 0; i < src_literals.size(); ++i) {
ASSERT_TRUE(
ShapeUtil::Compatible(src_literals[i].shape(), literals[i]->shape()));
ASSERT_EQ(
src_literals[i].data<float>(),
literals[i]->Relayout(src_literals[i].shape().layout()).data<float>());
}
}
TEST(StreamExecutorGpuClientTest, CopyRawToHostFullBuffer) {
TF_ASSERT_OK_AND_ASSIGN(auto client,
GetStreamExecutorGpuClient(GpuClientOptions()));
auto literal = xla::LiteralUtil::CreateR1<float>({41.0f, 42.0f});
TF_ASSERT_OK_AND_ASSIGN(
std::unique_ptr<PjRtBuffer> buffer,
client->BufferFromHostLiteral(literal, client->addressable_devices()[0]));
void* dst = aligned_alloc(buffer->GetOnDeviceSizeInBytes().value(), 0);
auto result =
buffer->CopyRawToHost(dst, 0, buffer->GetOnDeviceSizeInBytes().value());
TF_EXPECT_OK(result.Await());
EXPECT_EQ(*(static_cast<float*>(dst)), 41.0f);
EXPECT_EQ(*(static_cast<float*>(dst) + 1), 42.0f);
free(dst);
}
TEST(StreamExecutorGpuClientTest, CopyRawToHostSubBuffer) {
TF_ASSERT_OK_AND_ASSIGN(auto client,
GetStreamExecutorGpuClient(GpuClientOptions()));
auto literal = xla::LiteralUtil::CreateR1<float>({41.0f, 42.0f});
TF_ASSERT_OK_AND_ASSIGN(
std::unique_ptr<PjRtBuffer> buffer,
client->BufferFromHostLiteral(literal, client->addressable_devices()[0]));
void* dst = aligned_alloc(buffer->GetOnDeviceSizeInBytes().value(), 0);
auto result = buffer->CopyRawToHost(dst, 0, sizeof(float));
TF_EXPECT_OK(result.Await());
EXPECT_EQ(*(static_cast<float*>(dst)), 41.0f);
free(dst);
}
TEST(StreamExecutorGpuClientTest, CopyRawToHostOutOfRange) {
TF_ASSERT_OK_AND_ASSIGN(auto client,
GetStreamExecutorGpuClient(GpuClientOptions()));
auto literal = xla::LiteralUtil::CreateR1<float>({41.0f, 42.0f});
TF_ASSERT_OK_AND_ASSIGN(
std::unique_ptr<PjRtBuffer> buffer,
client->BufferFromHostLiteral(literal, client->addressable_devices()[0]));
void* dst = aligned_alloc(buffer->GetOnDeviceSizeInBytes().value(), 0);
auto result =
buffer->CopyRawToHost(dst, 1, buffer->GetOnDeviceSizeInBytes().value());
EXPECT_THAT(result.Await(), StatusIs(absl::StatusCode::kInvalidArgument,
HasSubstr("invalid offset 1")));
free(dst);
}
TEST(StreamExecutorGpuClientTest, CopyRawToHostFuture) {
TF_ASSERT_OK_AND_ASSIGN(auto client,
GetStreamExecutorGpuClient(GpuClientOptions()));
auto literal = xla::LiteralUtil::CreateR1<float>({41.0f, 42.0f});
TF_ASSERT_OK_AND_ASSIGN(
std::unique_ptr<PjRtBuffer> buffer,
client->BufferFromHostLiteral(literal, client->addressable_devices()[0]));
auto dst_promise = xla::PjRtFuture<void*>::CreatePromise();
xla::PjRtFuture<void*> dst_future(dst_promise);
TF_ASSERT_OK_AND_ASSIGN(int64_t size, buffer->GetOnDeviceSizeInBytes());
auto ready = buffer->GetReadyFuture();
auto result = buffer->CopyRawToHostFuture(dst_future, 0, size);
buffer.reset();
ready.OnReady([dst_promise = std::move(dst_promise),
size](absl::Status status) mutable {
dst_promise.Set(aligned_alloc(size, 0));
});
TF_EXPECT_OK(result.Await());
TF_ASSERT_OK_AND_ASSIGN(auto* dst, dst_future.Await());
EXPECT_EQ(*(static_cast<float*>(dst)), 41.0f);
EXPECT_EQ(*(static_cast<float*>(dst) + 1), 42.0f);
free(dst);
}
TEST(StreamExecutorGpuClientTest, AsyncCopyToDevice) {
TF_ASSERT_OK_AND_ASSIGN(auto client,
GetStreamExecutorGpuClient(GpuClientOptions()));
ASSERT_GE(client->addressable_devices().size(), 2);
auto* d0 = client->addressable_devices()[0];
auto* d1 = client->addressable_devices()[1];
auto src_literal = LiteralUtil::CreateR1<float>({41.0f, 42.0f, 43.0f, 44.0f});
TF_ASSERT_OK_AND_ASSIGN(
auto transfer_manager,
client->CreateBuffersForAsyncHostToDevice({src_literal.shape()}, d0));
auto src_buffer = transfer_manager->RetrieveBuffer(0);
auto local_recv_buffer = *src_buffer->CopyToDevice(d1);
TF_ASSERT_OK(
transfer_manager->TransferLiteralToBuffer(0, src_literal, []() {}));
auto literal = std::make_shared<Literal>(src_literal.shape());
auto local_recv_literal = local_recv_buffer->ToLiteral(literal.get());
TF_EXPECT_OK(local_recv_literal.Await());
ASSERT_TRUE(ShapeUtil::Compatible(src_literal.shape(), literal->shape()));
ASSERT_EQ(src_literal.data<float>(),
literal->Relayout(src_literal.shape().layout()).data<float>());
}
TEST(StreamExecutorGpuClientTest, CreateMixOfErrorBuffers) {
TF_ASSERT_OK_AND_ASSIGN(auto client,
GetStreamExecutorGpuClient(GpuClientOptions()));
ASSERT_GE(client->addressable_devices().size(), 1);
std::vector<Literal> src_literals;
std::vector<Shape> src_shapes;
for (int i = 0; i < 4; ++i) {
std::vector<float> data(i + 1);
std::iota(data.begin(), data.end(), static_cast<float>(i + 10));
src_literals.emplace_back(LiteralUtil::CreateR1<float>(data));
src_shapes.push_back(src_literals.back().shape());
}
TF_ASSERT_OK_AND_ASSIGN(
auto transfer_manager,
client->CreateBuffersForAsyncHostToDevice(
src_shapes, client->addressable_devices()[0]->memory_spaces()[0]));
std::vector<std::unique_ptr<PjRtBuffer>> buffers;
for (int i = 0; i < src_shapes.size(); ++i) {
buffers.emplace_back(transfer_manager->RetrieveBuffer(i));
}
absl::Mutex mu;
int got_callback_count = 0;
for (int i = 0; i < 4; ++i) {
auto& buffer = buffers[i];
if (i == 0 || i == 3) {
TF_ASSERT_OK(transfer_manager->TransferLiteralToBuffer(i, src_literals[i],
[&]() {}));
buffer->GetReadyFuture().OnReady([&](absl::Status s) {
absl::MutexLock l(&mu);
TF_ASSERT_OK(s);
++got_callback_count;
});
} else {
absl::Status error = Internal("error %d", i);
transfer_manager->SetBufferError(i, error);
buffer->GetReadyFuture().OnReady(
[error, &mu, &got_callback_count](absl::Status s) {
absl::MutexLock l(&mu);
ASSERT_EQ(s, error);
++got_callback_count;
});
}
buffer.reset();
}
{
auto done = [&]() { return got_callback_count == src_literals.size(); };
absl::MutexLock l(&mu);
QCHECK(mu.AwaitWithTimeout(absl::Condition(&done), absl::Seconds(60)));
}
}
TEST(GpuTopology, FromProto) {
GpuTopologyProto msg;
ASSERT_TRUE(tsl::protobuf::TextFormat::ParseFromString(
R"pb(
device_ids: [ 3, 2, 1 ]
platform_version: "platform_version"
num_slices: 2
num_hosts_per_slice: 1
num_devices_per_host: 3
)pb",
&msg));
std::unique_ptr<const GpuTopology> gpu_topology = GpuTopology::FromProto(msg);
EXPECT_THAT(gpu_topology->device_ids(), ElementsAre(3, 2, 1));
EXPECT_THAT(gpu_topology->platform_version(), "platform_version");
EXPECT_THAT(gpu_topology->num_slices(), 2);
EXPECT_THAT(gpu_topology->num_hosts_per_slice(), 1);
EXPECT_THAT(gpu_topology->num_devices_per_host(), 3);
}
TEST(GpuTopology, ToProto) {
GpuTopology gpu_topology({3, 2, 1},
"platform_version",
2,
1,
3);
GpuTopologyProto msg = gpu_topology.ToProto();
EXPECT_THAT(msg.device_ids(), ElementsAre(3, 2, 1));
EXPECT_THAT(msg.platform_version(), "platform_version");
EXPECT_THAT(msg.num_slices(), 2);
EXPECT_THAT(msg.num_hosts_per_slice(), 1);
EXPECT_THAT(msg.num_devices_per_host(), 3);
}
TEST(StreamExecutorGpuClientTest, DistributedInit) {
auto kv_store = std::make_shared<InMemoryKeyValueStore>();
tsl::thread::ThreadPool thread_pool(tsl::Env::Default(), "DistributeInit", 4);
int num_nodes = 2;
for (int i = 0; i < num_nodes; i++) {
thread_pool.Schedule([kv_store, i, num_nodes] {
GpuClientOptions options;
options.node_id = i;
options.num_nodes = num_nodes;
options.kv_store = kv_store;
TF_ASSERT_OK_AND_ASSIGN(auto client, GetStreamExecutorGpuClient(options));
EXPECT_TRUE(client->platform_name() == "cuda" ||
client->platform_name() == "rocm");
EXPECT_EQ(client->addressable_device_count(), 2);
EXPECT_EQ(client->device_count(), 4);
});
}
}
TEST(StreamExecutorGpuClientTest, GetAllocatorStatsTest) {
TF_ASSERT_OK_AND_ASSIGN(auto client,
GetStreamExecutorGpuClient(GpuClientOptions()));
ASSERT_GE(client->addressable_devices().size(), 2);
for (auto device : client->addressable_devices()) {
const xla::Literal literal = xla::LiteralUtil::CreateR0<int32_t>(0);
TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<PjRtBuffer> buffer,
client->BufferFromHostLiteral(literal, device));
auto stats = device->GetAllocatorStats();
TF_ASSERT_OK(stats.status());
ASSERT_GT(stats.value().peak_bytes_in_use, 0);
}
}
TEST(StreamExecutorGpuClientTest, GpuDeviceDescriptionTest) {
TF_ASSERT_OK_AND_ASSIGN(auto client,
GetStreamExecutorGpuClient(GpuClientOptions()));
for (int device_index = 0; device_index < client->device_count();
device_index++) {
auto coords =
static_cast<PjRtStreamExecutorDevice*>(client->devices()[device_index])
->description()
.coords();
EXPECT_EQ(coords[0], device_index);
}
EXPECT_EQ(static_cast<PjRtStreamExecutorDevice*>(client->devices()[0])
->description()
.core_on_chip(),
0);
}
TEST(StreamExecutorGpuClientTest, MockNcclClientTest) {
const int num_nodes = 4;
GpuClientOptions options;
options.num_nodes = num_nodes;
options.enable_mock_nccl = true;
TF_ASSERT_OK_AND_ASSIGN(auto client, GetStreamExecutorGpuClient(options));
auto devices_per_host = client->addressable_device_count();
EXPECT_EQ(devices_per_host, 2);
EXPECT_EQ(client->device_count(), devices_per_host * num_nodes);
for (int i = 0; i < client->device_count(); i++) {
auto device = client->devices()[i];
auto slice_index =
std::get<int64_t>(device->Attributes().at("slice_index"));
auto host_index = device->process_index();
EXPECT_EQ(slice_index, host_index);
}
}
namespace {
absl::StatusOr<std::unique_ptr<PjRtBuffer>> CreateDeviceBufferForTest(
xla::PjRtClient* client) {
auto device = client->addressable_devices()[0];
TF_EXPECT_OK(device->default_memory_space());
std::vector<int32_t> data{1, 2, 3, 4};
Shape shape = ShapeUtil::MakeShapeWithDenseLayout(S32, {4}, {0});
TF_ASSIGN_OR_RETURN(
auto input, client->BufferFromHostBuffer(
data.data(), shape.element_type(), shape.dimensions(),
std::nullopt,
PjRtClient::HostBufferSemantics::kImmutableOnlyDuringCall,
nullptr, device));
EXPECT_EQ(input->memory_space()->kind(), "device");
return input;
}
constexpr char const* kD2HProgram = R"(
HloModule f
ENTRY main.5 {
p = s32[4]{0} parameter(0)
ROOT cc = s32[4] custom-call(p),
custom_call_target="annotate_device_placement",
frontend_attributes={_xla_buffer_placement="pinned_host"}
}
)";
constexpr char const* kD2HProgramTupleOutput = R"(
HloModule f
ENTRY main.5 {
p = s32[4]{0} parameter(0)
cc = s32[4] custom-call(p),
custom_call_target="annotate_device_placement",
frontend_attributes={_xla_buffer_placement="pinned_host"}
ROOT tuple = (s32[4]{0}, s32[4]{0}) tuple(s32[4]{0} p, s32[4]{0} cc)
}
)";
}
TEST(StreamExecutorGpuClientTest, ExecutePinnedHostOutputTest) {
TF_ASSERT_OK_AND_ASSIGN(auto client,
GetStreamExecutorGpuClient(GpuClientOptions()));
TF_ASSERT_OK_AND_ASSIGN(auto input, CreateDeviceBufferForTest(client.get()));
TF_ASSERT_OK_AND_ASSIGN(auto executable,
CompileExecutable(kD2HProgram, *client));
TF_ASSERT_OK_AND_ASSIGN(
auto result, executable->Execute({{input.get()}}, ExecuteOptions()));
std::vector<std::unique_ptr<xla::PjRtBuffer>>& result_buffers = result[0];
EXPECT_EQ(result_buffers[0]->memory_space()->kind(), "pinned_host");
TF_ASSERT_OK_AND_ASSIGN(auto memory_stats,
executable->GetCompiledMemoryStats());
EXPECT_EQ(memory_stats.output_size_in_bytes, 0);
EXPECT_EQ(memory_stats.host_output_size_in_bytes, 16);
}
TEST(StreamExecutorGpuClientTest, ExecutePinnedHostOutputTupleTest) {
TF_ASSERT_OK_AND_ASSIGN(auto client,
GetStreamExecutorGpuClient(GpuClientOptions()));
TF_ASSERT_OK_AND_ASSIGN(auto input, CreateDeviceBufferForTest(client.get()));
Shape host_shape = input->on_device_shape();
host_shape.mutable_layout()->set_memory_space(Layout::kHostMemorySpace);
Shape out_shape =
ShapeUtil::MakeTupleShape({input->on_device_shape(), host_shape});
xla::CompileOptions options;
options.executable_build_options.set_result_layout(out_shape);
TF_ASSERT_OK_AND_ASSIGN(
auto executable,
CompileExecutable(kD2HProgramTupleOutput, *client, options));
ExecuteOptions execute_options;
execute_options.untuple_result = true;
TF_ASSERT_OK_AND_ASSIGN(
auto result, executable->Execute({{input.get()}}, execute_options));
std::vector<std::unique_ptr<xla::PjRtBuffer>>& result_buffers = result[0];
EXPECT_EQ(result_buffers.size(), 2);
EXPECT_EQ(result_buffers[0]->memory_space()->kind(), "device");
EXPECT_EQ(result_buffers[1]->memory_space()->kind(), "pinned_host");
}
TEST(StreamExecutorGpuClientTest, ExecutablePinnedHostOutputMemoryKindTest) {
TF_ASSERT_OK_AND_ASSIGN(auto client,
GetStreamExecutorGpuClient(GpuClientOptions()));
TF_ASSERT_OK_AND_ASSIGN(auto executable,
CompileExecutable(kD2HProg | 2,219 |
#ifndef XLA_CLIENT_XLA_BUILDER_H_
#define XLA_CLIENT_XLA_BUILDER_H_
#include <cstdint>
#include <deque>
#include <initializer_list>
#include <map>
#include <memory>
#include <optional>
#include <ostream>
#include <string>
#include <type_traits>
#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/string_view.h"
#include "absl/types/span.h"
#include "xla/array.h"
#include "xla/array2d.h"
#include "xla/array3d.h"
#include "xla/array4d.h"
#include "xla/client/padding.h"
#include "xla/client/xla_computation.h"
#include "xla/comparison_util.h"
#include "xla/hlo/ir/dynamic_parameter_binding.h"
#include "xla/hlo/ir/hlo_input_output_alias_config.h"
#include "xla/hlo/ir/hlo_opcode.h"
#include "xla/layout.h"
#include "xla/literal.h"
#include "xla/literal_util.h"
#include "xla/service/hlo.pb.h"
#include "xla/shape.h"
#include "xla/shape_util.h"
#include "xla/util.h"
#include "xla/xla_data.pb.h"
#include "tsl/lib/core/bitmap.h"
#include "tsl/platform/errors.h"
#include "tsl/platform/stacktrace.h"
namespace xla {
class XlaBuilder;
class XlaOp;
class HloInstruction;
namespace internal {
struct XlaBuilderFriend {
static XlaOp BuildAddDependency(XlaBuilder* builder, XlaOp operand,
XlaOp token, const Shape& shape);
static std::pair<XlaOp, int64_t> BuildAsyncStart(
XlaBuilder* builder, absl::Span<const XlaOp> operands,
std::string execution_thread, const XlaComputation& called_computation,
const Shape& shape);
static XlaOp BuildAsyncUpdate(XlaBuilder* builder, XlaOp operands,
const Shape& shape);
static XlaOp BuildAsyncDone(XlaBuilder* builder, XlaOp operands,
const Shape& shape);
static XlaOp BuildAllGatherStart(
XlaBuilder* builder, XlaOp operand, int64_t all_gather_dimension,
int64_t shard_count, absl::Span<const ReplicaGroup> replica_groups = {},
const std::optional<ChannelHandle>& channel_id = std::nullopt,
const std::optional<Layout>& layout = std::nullopt,
std::optional<bool> use_global_device_ids = std::nullopt);
static XlaOp BuildAllGatherDone(XlaBuilder* builder, XlaOp operands,
const Shape& shape);
static XlaOp BuildAllReduceStart(
XlaBuilder* builder, XlaOp operand, const XlaComputation& computation,
absl::Span<const ReplicaGroup> replica_groups = {},
const std::optional<ChannelHandle>& channel_id = std::nullopt,
const std::optional<Shape>& layout = std::nullopt,
std::optional<bool> use_global_device_ids = std::nullopt);
static XlaOp BuildAllReduceDone(XlaBuilder* builder, XlaOp operands,
const Shape& shape);
static XlaOp BuildCollectivePermuteStart(
XlaBuilder* builder, XlaOp operand,
const std::vector<std::pair<int64_t, int64_t>>& source_target_pairs,
const std::optional<ChannelHandle>& channel_id = std::nullopt);
static XlaOp BuildCollectivePermuteDone(XlaBuilder* builder, XlaOp operands,
const Shape& shape);
static XlaOp BuildCopyStart(
XlaBuilder* builder, XlaOp operand,
std::optional<int> cross_program_prefetch_index = std::nullopt);
static XlaOp BuildCopyDone(XlaBuilder* builder, XlaOp operand,
const Shape& shape);
static XlaOp BuildFusion(
XlaBuilder* builder, absl::Span<const XlaOp> operands,
absl::string_view fusion_kind, const XlaComputation& fused_computation,
absl::Span<const std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>
output_operand_aliasing = {});
static XlaOp BuildBitcast(XlaBuilder* builder, XlaOp operand,
const Shape& shape);
static XlaOp BuildPartitionId(XlaBuilder* builder, const Shape& shape);
static XlaOp BuildSend(XlaBuilder* builder, XlaOp operand, XlaOp token,
const ChannelHandle& handle, bool is_host_transfer);
static XlaOp BuildSendDone(XlaBuilder* builder, XlaOp operand,
const ChannelHandle& handle,
bool is_host_transfer);
static XlaOp BuildRecv(XlaBuilder* builder, XlaOp token, const Shape& shape,
const ChannelHandle& handle, bool is_host_transfer);
static XlaOp BuildRecvDone(XlaBuilder* builder, XlaOp token,
const Shape& shape, const ChannelHandle& handle,
bool is_host_transfer);
static XlaOp BuildDomain(XlaBuilder* builder, XlaOp operand, OpSharding entry,
OpSharding exit, const Shape& shape);
static XlaOp BuildRngGetAndUpdateState(XlaBuilder* builder, int64_t delta,
const Shape& shape);
static HloInstructionProto* GetInstruction(XlaOp op);
static HloInstructionProto* GetInstructionByHandle(XlaBuilder* builder,
int64_t handle);
};
}
class XlaOp {
public:
XlaOp() : handle_(-1), builder_(nullptr) {
static_assert(std::is_trivially_destructible<XlaOp>::value,
"XlaOp should be trivially destructible");
}
~XlaOp() = default;
XlaOp(const XlaOp& other) = default;
XlaOp& operator=(const XlaOp& other) = default;
XlaBuilder* builder() const {
CHECK(builder_ != nullptr);
return builder_;
}
bool valid() const { return handle_ >= 0; }
bool IsUninitialized() const { return builder_ == nullptr; }
bool IsIdenticalTo(XlaOp rhs) const {
return handle_ == rhs.handle_ && builder_ == rhs.builder_;
}
friend std::ostream& operator<<(std::ostream& out, XlaOp op) {
out << op.handle();
return out;
}
private:
explicit XlaOp(XlaBuilder* builder) : handle_(-1), builder_(builder) {}
XlaOp(int64_t handle, XlaBuilder* builder)
: handle_(handle), builder_(builder) {}
int64_t handle() const { return handle_; }
friend class XlaBuilder;
friend class ValueInference;
friend struct internal::XlaBuilderFriend;
int64_t handle_;
XlaBuilder* builder_;
};
XlaOp operator-(XlaOp x);
XlaOp operator+(XlaOp x, XlaOp y);
XlaOp operator-(XlaOp x, XlaOp y);
XlaOp operator*(XlaOp x, XlaOp y);
XlaOp operator/(XlaOp x, XlaOp y);
XlaOp operator%(XlaOp x, XlaOp y);
XlaOp operator~(XlaOp x);
XlaOp operator&(XlaOp x, XlaOp y);
XlaOp operator|(XlaOp x, XlaOp y);
XlaOp operator^(XlaOp x, XlaOp y);
XlaOp operator<<(XlaOp x, XlaOp y);
XlaOp operator>>(XlaOp x, XlaOp y);
class XlaBuilder {
public:
explicit XlaBuilder(const std::string& computation_name);
XlaBuilder(const XlaBuilder&) = delete;
XlaBuilder& operator=(const XlaBuilder&) = delete;
virtual ~XlaBuilder();
const std::string& name() const { return name_; }
void SetOpMetadata(OpMetadata metadata) { metadata_ = std::move(metadata); }
OpMetadata SwapOpMetadata(OpMetadata metadata) {
OpMetadata old_metadata = std::move(metadata_);
metadata_ = std::move(metadata);
return old_metadata;
}
void SetOneShotOpMetadata(OpMetadata metadata) {
one_shot_metadata_ = std::move(metadata);
}
void ClearOpMetadata() { metadata_.Clear(); }
void SetSharding(const OpSharding& sharding) { sharding_ = sharding; }
virtual void SetFrontendAttributes(
const FrontendAttributes& frontend_attributes) {
frontend_attributes_ = frontend_attributes;
}
FrontendAttributes SwapFrontendAttributes(
const FrontendAttributes& frontend_attributes) {
FrontendAttributes old_attributes = std::move(frontend_attributes_);
frontend_attributes_ = frontend_attributes;
return old_attributes;
}
const FrontendAttributes& frontend_attributes() const {
return frontend_attributes_;
}
void ClearFrontendAttributes() { frontend_attributes_.Clear(); }
void ClearSharding() { sharding_ = std::nullopt; }
const std::optional<OpSharding>& sharding() const { return sharding_; }
void set_die_immediately_on_error(bool enabled) {
die_immediately_on_error_ = enabled;
}
static constexpr int64_t kConvBatchDimension = 0;
static constexpr int64_t kConvFeatureDimension = 1;
static constexpr int64_t kConvFirstSpatialDimension = 2;
static constexpr int64_t kConvSecondSpatialDimension = 3;
static constexpr int64_t kConvKernelOutputDimension = 0;
static constexpr int64_t kConvKernelInputDimension = 1;
static constexpr int64_t kConvKernelFirstSpatialDimension = 2;
static constexpr int64_t kConvKernelSecondSpatialDimension = 3;
static ConvolutionDimensionNumbers CreateDefaultConvDimensionNumbers(
int num_spatial_dims = 2);
static absl::Status Validate(const ConvolutionDimensionNumbers& dnum);
std::unique_ptr<XlaBuilder> CreateSubBuilder(
const std::string& computation_name);
absl::StatusOr<XlaComputation> Build(bool remove_dynamic_dimensions = false);
absl::StatusOr<XlaComputation> Build(XlaOp root,
bool remove_dynamic_dimensions = false);
XlaComputation BuildAndNoteError();
absl::StatusOr<XlaComputation> BuildConstantSubGraph(
XlaOp root_op, bool dynamic_dimension_is_minus_one = false);
absl::Status first_error() const { return first_error_; }
absl::Status GetCurrentStatus() const;
absl::StatusOr<Shape> GetShape(XlaOp op) const;
virtual absl::StatusOr<const Shape*> GetShapePtr(XlaOp op) const;
absl::StatusOr<std::optional<OpSharding>> GetOpSharding(XlaOp op) const;
absl::StatusOr<ProgramShape> GetProgramShape() const;
absl::StatusOr<ProgramShape> GetProgramShape(XlaOp root) const;
XlaOp ReportError(const absl::Status& error);
XlaOp ReportErrorOrReturn(const absl::StatusOr<XlaOp>& op);
XlaOp ReportErrorOrReturn(
absl::FunctionRef<absl::StatusOr<XlaOp>()> op_creator);
absl::StatusOr<bool> IsConstant(XlaOp operand) const;
void SetUpAlias(const ShapeIndex& output_index, int64_t param_number,
const ShapeIndex& param_index,
HloInputOutputAliasConfig::AliasKind kind =
HloInputOutputAliasConfig::AliasKind::kMayAlias) {
input_output_aliases_.push_back(
{output_index, param_number, param_index, kind});
}
struct InputOutputAlias {
ShapeIndex output_index;
int64_t param_number;
ShapeIndex param_index;
HloInputOutputAliasConfig::AliasKind kind;
};
void AddBufferDonor(int64_t param_number, const ShapeIndex& param_index) {
buffer_donors_.insert({param_number, param_index});
}
absl::Status SetInstructionFrontendAttribute(XlaOp op, std::string attribute,
std::string value);
absl::Status SetInstructionSharding(
XlaOp op, const std::optional<OpSharding>& sharding);
absl::StatusOr<std::vector<Shape>> GetOperandShapes(
absl::Span<const XlaOp> operands) const;
std::string OpToString(XlaOp op) const;
private:
void ToStringHelper(std::string* out, int ident, int64_t op_handle) const;
absl::StatusOr<XlaComputation> Build(int64_t root_id,
bool remove_dynamic_dimensions);
XlaOp Parameter(int64_t parameter_number, const Shape& shape,
const std::string& name,
const std::vector<bool>& replicated_at_leaf_buffers);
XlaOp Parameter(int64_t parameter_number, const Shape& shape,
const std::string& name) {
std::vector<bool> empty_bools;
return Parameter(parameter_number, shape, name, empty_bools);
}
virtual XlaOp ConstantLiteral(const LiteralSlice& literal);
XlaOp Broadcast(XlaOp operand, absl::Span<const int64_t> broadcast_sizes);
XlaOp BroadcastInDim(XlaOp operand, absl::Span<const int64_t> out_dim_size,
absl::Span<const int64_t> broadcast_dimensions);
XlaOp MhloDynamicBroadcastInDim(
XlaOp operand, XlaOp output_dimensions,
absl::Span<const int64_t> broadcast_dimensions,
const Shape& output_shape);
XlaOp Pad(XlaOp operand, XlaOp padding_value,
const PaddingConfig& padding_config);
XlaOp PadInDim(XlaOp operand, XlaOp padding_value, int64_t dimno,
int64_t pad_lo, int64_t pad_hi);
virtual absl::StatusOr<XlaOp> PadInternal(
const Shape& shape, XlaOp operand, XlaOp padding_value,
const PaddingConfig& padding_config);
XlaOp Reshape(XlaOp operand, absl::Span<const int64_t> dimensions,
absl::Span<const int64_t> new_sizes,
int64_t inferred_dimension = -1);
XlaOp Reshape(XlaOp operand, absl::Span<const int64_t> new_sizes,
int64_t inferred_dimension = -1);
XlaOp Reshape(const Shape& shape, XlaOp operand,
int64_t inferred_dimension = -1);
XlaOp DynamicReshape(XlaOp operand, absl::Span<const XlaOp> dim_sizes,
absl::Span<const int64_t> new_size_bounds,
const std::vector<bool>& dims_are_dynamic);
XlaOp MhloDynamicReshape(XlaOp operand, XlaOp output_shape,
const Shape& shape);
XlaOp Collapse(XlaOp operand, absl::Span<const int64_t> dimensions);
XlaOp Slice(XlaOp operand, absl::Span<const int64_t> start_indices,
absl::Span<const int64_t> limit_indices,
absl::Span<const int64_t> strides);
virtual absl::StatusOr<XlaOp> SliceInternal(
const Shape& shape, XlaOp operand,
absl::Span<const int64_t> start_indices,
absl::Span<const int64_t> limit_indices,
absl::Span<const int64_t> strides);
virtual XlaOp SliceInDim(XlaOp operand, int64_t start_index,
int64_t limit_index, int64_t stride, int64_t dimno);
XlaOp DynamicSlice(XlaOp operand, absl::Span<const XlaOp> start_indices,
absl::Span<const int64_t> slice_sizes);
virtual absl::StatusOr<XlaOp> DynamicSliceInternal(
const Shape& shape, XlaOp operand, absl::Span<const XlaOp> start_indices,
absl::Span<const int64_t> slice_sizes);
XlaOp DynamicUpdateSlice(XlaOp operand, XlaOp update,
absl::Span<const XlaOp> start_indices);
virtual absl::StatusOr<XlaOp> DynamicUpdateSliceInternal(
const Shape& shape, XlaOp operand, XlaOp update,
absl::Span<const XlaOp> start_indices);
XlaOp ConcatInDim(absl::Span<const XlaOp> operands, int64_t dimension);
virtual absl::StatusOr<XlaOp> ConcatInDimInternal(
const Shape& shape, absl::Span<const XlaOp> operands, int64_t dimension);
XlaOp Select(XlaOp pred, XlaOp on_true, XlaOp on_false);
XlaOp Tuple(absl::Span<const XlaOp> elements);
virtual absl::StatusOr<XlaOp> TupleInternal(const Shape& shape,
absl::Span<const XlaOp> elements);
XlaOp GetTupleElement(XlaOp tuple_data, int64_t index);
virtual absl::StatusOr<XlaOp> GetTupleElementInternal(const Shape& shape,
XlaOp tuple_data,
int64_t index);
XlaOp Dot(XlaOp lhs, XlaOp rhs,
const PrecisionConfig* precision_config = nullptr,
std::optional<PrimitiveType> preferred_element_type = std::nullopt);
XlaOp DotGeneral(
XlaOp lhs, XlaOp rhs, const DotDimensionNumbers& dimension_numbers,
const PrecisionConfig* precision_config = nullptr,
std::optional<PrimitiveType> preferred_element_type = std::nullopt);
XlaOp SparseDot(
XlaOp lhs, XlaOp rhs, absl::Span<const XlaOp> sparse_meta,
absl::Span<const SparsityDescriptor> sparsity,
const DotDimensionNumbers& dimension_numbers,
const PrecisionConfig* precision_config = nullptr,
std::optional<PrimitiveType> preferred_element_type = std::nullopt);
XlaOp Conv(
XlaOp lhs, XlaOp rhs, absl::Span<const int64_t> window_strides,
Padding padding, int64_t feature_group_count = 1,
int64_t batch_group_count = 1,
const PrecisionConfig* precision_config = nullptr,
std::optional<PrimitiveType> preferred_element_type = std::nullopt);
XlaOp ConvWithGeneralPadding(
XlaOp lhs, XlaOp rhs, absl::Span<const int64_t> window_strides,
absl::Span<const std::pair<int64_t, int64_t>> padding,
int64_t feature_group_count = 1, int64_t batch_group_count = 1,
const PrecisionConfig* precision_config = nullptr,
std::optional<PrimitiveType> preferred_element_type = std::nullopt);
XlaOp ConvWithGeneralDimensions(
XlaOp lhs, XlaOp rhs, absl::Span<const int64_t> window_strides,
Padding padding, const ConvolutionDimensionNumbers& dimension_numbers,
int64_t feature_group_count = 1, int64_t batch_group_count = 1,
const PrecisionConfig* precision_config = nullptr,
std::optional<PrimitiveType> preferred_element_type = std::nullopt);
XlaOp ConvGeneral(
XlaOp lhs, XlaOp rhs, absl::Span<const int64_t> window_strides,
absl::Span<const std::pair<int64_t, int64_t>> padding,
const ConvolutionDimensionNumbers& dimension_numbers,
int64_t feature_group_count = 1, int64_t batch_group_count = 1,
const PrecisionConfig* precision_config = nullptr,
std::optional<PrimitiveType> preferred_element_type = std::nullopt);
XlaOp ConvGeneralDilated(
XlaOp lhs, XlaOp rhs, absl::Span<const int64_t> window_strides,
absl::Span<const std::pair<int64_t, int64_t>> padding,
absl::Span<const int64_t> lhs_dilation,
absl::Span<const int64_t> rhs_dilation,
const ConvolutionDimensionNumbers& dimension_numbers,
int64_t feature_group_count = 1, int64_t batch_group_count = 1,
const PrecisionConfig* precision_config = nullptr,
std::optional<PrimitiveType> preferred_element_type = std::nullopt,
std::optional<std::vector<bool>> window_reversal = std::nullopt);
XlaOp DynamicConvForward(
XlaOp lhs, XlaOp rhs, absl::Span<const int64_t> window_strides,
absl::Span<const std::pair<int64_t, int64_t>> padding,
absl::Span<const int64_t> lhs_dilation,
absl::Span<const int64_t> rhs_dilation,
const ConvolutionDimensionNumbers& dimension_numbers,
int64_t feature_group_count, int64_t batch_group_count,
const PrecisionConfig* precision_config, PaddingType padding_type,
std::optional<PrimitiveType> preferred_element_type = std::nullopt);
XlaOp DynamicConvInputGrad(
XlaOp input_sizes, XlaOp lhs, XlaOp rhs,
absl::Span<const int64_t> window_strides,
absl::Span<const std::pair<int64_t, int64_t>> padding,
absl::Span<const int64_t> lhs_dilation,
absl::Span<const int64_t> rhs_dilation,
const ConvolutionDimensionNumbers& dimension_numbers,
int64_t feature_group_count, int64_t batch_group_count,
const PrecisionConfig* precision_config, PaddingType padding_type,
std::optional<PrimitiveType> preferred_element_type = std::nullopt);
XlaOp DynamicConvKernelGrad(
XlaOp activations, XlaOp gradients,
absl::Span<const int64_t> window_strides,
absl::Span<const std::pair<int64_t, int64_t>> padding,
absl::Span<const int64_t> lhs_dilation,
absl::Span<const int64_t> rhs_dilation,
const ConvolutionDimensionNumbers& dimension_numbers,
int64_t feature_group_count, int64_t batch_group_count,
const PrecisionConfig* precision_config, PaddingType padding_type,
std::optional<PrimitiveType> preferred_element_type = std::nullopt);
absl::StatusOr<HloInstructionProto> DynamicConvInstruction(
XlaOp lhs, XlaOp rhs, absl::Span<const int64_t> window_strides,
absl::Span<const std::pair<int64_t, int64_t>> padding,
absl::Span<const int64_t> lhs_dilation,
absl::Span<const int64_t> rhs_dilation,
const ConvolutionDimensionNumbers& dimension_numbers,
int64_t feature_group_count, int64_t batch_group_count,
const PrecisionConfig* precision_config, PaddingType padding_type,
std::optional<PrimitiveType> preferred_element_type = std::nullopt);
virtual absl::StatusOr<XlaOp> ConvGeneralDilatedInternal(
const Shape& shape, XlaOp lhs, XlaOp rhs, const Window& window,
absl::Span<const int64_t> window_strides,
absl::Span<const std::pair<int64_t, int64_t>> padding,
absl::Span<const int64_t> lhs_dilation,
absl::Span<const int64_t> rhs_dilation,
const ConvolutionDimensionNumbers& dimension_numbers,
int64_t feature_group_count, int64_t batch_group_count,
const PrecisionConfig* precision_config);
XlaOp Fft(XlaOp operand, FftType fft_type,
absl::Span<const int64_t> fft_length);
virtual absl::StatusOr<XlaOp> FftInternal(
const Shape& shape, XlaOp operand, FftType fft_type,
absl::Span<const int64_t> fft_length);
virtual absl::StatusOr<XlaOp> TriangularSolveInternal(
const Shape& shape, XlaOp a, XlaOp b, TriangularSolveOptions options);
virtual absl::StatusOr<XlaOp> CholeskyInternal(const Shape& shape, XlaOp a,
bool lower);
XlaOp Infeed(const Shape& shape, const std::string& config = "");
XlaOp InfeedWithToken(XlaOp token, const Shape& shape,
const std::string& config);
virtual absl::StatusOr<XlaOp> InfeedWithTokenInternal(
const Shape& infeed_instruction_shape, XlaOp token,
const std::string& config);
void Outfeed(XlaOp operand, const Shape& shape_with_layout,
const std::string& outfeed_config);
XlaOp OutfeedWithToken(XlaOp operand, XlaOp token,
const Shape& shape_with_layout,
const std::string& outfeed_config);
virtual absl::StatusOr<XlaOp> OutfeedWithTokenInternal(
XlaOp operand, XlaOp token, const Shape& shape_with_layout,
const std::string& outfeed_config);
XlaOp Call(const XlaComputation& computation,
absl::Span<const XlaOp> operands);
XlaOp CustomCall(
const std::string& call_target_name, absl::Span<const XlaOp> operands,
const Shape& shape_with_layout, const std::string& opaque,
std::optional<absl::Span<const Shape>> operand_shapes_with_layout,
bool has_side_effect,
absl::Span<const std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>
output_operand_aliasing,
const Literal* literal, std::optional<Window> window,
std::optional<ConvolutionDimensionNumbers> dnums,
CustomCallSchedule schedule, CustomCallApiVersion api_version);
virtual absl::StatusOr<XlaOp> CustomCallInternal(
const std::string& call_target_name, absl::Span<const XlaOp> operands, | #include "xla/client/xla_builder.h"
#include <algorithm>
#include <array>
#include <complex>
#include <cstdint>
#include <functional>
#include <memory>
#include <optional>
#include <string>
#include <utility>
#include <vector>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "absl/algorithm/container.h"
#include "absl/log/check.h"
#include "absl/log/log.h"
#include "absl/status/status.h"
#include "absl/strings/string_view.h"
#include "absl/types/span.h"
#include "xla/client/padding.h"
#include "xla/client/sharding_builder.h"
#include "xla/client/value_inference.h"
#include "xla/client/xla_computation.h"
#include "xla/comparison_util.h"
#include "xla/debug_options_flags.h"
#include "xla/hlo/ir/hlo_casting_utils.h"
#include "xla/hlo/ir/hlo_input_output_alias_config.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/hlo/ir/hlo_sharding.h"
#include "xla/layout_util.h"
#include "xla/service/hlo_parser.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/test.h"
#include "xla/test_helpers.h"
#include "xla/util.h"
#include "xla/xla_data.pb.h"
#include "tsl/platform/status_matchers.h"
#include "tsl/platform/statusor.h"
namespace xla {
namespace {
namespace m = ::xla::match;
using ::testing::_;
using ::testing::HasSubstr;
using ::testing::Test;
using ::tsl::testing::StatusIs;
HloInstruction* GetRoot(HloModule& module) {
return module.entry_computation()->root_instruction();
}
absl::StatusOr<std::unique_ptr<HloModule>> BuildHloModule(XlaBuilder& b) {
TF_ASSIGN_OR_RETURN(XlaComputation computation,
b.Build(false));
const HloModuleProto& proto = computation.proto();
TF_ASSIGN_OR_RETURN(const auto& config,
HloModule::CreateModuleConfigFromProto(
proto, GetDebugOptionsFromFlags()));
return HloModule::CreateFromProto(proto, config);
}
absl::StatusOr<std::unique_ptr<HloModule>> BuildHloModule(XlaBuilder& b,
XlaOp root) {
TF_ASSIGN_OR_RETURN(XlaComputation computation,
b.Build(root, false));
const HloModuleProto& proto = computation.proto();
TF_ASSIGN_OR_RETURN(const auto& config,
HloModule::CreateModuleConfigFromProto(
proto, GetDebugOptionsFromFlags()));
return HloModule::CreateFromProto(proto, config);
}
std::string TestName() {
return ::testing::UnitTest::GetInstance()->current_test_info()->name();
}
TEST(XlaBuilderTest, OnePlusTwo) {
XlaBuilder b(TestName());
Add(ConstantR0<float>(&b, 1.0), ConstantR0<float>(&b, 2.0));
TF_ASSERT_OK_AND_ASSIGN(const auto module, BuildHloModule(b));
auto root = module->entry_computation()->root_instruction();
EXPECT_THAT(root, GmockMatch(m::Add(m::Constant(), m::Constant())));
}
TEST(XlaBuilderTest, UnaryOperatorsBuildExpectedHLO) {
auto test_unary_operator = [&](std::function<XlaOp(XlaOp)> op,
auto matches_pattern) {
XlaBuilder b(TestName());
op(ConstantR0<int32_t>(&b, 1));
TF_ASSERT_OK_AND_ASSIGN(const auto module, BuildHloModule(b));
auto root = module->entry_computation()->root_instruction();
EXPECT_THAT(root, matches_pattern);
};
test_unary_operator([](XlaOp x) { return -x; },
GmockMatch(m::Negate(m::Constant())));
test_unary_operator([](XlaOp x) { return ~x; },
GmockMatch(m::Not(m::Constant())));
}
TEST(XlaBuilderTest, BinaryOperatorsBuildExpectedHLO) {
auto test_binary_operator = [&](std::function<XlaOp(XlaOp, XlaOp)> op,
auto matches_pattern) {
XlaBuilder b(TestName());
op(ConstantR0<int32_t>(&b, 1), ConstantR0<int32_t>(&b, 2));
TF_ASSERT_OK_AND_ASSIGN(const auto module, BuildHloModule(b));
auto root = module->entry_computation()->root_instruction();
EXPECT_THAT(root, matches_pattern);
};
test_binary_operator([](XlaOp x, XlaOp y) { return x + y; },
GmockMatch(m::Add(m::Constant(), m::Constant())));
test_binary_operator([](XlaOp x, XlaOp y) { return x - y; },
GmockMatch(m::Subtract(m::Constant(), m::Constant())));
test_binary_operator([](XlaOp x, XlaOp y) { return x * y; },
GmockMatch(m::Multiply(m::Constant(), m::Constant())));
test_binary_operator([](XlaOp x, XlaOp y) { return x / y; },
GmockMatch(m::Divide(m::Constant(), m::Constant())));
test_binary_operator([](XlaOp x, XlaOp y) { return x & y; },
GmockMatch(m::And(m::Constant(), m::Constant())));
test_binary_operator([](XlaOp x, XlaOp y) { return x | y; },
GmockMatch(m::Or(m::Constant(), m::Constant())));
test_binary_operator([](XlaOp x, XlaOp y) { return x ^ y; },
GmockMatch(m::Xor(m::Constant(), m::Constant())));
test_binary_operator([](XlaOp x, XlaOp y) { return x << y; },
GmockMatch(m::ShiftLeft(m::Constant(), m::Constant())));
test_binary_operator(
[](XlaOp x, XlaOp y) { return x >> y; },
GmockMatch(m::ShiftRightArithmetic(m::Constant(), m::Constant())));
auto test_unsigned_binary_operator =
[&](std::function<XlaOp(XlaOp, XlaOp)> op, auto matches_pattern) {
XlaBuilder b(TestName());
op(ConstantR0<uint32_t>(&b, 1), ConstantR0<uint32_t>(&b, 2));
TF_ASSERT_OK_AND_ASSIGN(const auto module, BuildHloModule(b));
auto root = module->entry_computation()->root_instruction();
EXPECT_THAT(root, matches_pattern);
};
test_unsigned_binary_operator(
[](XlaOp x, XlaOp y) { return x >> y; },
GmockMatch(m::ShiftRightLogical(m::Constant(), m::Constant())));
}
TEST(XlaBuilderTest, VariadicAnd) {
XlaBuilder b(TestName());
const Shape s = ShapeUtil::MakeShape(PRED, {});
And(Parameter(&b, 0, s, "p0"), Parameter(&b, 1, s, "p1"),
Parameter(&b, 2, s, "p2"));
TF_ASSERT_OK_AND_ASSIGN(const auto module, BuildHloModule(b));
EXPECT_THAT(module->entry_computation()->root_instruction(),
::testing::AnyOf(
GmockMatch(m::And(m::Parameter(0),
m::And(m::Parameter(1), m::Parameter(2)))),
GmockMatch(m::And(m::And(m::Parameter(0), m::Parameter(1)),
m::Parameter(2)))));
}
TEST(XlaBuilderTest, VariadicOr) {
XlaBuilder b(TestName());
const Shape s = ShapeUtil::MakeShape(PRED, {});
Or(Parameter(&b, 0, s, "p0"), Parameter(&b, 1, s, "p1"),
Parameter(&b, 2, s, "p2"));
TF_ASSERT_OK_AND_ASSIGN(const auto module, BuildHloModule(b));
EXPECT_THAT(module->entry_computation()->root_instruction(),
::testing::AnyOf(
GmockMatch(m::Or(m::Parameter(0),
m::Or(m::Parameter(1), m::Parameter(2)))),
GmockMatch(m::Or(m::Or(m::Parameter(0), m::Parameter(1)),
m::Parameter(2)))));
}
TEST(XlaBuilderTest, ShiftRightOperatorOnNonIntegerProducesError) {
XlaBuilder b(TestName());
ConstantR0<float>(&b, 1) >> ConstantR0<float>(&b, 2);
auto statusor = b.Build();
ASSERT_FALSE(statusor.ok());
EXPECT_THAT(
statusor.status().message(),
HasSubstr("Argument to >> operator does not have an integral type"));
}
TEST(XlaBuilderTest, ParamPlusConstantHasScalarBroadcast) {
XlaBuilder b(TestName());
auto x = Parameter(&b, 0, ShapeUtil::MakeShape(F32, {3, 5}), "x");
Add(x, ConstantR0<float>(&b, 1.0));
TF_ASSERT_OK_AND_ASSIGN(const auto module, BuildHloModule(b));
auto root = module->entry_computation()->root_instruction();
EXPECT_THAT(root,
GmockMatch(m::Add(m::Parameter(), m::Broadcast(m::Constant()))));
}
TEST(XlaBuilderTest, ParamPlusConstantHasScalarBroadcastReversed) {
XlaBuilder b(TestName());
const XlaOp x = Parameter(&b, 0, ShapeUtil::MakeShape(F32, {3, 5}), "x");
Add(ConstantR0<float>(&b, 1.0), x);
TF_ASSERT_OK_AND_ASSIGN(const auto module, BuildHloModule(b));
HloInstruction* root = module->entry_computation()->root_instruction();
EXPECT_THAT(root,
GmockMatch(m::Add(m::Broadcast(m::Constant()), m::Parameter())));
}
TEST(XlaBuilderTest, ParamPlusParamHasBroadcast) {
XlaBuilder b(TestName());
const auto& x_shape = ShapeUtil::MakeShape(S32, {2, 4, 6});
const auto& y_shape = ShapeUtil::MakeShape(S32, {2, 4});
auto x = Parameter(&b, 0, x_shape, "x");
auto y = Parameter(&b, 1, y_shape, "y");
auto add = Add(x, y, {0, 1});
TF_ASSERT_OK_AND_ASSIGN(const auto add_shape, b.GetShape(add));
EXPECT_TRUE(ShapeUtil::Equal(add_shape, x_shape));
TF_ASSERT_OK_AND_ASSIGN(const auto module, BuildHloModule(b));
auto root = module->entry_computation()->root_instruction();
EXPECT_THAT(
root, GmockMatch(m::Add(m::Parameter(0), m::Broadcast(m::Parameter(1)))));
}
TEST(XlaBuilderTest, XPlusX) {
XlaBuilder b(TestName());
auto x = Parameter(&b, 0, ShapeUtil::MakeShape(S32, {1, 3, 5, 7}), "x");
Add(x, x);
TF_ASSERT_OK_AND_ASSIGN(const auto module, BuildHloModule(b));
auto root = module->entry_computation()->root_instruction();
EXPECT_THAT(root, GmockMatch(m::Add(m::Parameter(0), m::Parameter(0))));
}
TEST(XlaBuilderTest, TestBinaryOpImplicitBroadcast) {
XlaBuilder b(TestName());
TF_ASSERT_OK_AND_ASSIGN(const Shape lhs, ParseShape("f32[1]"));
TF_ASSERT_OK_AND_ASSIGN(const Shape rhs, ParseShape("f32[2, 2]"));
TF_ASSERT_OK_AND_ASSIGN(const Shape expected, ParseShape("f32[2,2]"));
Add(Parameter(&b, 0, lhs, "lhs"), Parameter(&b, 1, rhs, "rhs"),
{1});
TF_ASSERT_OK_AND_ASSIGN(const auto module, BuildHloModule(b));
EXPECT_THAT(GetRoot(*module),
GmockMatch(m::Op().WithShapeEqualTo(&expected)));
}
TEST(XlaBuilderTest, TestBinaryOpImplicitBroadcastBounded) {
XlaBuilder b(TestName());
TF_ASSERT_OK_AND_ASSIGN(const Shape lhs, ParseShape("f32[1]"));
TF_ASSERT_OK_AND_ASSIGN(const Shape rhs, ParseShape("f32[<=2, <=2]"));
TF_ASSERT_OK_AND_ASSIGN(const Shape expected, ParseShape("f32[<=2, <=2]"));
Add(Parameter(&b, 0, lhs, "lhs"), Parameter(&b, 1, rhs, "rhs"),
{1});
TF_ASSERT_OK_AND_ASSIGN(const auto module, BuildHloModule(b));
EXPECT_THAT(GetRoot(*module),
GmockMatch(m::Op().WithShapeEqualTo(&expected)));
}
TEST(XlaBuilderTest, ShapeInferenceError) {
XlaBuilder b(TestName());
auto x = Parameter(&b, 0, ShapeUtil::MakeShape(U32, {2, 4, 6}), "x");
auto y = Parameter(&b, 1, ShapeUtil::MakeShape(U32, {2, 4}), "y");
Add(x, y);
auto statusor = BuildHloModule(b);
ASSERT_FALSE(statusor.ok());
EXPECT_THAT(statusor.status().message(),
HasSubstr("Shapes must be equal rank"));
}
TEST(XlaBuilderTest, DynamicDimensionReshapeToR0) {
XlaBuilder b(TestName());
auto x = Parameter(&b, 0, ShapeUtil::MakeShape(F32, {1}), "x");
auto y = Parameter(&b, 1, ShapeUtil::MakeShape(S32, {}), "dyn_dim");
auto dx = SetDimensionSize(x, y, 0);
Reshape(dx, {});
auto statusor = BuildHloModule(b);
ASSERT_TRUE(statusor.ok());
}
TEST(XlaBuilderTest, ParameterAlreadyRegistered) {
XlaBuilder b_call("add");
Parameter(&b_call, 0, ShapeUtil::MakeShape(PRED, {}), "x");
XlaBuilder b(TestName());
auto x = Parameter(&b, 0, ShapeUtil::MakeShape(PRED, {}), "x");
auto y = Parameter(&b, 0, ShapeUtil::MakeShape(PRED, {}), "y");
Add(x, y);
auto statusor = BuildHloModule(b);
ASSERT_FALSE(statusor.ok());
EXPECT_THAT(statusor.status().message(),
HasSubstr("parameter 0 already registered"));
}
TEST(XlaBuilderTest, Call) {
XlaBuilder b_call("the_only_to_apply");
auto p0 = Parameter(&b_call, 0, ShapeUtil::MakeShape(F32, {}), "p0");
auto p1 = Parameter(&b_call, 1, ShapeUtil::MakeShape(F32, {}), "p1");
Add(p0, p1);
TF_ASSERT_OK_AND_ASSIGN(const auto call, b_call.Build());
XlaBuilder b(TestName());
auto x = Parameter(&b, 0, ShapeUtil::MakeShape(F32, {}), "x");
auto y = Parameter(&b, 1, ShapeUtil::MakeShape(F32, {}), "y");
auto one = ConstantR0<float>(&b, 1);
auto two = ConstantR0<float>(&b, 2);
Add(Call(&b, call, {x, y}), Call(&b, call, {one, two}));
TF_ASSERT_OK_AND_ASSIGN(const auto module, BuildHloModule(b));
auto root = module->entry_computation()->root_instruction();
EXPECT_THAT(root, GmockMatch(m::Add(m::Call(m::Parameter(), m::Parameter()),
m::Call(m::Constant(), m::Constant()))));
}
TEST(XlaBuilderTest, BinopHasDegenerateBroadcast) {
XlaBuilder b(TestName());
auto x = Parameter(&b, 0, ShapeUtil::MakeShape(F32, {1, 2, 3}), "x");
auto y = Parameter(&b, 1, ShapeUtil::MakeShape(F32, {1, 2, 1}), "y");
Add(x, y);
TF_ASSERT_OK_AND_ASSIGN(const auto module, BuildHloModule(b));
auto root = module->entry_computation()->root_instruction();
EXPECT_THAT(root,
GmockMatch(m::Add(m::Parameter(0),
m::Broadcast(m::Reshape(m::Parameter(1))))));
}
TEST(XlaBuilderTest, BinopHasInDimAndDegenerateBroadcast) {
XlaBuilder b(TestName());
auto x = Parameter(&b, 0, ShapeUtil::MakeShape(F32, {2, 3}), "x");
auto y = Parameter(&b, 1, ShapeUtil::MakeShape(F32, {2, 1, 4}), "y");
Add(x, y, {0, 1});
TF_ASSERT_OK_AND_ASSIGN(const auto module, BuildHloModule(b));
auto root = module->entry_computation()->root_instruction();
EXPECT_THAT(root,
GmockMatch(m::Add(m::Broadcast(m::Parameter(0)),
m::Broadcast(m::Reshape(m::Parameter(1))))));
}
TEST(XlaBuilderTest, BroadcastInDim) {
XlaBuilder b(TestName());
auto x = Parameter(&b, 0, ShapeUtil::MakeShape(F32, {2, 3}), "x");
BroadcastInDim(x, {2, 4, 3},
{0, 2});
TF_ASSERT_OK_AND_ASSIGN(const auto module, BuildHloModule(b));
auto root = module->entry_computation()->root_instruction();
EXPECT_THAT(root, GmockMatch(m::Broadcast()));
}
TEST(XlaBuilderTest, BroadcastInDimWithDegeneratedDim) {
XlaBuilder b(TestName());
auto x = Parameter(&b, 0, ShapeUtil::MakeShape(F32, {2, 1, 4}), "x");
BroadcastInDim(x, {2, 3, 4},
{0, 1, 2});
TF_ASSERT_OK_AND_ASSIGN(const auto module, BuildHloModule(b));
EXPECT_THAT(module->entry_computation()->root_instruction(),
GmockMatch(m::Broadcast(m::Reshape(m::Broadcast()))));
}
TEST(XlaBuilderTest, BroadcastInDimWithNegativeSize) {
XlaBuilder b(TestName());
auto x = Parameter(&b, 0, ShapeUtil::MakeShape(F32, {2, 1, 4}), "x");
BroadcastInDim(x, {-3, 3, 4},
{0, 1, 2});
auto statusor = BuildHloModule(b);
ASSERT_FALSE(statusor.ok());
EXPECT_THAT(statusor.status().message(), HasSubstr("invalid shape"));
}
TEST(XlaBuilderTest, OperandFromWrongBuilder) {
XlaBuilder b1("b1");
auto p0 = Parameter(&b1, 0, ShapeUtil::MakeShape(F32, {}), "p0");
XlaBuilder builder("main");
auto p = Parameter(&builder, 0, ShapeUtil::MakeShape(F32, {}), "p");
Add(p, p0);
auto statusor = builder.Build();
ASSERT_FALSE(statusor.ok());
EXPECT_THAT(
statusor.status().message(),
HasSubstr(
"built by builder 'b1', but is trying to use it in builder 'main'"));
}
TEST(XlaBuilderTest, ReshapeDefaultOrder) {
XlaBuilder b(TestName());
auto x = Parameter(&b, 0, ShapeUtil::MakeShape(F32, {2, 3, 5, 7}), "x");
Reshape(x, {6, 35});
TF_ASSERT_OK_AND_ASSIGN(const auto module, BuildHloModule(b));
auto root = module->entry_computation()->root_instruction();
EXPECT_THAT(root, GmockMatch(m::Reshape(m::Parameter())));
}
TEST(XlaBuilderTest, ReshapeHasTranspose) {
XlaBuilder b(TestName());
auto x = Parameter(&b, 0, ShapeUtil::MakeShape(F32, {2, 3, 5, 7}), "x");
Reshape(x, {3, 2, 1, 0}, {6, 35});
TF_ASSERT_OK_AND_ASSIGN(const auto module, BuildHloModule(b));
auto root = module->entry_computation()->root_instruction();
EXPECT_THAT(root, GmockMatch(m::Reshape(m::Transpose(m::Parameter()))));
}
TEST(XlaBuilderTest, Transpose) {
XlaBuilder b(TestName());
auto x = Parameter(&b, 0, ShapeUtil::MakeShape(F32, {5, 7}), "x");
Transpose(x, {1, 0});
TF_ASSERT_OK_AND_ASSIGN(const auto module, BuildHloModule(b));
auto root = module->entry_computation()->root_instruction();
EXPECT_THAT(root, GmockMatch(m::Transpose(m::Parameter())));
}
TEST(XlaBuilderTest, AllGatherR1) {
XlaBuilder b(TestName());
auto x = Parameter(&b, 0, ShapeUtil::MakeShape(F32, {4}), "x");
AllGather(x, 0, 4);
TF_ASSERT_OK_AND_ASSIGN(const auto module, BuildHloModule(b));
auto root = module->entry_computation()->root_instruction();
EXPECT_EQ(root->opcode(), HloOpcode::kAllGather);
EXPECT_TRUE(ShapeUtil::Equal(root->shape(), ShapeUtil::MakeShape(F32, {16})));
}
TEST(XlaBuilderTest, AllGatherR2) {
XlaBuilder b(TestName());
auto x = Parameter(&b, 0, ShapeUtil::MakeShape(F32, {4, 16}), "x");
AllGather(x, 1, 4);
TF_ASSERT_OK_AND_ASSIGN(const auto module, BuildHloModule(b));
auto root = module->entry_computation()->root_instruction();
EXPECT_EQ(root->opcode(), HloOpcode::kAllGather);
EXPECT_TRUE(
ShapeUtil::Equal(root->shape(), ShapeUtil::MakeShape(F32, {4, 64})));
}
TEST(XlaBuilderTest, AllGatherWithTuple) {
XlaBuilder b(TestName());
auto x = Parameter(&b, 0, ShapeUtil::MakeShape(F32, {4}), "x");
auto x2 = Parameter(&b, 1, ShapeUtil::MakeShape(F32, {16, 4}), "x2");
AllGather(Tuple(&b, {x, x2}), 0,
4);
TF_ASSERT_OK_AND_ASSIGN(const auto module, BuildHloModule(b));
auto root = module->entry_computation()->root_instruction();
EXPECT_EQ(root->opcode(), HloOpcode::kAllGather);
EXPECT_TRUE(ShapeUtil::Equal(
root->shape(),
ShapeUtil::MakeTupleShape({ShapeUtil::MakeShape(F32, {16}),
ShapeUtil::MakeShape(F32, {64, 4})})));
}
TEST(XlaBuilderTest, AllGatherTuple) {
XlaBuilder b(TestName());
auto p0 = Parameter(&b, 0, ShapeUtil::MakeShape(F32, {128, 4}), "p0");
auto p1 = Parameter(&b, 1, ShapeUtil::MakeShape(F32, {128, 8}), "p1");
AllGatherTuple({p0, p1}, 1, 4);
TF_ASSERT_OK_AND_ASSIGN(const auto module, BuildHloModule(b));
auto root = module->entry_computation()->root_instruction();
auto tuple_shape =
ShapeUtil::MakeTupleShape({ShapeUtil::MakeShape(F32, {128, 16}),
ShapeUtil::MakeShape(F32, {128, 32})});
EXPECT_THAT(root, GmockMatch(m::Op()
.WithOpcode(HloOpcode::kAllGather)
.WithShapeEqualTo(&tuple_shape)));
}
TEST(XlaBuilderTest, ReduceScatter) {
XlaBuilder b(TestName());
XlaComputation to_apply;
{
auto sub_builder = b.CreateSubBuilder("add");
auto arg0 =
Parameter(sub_builder.get(), 0, ShapeUtil::MakeScalarShape(F32), "x");
auto arg1 =
Parameter(sub_builder.get(), 1, ShapeUtil::MakeScalarShape(F32), "y");
Add(arg0, arg1);
TF_ASSERT_OK_AND_ASSIGN(to_apply, sub_builder->Build());
}
auto x = Parameter(&b, 0, ShapeUtil::MakeShape(F32, {4, 16}), "x");
ReplicaGroup group;
group.add_replica_ids(0);
group.add_replica_ids(1);
ReduceScatter(x, to_apply, 1, 2,
{group});
TF_ASSERT_OK_AND_ASSIGN(const auto module, BuildHloModule(b));
auto root = module->entry_computation()->root_instruction();
EXPECT_EQ(root->opcode(), HloOpcode::kReduceScatter);
EXPECT_TRUE(
ShapeUtil::Equal(root->shape(), ShapeUtil::MakeShape(F32, {4, 8})));
}
TEST(XlaBuilderTest, ReduceScatterWithTuple) {
XlaBuilder b(TestName());
XlaComputation to_apply;
{
auto sub_builder = b.CreateSubBuilder("add");
auto arg0 =
Parameter(sub_builder.get(), 0, ShapeUtil::MakeScalarShape(F32), "x");
auto arg1 =
Parameter(sub_builder.get(), 1, ShapeUtil::MakeScalarShape(F32), "y");
Add(arg0, arg1);
TF_ASSERT_OK_AND_ASSIGN(to_apply, sub_builder->Build());
}
auto x = Parameter(&b, 0, ShapeUtil::MakeShape(F32, {4, 16}), "x");
auto x2 = Parameter(&b, 1, ShapeUtil::MakeShape(F32, {16, 4}), "x2");
ReplicaGroup group;
group.add_replica_ids(0);
group.add_replica_ids(1);
ReduceScatter(Tuple(&b, {x, x2}), to_apply, 1,
2,
{group});
TF_ASSERT_OK_AND_ASSIGN(const auto module, BuildHloModule(b));
auto root = module->entry_computation()->root_instruction();
EXPECT_EQ(root->opcode(), HloOpcode::kReduceScatter);
EXPECT_TRUE(ShapeUtil::Equal(
root->shape(),
ShapeUtil::MakeTupleShape({ShapeUtil::MakeShape(F32, {4, 8}),
ShapeUtil::MakeShape(F32, {16, 2})})));
}
TEST(XlaBuilderTest, AllToAll) {
XlaBuilder b(TestName());
auto x = Parameter(&b, 0, ShapeUtil::MakeShape(F32, {4, 16}), "x");
AllToAll(x, 1, 0,
2);
TF_ASSERT_OK_AND_ASSIGN(const auto module, BuildHloModule(b));
auto root = module->entry_computation()->root_instruction();
EXPECT_EQ(root->opcode(), HloOpcode::kReshape);
EXPECT_EQ(root->operand(0)->operand(0)->operand(0)->opcode(),
HloOpcode::kAllToAll);
EXPECT_TRUE(
ShapeUtil::Equal(root->shape(), ShapeUtil::MakeShape(F32, {8, 8})));
}
TEST(XlaBuilderTest, AllToAllSpecial) {
XlaBuilder b(TestName());
auto x = Parameter(&b, 0, ShapeUtil::MakeShape(F32, {4, 16, 8}), "x");
AllToAll(x, 0, 0,
2);
TF_ASSERT_OK_AND_ASSIGN(const auto module, BuildHloModule(b));
auto root = module->entry_computation()->root_instruction();
EXPECT_EQ(root->opcode(), HloOpcode::kAllToAll);
EXPECT_TRUE(
ShapeUtil::Equal(root->shape(), ShapeUtil::MakeShape(F32, {4, 16, 8})));
}
TEST(XlaBuilderTest, AllToAllTuple) {
XlaBuilder b(TestName());
auto p0 = Parameter(&b, 0, ShapeUtil::MakeShape(F32, {2, 4}), "p0");
auto p1 = Parameter(&b, 1, ShapeUtil::MakeShape(F32, {2, 4}), "p1");
ReplicaGroup replica_group;
replica_group.add_replica_ids(0);
replica_group.add_replica_ids(1);
AllToAllTuple({p0, p1}, {replica_group}, LayoutUtil::MakeAscendingLayout(2));
TF_ASSERT_OK_AND_ASSIGN(const auto module, BuildHloModule(b));
auto root = module->entry_computation()->root_instruction();
auto expected_shape =
ShapeUtil::MakeShapeWithDenseLayout(F32, {2, 4},
{0, 1});
auto tuple_shape =
ShapeUtil::MakeTupleShape({expected_shape, expected_shape});
auto is_replica_group_pred = [](const HloInstruction* instr) {
return instr->replica_groups().size() == 1 &&
absl::c_equal(instr->replica_groups()[0].replica_ids(),
std::vector<int64_t>{0, 1});
};
EXPECT_THAT(root, GmockMatch(m::Op()
.WithOpcode(HloOpcode::kAllToAll)
.WithShapeEqualTo(&tuple_shape)
.WithPredicate(is_replica_group_pred)));
}
TEST(XlaBuilderTest, AllReduceTuple) {
XlaBuilder b(TestName());
auto shape0 = ShapeUtil::MakeShape(F32, {});
auto shape1 = ShapeUtil::MakeShape(F32, {1, 2});
auto p0 = Parameter(&b, 0, shape0, "p0");
auto p1 = Parameter(&b, 1, shape1, "p1");
XlaBuilder bsum(TestName());
auto f32Scalar = ShapeUtil::MakeShape(F32, {});
Add(Parameter(&bsum, 0, f32Scalar, "x"), Parameter(&bsum, 1, f32Scalar, "y"));
TF_ASSERT_OK_AND_ASSIGN(const auto sum, bsum.Build());
AllReduceTuple({p0, p1}, sum);
TF_ASSERT_OK_AND_ASSIGN(const auto module, BuildHloModule(b));
auto root = module->entry_computation()->root_instruction();
auto tuple_shape = ShapeUtil::MakeTupleShape({shape0, shape1});
EXPECT_THAT(root, GmockMatch(m::Op()
.WithOpcode(HloOpcode::kAllReduce)
.WithShapeEqualTo(&tuple_shape)));
}
TEST(XlaBuilderTest, CollectiveBroadcast) {
XlaBuilder b(TestName());
auto x = Parameter(&b, 0, ShapeUtil::MakeShape(F32, {5, 7}), "x");
ReplicaGroup replica_group;
replica_group.add_replica_ids(0);
replica_group.add_replica_ids(1);
CollectiveBroadcast(x, {replica_group});
TF_ASSERT_OK_AND_ASSIGN(const auto module, BuildHloModule(b));
auto root = module->entry_computation()->root_instruction();
EXPECT_EQ(root->opcode(), HloOpcode::kCollectiveBroadcast);
}
TEST(XlaBuilderTest, CollectivePermute) {
XlaBuilder b(TestName());
auto x = Parameter(&b, 0, ShapeUtil::MakeShape(F32, {5, 7}), "x");
CollectivePermute(x, {{0, 1}, {1, 2}, {2, 3}});
TF_ASSERT_OK_AND_ASSIGN(const auto module, BuildHloModule(b));
auto root = module->entry_computation()->root_instruction();
EXPECT_EQ(root->opcode(), HloOpcode::kCollectivePermute);
}
TEST(XlaBuilderTest, GetDimensionSize) {
XlaBuilder b(TestName());
auto x =
Parameter(&b, 0, ShapeUtil::MakeShape(F32, {5, 7}, {false, true}), "x");
GetDimensionSize(x, 1);
TF_ASSERT_OK_AND_ASSIGN(const auto module, BuildHloModule(b));
auto root = module->entry_computation()->root_instruction();
EXPECT_EQ(root->opcode(), HloOpcode::kGetDimensionSize);
}
TEST(XlaBuilderTest, GetDimensionSizeConstant) {
XlaBuilder b(TestName());
auto x =
Parameter(&b, 0, ShapeUtil::MakeShape(F32, {5, 7}, {false, true}), "x");
GetDimensionSize(x, 0);
TF_ASSERT_OK_AND_ASSIGN(const auto module, BuildHloModule(b));
auto root = module->entry_computation()->root_instruction();
EXPECT_EQ(root->opcode(), HloOpcode::kConstant);
}
TEST(XlaBuilderTest, ReportError) {
XlaBuilder b(TestName());
auto x = Parameter(&b, 0, ShapeUtil::MakeShape(F32, {5, 7}), "x");
Add(b.ReportError(InvalidArgument("a test error")), x);
auto statusor = b.Build();
ASSERT_FALSE(statusor.ok());
EXPECT_THAT(statusor.status().message(), HasSubstr("a test error"));
}
TEST(XlaBuilderTest, ReportErrorOrReturnHandlesNonErrors) {
XlaBuilder b(TestName());
absl::StatusOr<XlaOp> op(ConstantR0<float>(&b, 1.0));
Add(b.ReportErrorOrReturn(op), ConstantR0<float>(&b, 2.0));
TF_ASSERT_OK_AND_ASSIGN(const auto module, BuildHloModule(b));
auto root = module->entry_computation()->root_instruction();
EXPECT_THAT(root, GmockMatch(m::Add(m::Constant(), m::Constant())));
}
TEST(XlaBuilderTest, ReportErrorOrReturnHandlesErrors) {
XlaBuilder b(TestName());
absl::StatusOr<XlaOp> op(InvalidArgument("a test error"));
Add(b.ReportErrorOrReturn(op), ConstantR0<float>(&b, 2.0));
auto statusor = b.Build();
ASSERT_FALSE(statusor.ok());
EXPECT_THAT(statusor.status().message(), HasSubstr("a test error"));
}
TEST(XlaBuilderTest, BuildWithSpecificRoot) {
XlaBuilder b(TestName());
const XlaOp constant = ConstantR0<float>(&b, 1.0);
Add(constant, ConstantR0<float>(&b, 2.0));
TF_ASSERT_OK_AND_ASSIGN(const auto module,
BuildHloModule(b, constant));
auto root = module->entry_computation()->root_instruction();
EXPECT_THAT(root, GmockMatch(m::Constant()));
}
TEST(XlaBuilderTest, BuildWithSpecificRootAndMultipleParameters) {
XlaBuilder b(TestName());
const Shape shape = ShapeUtil::MakeShape(F32, {42, 123});
const XlaOp x = Parameter(&b, 0, shape, "x");
const XlaOp y = Parameter(&b, 1, shape, "y");
const XlaOp z = Parameter(&b, 2, shape, "z");
Add(x, Sub(y, z));
TF_ASSERT_OK_AND_ASSIGN(const auto module, BuildHloModule(b, x));
auto root = module->entry_computation()->root_instruction();
EXPECT_THAT(root, GmockMatch(m::Parameter()));
EXPECT_EQ(module->entry_computation()->num_parameters(), 3);
EXPECT_EQ(module->entry_computation()->instruction_count(), 5);
}
TEST(XlaBuilderTest, BuildWithSpecificRootWithWrongBuilder) {
XlaBuilder b(TestName());
XlaBuilder other_b(TestName());
const Shape shape = ShapeUtil::MakeShape(F32, {42, 123});
Parameter(&b, 0, shape, "param");
const XlaOp other_param = Parameter(&other_b, 0, shape, "other_param");
absl::Status status = b.Build(other_param).status();
ASSERT_IS_NOT_OK(status);
EXPECT_THAT(
status.message(),
::testing::HasSubstr("root operation is not in this computation"));
}
TEST(XlaBuilderTest, ProtoMatches) {
std::vector<XlaComputation> computations;
const int n = 2;
computations.reserve(n);
for (int i = 0; i < n; ++i) {
XlaBuilder b_call("the_only_to_apply");
auto p0 = Parameter(&b_call, 0, ShapeUtil::MakeShape(F32, {}), "p0");
auto p1 = Parameter(&b_call, 1, ShapeUtil::MakeShape(F32, {}), "p1");
Add(p0, Add(p1, p0));
TF_ASSERT_OK_AND_ASSIGN(const auto call, b_call.Build());
XlaBuilder b(TestName());
auto x = Parameter(&b, 0, ShapeUtil::MakeShape(F32, {}), "x");
auto y = Parameter(&b, 1, ShapeUtil::MakeShape(F32, {}), "y");
auto one = ConstantR0<float>(&b, 1);
auto two = ConstantR0<float>(&b, 2);
Add(Call(&b, call, {x, y}), Call(&b, call, {one, two}));
computations.push_back(b.Build().value());
}
auto c0_string = computations[0].proto().SerializeAsString();
auto c1_string = computations[1].proto().SerializeAsString();
EXPECT_EQ(c0_string, c1_string);
}
TEST(XlaBuilderTest, DynamicParameter) {
XlaBuilder b(TestName());
const Shape tuple_param_shape = ShapeUtil::MakeTupleShape(
{ShapeUtil::MakeShape(F32, {5}), ShapeUtil::MakeShape(F32, {6}, {true})});
auto p0 = Parameter(&b, 0, tuple_param_shape, "p0");
Parameter(&b, 1, ShapeUtil::MakeShape(U32, {}), "p1");
TF_ASSERT_OK_AND_ASSIGN(const auto module, BuildHloModule(b, p0));
const Shape& param_shape = module->entry_computation()
->parameter_instruction(0)
->shape()
.tuple_shapes(1);
EXPECT_TRUE(param_shape.is_dynamic_dimension(0));
}
TEST(XlaBuilderTest, SetDimensionSize) {
XlaBuilder b(TestName());
auto p0 = Parame | 2,220 |
#ifndef XLA_CLIENT_VALUE_INFERENCE_H_
#define XLA_CLIENT_VALUE_INFERENCE_H_
#include <optional>
#include <utility>
#include "absl/container/flat_hash_map.h"
#include "xla/client/xla_builder.h"
#include "xla/hlo/evaluator/hlo_evaluator.h"
#include "xla/hlo/ir/dfs_hlo_visitor.h"
#include "xla/hlo/ir/hlo_computation.h"
#include "xla/hlo/ir/hlo_opcode.h"
#include "xla/literal.h"
#include "xla/literal_util.h"
#include "xla/util.h"
#include "xla/xla_data.pb.h"
namespace xla {
class OptionalLiteral {
public:
explicit OptionalLiteral(Literal value, Literal mask)
: value_(std::move(value)), mask_(std::move(mask)) {}
template <typename NativeT>
std::optional<NativeT> Get(absl::Span<const int64_t> element_index,
ShapeIndex shape_index = {}) const {
if (mask_.Get<bool>(element_index, shape_index)) {
return std::nullopt;
} else {
return value_.Get<NativeT>(element_index, shape_index);
}
}
bool AllValid() { return mask_.IsAll(0); }
std::optional<LiteralSlice> GetValue() {
if (!AllValid()) {
return std::nullopt;
}
return LiteralSlice(value_);
}
private:
Literal value_;
Literal mask_;
};
enum ValueInferenceMode {
kValue = 0,
kUpperBound,
kLowerBound,
};
class ValueInference {
public:
explicit ValueInference(XlaBuilder* builder) : builder_(builder) {
CHECK(builder_);
}
absl::StatusOr<Literal> AnalyzeIsDynamic(XlaOp op);
absl::StatusOr<OptionalLiteral> AnalyzeConstant(XlaOp op,
ValueInferenceMode mode);
XlaBuilder* builder() { return builder_; }
private:
absl::StatusOr<Literal> SimplifyOp(int64_t handle);
absl::StatusOr<std::optional<int64_t>> CseOpHandle(int64_t handle);
XlaBuilder* builder_;
HloEvaluator evaluator_;
absl::flat_hash_map<int64_t, int64_t> cse_map_;
};
}
#endif
#include "xla/client/value_inference.h"
#include <functional>
#include <memory>
#include <optional>
#include <string>
#include <utility>
#include <vector>
#include "absl/container/flat_hash_map.h"
#include "absl/status/statusor.h"
#include "absl/strings/str_format.h"
#include "absl/types/span.h"
#include "xla/comparison_util.h"
#include "xla/hlo/ir/dfs_hlo_visitor.h"
#include "xla/hlo/ir/hlo_computation.h"
#include "xla/hlo/ir/hlo_opcode.h"
#include "xla/literal.h"
#include "xla/literal_util.h"
#include "xla/primitive_util.h"
#include "xla/service/hlo.pb.h"
#include "xla/shape_util.h"
#include "xla/status_macros.h"
#include "xla/util.h"
#include "xla/xla_data.pb.h"
#include "tsl/platform/errors.h"
#include "tsl/platform/statusor.h"
namespace xla {
namespace {
Literal CreatePredLiteral(bool pred, const Shape& reference_shape) {
if (reference_shape.IsTuple()) {
std::vector<Literal> sub_literals;
const auto& reference_shape_tuple_shapes = reference_shape.tuple_shapes();
sub_literals.reserve(reference_shape_tuple_shapes.size());
for (const Shape& shape : reference_shape_tuple_shapes) {
sub_literals.emplace_back(CreatePredLiteral(pred, shape));
}
return Literal::MoveIntoTuple(absl::MakeSpan(sub_literals));
}
PrimitiveType element_type = reference_shape.element_type();
if (element_type == TOKEN) {
return LiteralUtil::CreateR0(pred);
}
Literal literal = LiteralUtil::CreateR0(pred);
Literal literal_broadcast =
literal.Broadcast(ShapeUtil::ChangeElementType(reference_shape, PRED), {})
.value();
return literal_broadcast;
}
Literal CreateS64Literal(int64_t value, const Shape& reference_shape) {
if (reference_shape.IsTuple()) {
std::vector<Literal> sub_literals;
const auto& reference_shape_tuple_shapes = reference_shape.tuple_shapes();
sub_literals.reserve(reference_shape_tuple_shapes.size());
for (const Shape& shape : reference_shape_tuple_shapes) {
sub_literals.emplace_back(CreateS64Literal(value, shape));
}
return Literal::MoveIntoTuple(absl::MakeSpan(sub_literals));
}
PrimitiveType element_type = reference_shape.element_type();
if (element_type == TOKEN) {
return LiteralUtil::CreateToken();
}
Literal literal = LiteralUtil::CreateR0<int64_t>(value);
return literal
.Broadcast(ShapeUtil::ChangeElementType(reference_shape, S64), {})
.value();
}
Literal CreateGarbageLiteral(const Shape& reference_shape) {
if (reference_shape.IsTuple()) {
std::vector<Literal> sub_literals;
for (const Shape& shape : reference_shape.tuple_shapes()) {
sub_literals.emplace_back(CreateGarbageLiteral(shape));
}
return Literal::MoveIntoTuple(absl::MakeSpan(sub_literals));
}
PrimitiveType element_type = reference_shape.element_type();
if (element_type == TOKEN) {
return LiteralUtil::CreateToken();
}
Literal literal = LiteralUtil::One(element_type);
return literal.Broadcast(reference_shape, {}).value();
}
struct HloProtoEvaluator {
explicit HloProtoEvaluator(HloEvaluator& evaluator, HloInstructionProto inst)
: evaluator(evaluator),
inst(std::move(inst)),
module("EmptyModuleForEvaluation", HloModuleConfig()) {}
HloProtoEvaluator& WithComputation(
std::unique_ptr<HloComputation> new_computation) {
computation = new_computation.get();
computation->ClearUniqueIdInternal();
for (HloInstruction* inst : computation->instructions()) {
inst->ClearUniqueIdInternal();
}
module.AddEmbeddedComputation(std::move(new_computation));
return *this;
}
HloProtoEvaluator& WithPrimitiveType(PrimitiveType new_primitive_type) {
primitive_type = new_primitive_type;
return *this;
}
HloProtoEvaluator& WithOpCode(HloOpcode new_opcode) {
opcode = new_opcode;
return *this;
}
HloProtoEvaluator& WithOperands(absl::Span<Literal> operands) {
this->operands = operands;
return *this;
}
HloProtoEvaluator& WithSubshape(ShapeIndex shape_index) {
this->shape_index = std::move(shape_index);
return *this;
}
absl::StatusOr<Literal> Evaluate() {
HloComputation::Builder builder("EmptyComputation");
absl::flat_hash_map<int64_t, HloInstruction*> operand_map;
for (int64_t i = 0; i < inst.operand_ids_size(); ++i) {
int64_t operand_handle = inst.operand_ids(i);
std::unique_ptr<HloInstruction> operand =
HloInstruction::CreateConstant(operands[i].Clone());
operand_map[operand_handle] = operand.get();
builder.AddInstruction(std::move(operand));
}
if (primitive_type.has_value()) {
*inst.mutable_shape() = ShapeUtil::ChangeElementType(
Shape(inst.shape()), primitive_type.value())
.ToProto();
}
if (opcode.has_value()) {
*inst.mutable_opcode() = std::string(HloOpcodeString(opcode.value()));
}
absl::flat_hash_map<int64_t, HloComputation*> computation_map;
if (inst.called_computation_ids_size() != 0) {
TF_RET_CHECK(inst.called_computation_ids_size() == 1 &&
computation != nullptr)
<< inst.DebugString();
computation_map[inst.called_computation_ids(0)] = computation;
}
TF_ASSIGN_OR_RETURN(
auto new_instruction,
HloInstruction::CreateFromProto(inst, operand_map, computation_map));
new_instruction->ClearUniqueIdInternal();
builder.AddInstruction(std::move(new_instruction));
auto computation = builder.Build();
module.AddEntryComputation(std::move(computation));
if (shape_index.empty()) {
return evaluator.Evaluate(module.entry_computation()->root_instruction());
} else {
TF_ASSIGN_OR_RETURN(
auto result,
evaluator.Evaluate(module.entry_computation()->root_instruction()));
return result.SubLiteral(this->shape_index);
}
}
HloEvaluator& evaluator;
HloInstructionProto inst;
HloModule module;
absl::Span<Literal> operands;
ShapeIndex shape_index = {};
HloComputation* computation = nullptr;
std::optional<PrimitiveType> primitive_type = std::nullopt;
std::optional<HloOpcode> opcode = std::nullopt;
};
enum PostorderDFSNodeType {
kConstantValue = 0,
kConstantUpperBound,
kConstantLowerBound,
kValueIsDynamic,
kBoundIsDynamic,
};
std::string PostorderDFSNodeTypeToString(PostorderDFSNodeType type) {
switch (type) {
case kConstantValue:
return "kConstantValue";
case kConstantUpperBound:
return "kConstantUpperBound";
case kConstantLowerBound:
return "kConstantLowerBound";
case kValueIsDynamic:
return "kValueIsDynamic";
case kBoundIsDynamic:
return "kBoundIsDynamic";
}
}
struct InferenceContext {
explicit InferenceContext(ShapeIndex shape_index,
std::vector<int64_t> caller_operand_handles)
: shape_index(std::move(shape_index)),
caller_operand_handles(std::move(caller_operand_handles)) {}
ShapeIndex shape_index;
std::vector<int64_t> caller_operand_handles;
};
struct PostorderDFSDep {
explicit PostorderDFSDep(int64_t handle, PostorderDFSNodeType type,
InferenceContext context, std::string annotation)
: handle(handle),
type(type),
context(std::move(context)),
annotation(std::move(annotation)) {}
int64_t handle;
PostorderDFSNodeType type;
InferenceContext context;
std::string annotation;
};
using Visit = std::function<absl::StatusOr<Literal>(absl::Span<Literal>)>;
using Visit0D = std::function<absl::StatusOr<Literal>()>;
using Visit1D = std::function<absl::StatusOr<Literal>(Literal)>;
using Visit2D = std::function<absl::StatusOr<Literal>(Literal, Literal)>;
struct [[nodiscard]] PostorderDFSNode {
PostorderDFSNode& AddDependency(int64_t handle, PostorderDFSNodeType type,
InferenceContext context,
std::string annotation = "") {
dependencies.emplace_back(handle, type, std::move(context),
std::move(annotation));
return *this;
}
PostorderDFSNode& AddVisit(const Visit& visit) {
this->visit = visit;
return *this;
}
PostorderDFSNode& AddVisit(const Visit0D& visit) {
this->visit = [visit](absl::Span<Literal> literals) { return visit(); };
return *this;
}
PostorderDFSNode& AddVisit(const Visit1D& visit) {
this->visit = [visit](absl::Span<Literal> literals) {
return visit(std::move(literals[0]));
};
return *this;
}
PostorderDFSNode& AddVisit(const Visit2D& visit) {
this->visit = [visit](absl::Span<Literal> literals) {
return visit(std::move(literals[0]), std::move(literals[1]));
};
return *this;
}
std::vector<PostorderDFSDep> dependencies;
Visit visit;
};
using HandleToInstruction =
std::function<absl::StatusOr<const HloInstructionProto*>(int64_t)>;
using HandleToComputation = std::function<const HloComputationProto*(int64_t)>;
struct PostorderDFSVisitor {
PostorderDFSVisitor(HloEvaluator& evaluator,
HandleToInstruction handle_to_instruction,
HandleToComputation handle_to_computation)
: evaluator(evaluator),
handle_to_instruction(handle_to_instruction),
handle_to_computation(handle_to_computation) {}
absl::StatusOr<PostorderDFSNode> AnalyzeUpperBound(int64_t handle,
InferenceContext context);
absl::StatusOr<PostorderDFSNode> AnalyzeLowerBound(int64_t handle,
InferenceContext context);
absl::StatusOr<PostorderDFSNode> AnalyzeIsDynamic(int64_t handle,
PostorderDFSNodeType type,
InferenceContext context);
absl::StatusOr<PostorderDFSNode> AnalyzeConstant(int64_t handle,
InferenceContext context);
absl::StatusOr<PostorderDFSNode> AnalyzeConstantValueFallback(
int64_t handle, PostorderDFSNodeType type, InferenceContext context);
absl::StatusOr<Literal> PostOrderDFSVisit(int64_t handle,
PostorderDFSNodeType type);
bool IsValueEffectiveInteger(int64_t handle) {
const HloInstructionProto* instr = handle_to_instruction(handle).value();
if (primitive_util::IsIntegralType(instr->shape().element_type())) {
return true;
}
HloOpcode opcode = StringToHloOpcode(instr->opcode()).value();
if (opcode != HloOpcode::kConvert) {
return false;
}
const HloInstructionProto* parent =
handle_to_instruction(instr->operand_ids(0)).value();
if (primitive_util::IsIntegralType(parent->shape().element_type())) {
return true;
}
return false;
}
bool IsInstructionOverLimit(const HloInstructionProto* proto,
const InferenceContext& context) {
auto subshape = std::make_unique<Shape>(
ShapeUtil::GetSubshape(Shape(proto->shape()), context.shape_index));
if (subshape->IsArray() &&
ShapeUtil::ElementsIn(*subshape) > kLargeShapeElementLimit) {
return true;
}
HloOpcode opcode = StringToHloOpcode(proto->opcode()).value();
for (int64_t operand_id : proto->operand_ids()) {
const HloInstructionProto* operand =
handle_to_instruction(operand_id).value();
auto operand_shape = std::make_unique<Shape>(operand->shape());
if (operand_shape->IsArray() &&
ShapeUtil::ElementsIn(*operand_shape) > kLargeShapeElementLimit &&
opcode != HloOpcode::kGetDimensionSize &&
opcode != HloOpcode::kSetDimensionSize) {
return true;
}
}
return false;
}
struct CacheKey {
CacheKey(int64_t handle, InferenceContext context,
PostorderDFSNodeType type)
: handle(handle), context(context), type(type) {}
int64_t handle;
InferenceContext context;
PostorderDFSNodeType type;
template <typename H>
friend H AbslHashValue(H h, const CacheKey& key) {
h = H::combine(std::move(h), key.handle);
h = H::combine(std::move(h), key.context.shape_index.ToString());
h = H::combine(std::move(h),
VectorString(key.context.caller_operand_handles));
h = H::combine(std::move(h), key.type);
return h;
}
friend bool operator==(const CacheKey& lhs, const CacheKey& rhs) {
return lhs.handle == rhs.handle &&
lhs.context.shape_index == rhs.context.shape_index &&
lhs.context.caller_operand_handles ==
rhs.context.caller_operand_handles &&
lhs.type == rhs.type;
}
};
HloEvaluator& evaluator;
absl::flat_hash_map<CacheKey, Literal> evaluated;
HandleToInstruction handle_to_instruction;
HandleToComputation handle_to_computation;
static constexpr int64_t kLargeShapeElementLimit = 1000 * 1000;
};
PostorderDFSNode CreateAllDynamicResult(const Shape& shape,
const PostorderDFSNodeType& type) {
return PostorderDFSNode().AddVisit(
[shape, type](absl::Span<Literal>) -> Literal {
if (type == PostorderDFSNodeType::kConstantValue ||
type == PostorderDFSNodeType::kConstantUpperBound ||
type == PostorderDFSNodeType::kConstantLowerBound) {
return CreateGarbageLiteral(shape);
} else {
return CreatePredLiteral(true, shape);
}
});
}
}
absl::StatusOr<PostorderDFSNode>
PostorderDFSVisitor::AnalyzeConstantValueFallback(int64_t handle,
PostorderDFSNodeType type,
InferenceContext context) {
TF_ASSIGN_OR_RETURN(const HloInstructionProto* root,
handle_to_instruction(handle));
TF_ASSIGN_OR_RETURN(HloOpcode opcode, StringToHloOpcode(root->opcode()));
Shape subshape =
ShapeUtil::GetSubshape(Shape(root->shape()), context.shape_index);
PostorderDFSNode result;
for (auto operand_id : root->operand_ids()) {
InferenceContext dep_context = context;
dep_context.shape_index = {};
result.AddDependency(operand_id, type, dep_context);
}
switch (opcode) {
case HloOpcode::kRng:
case HloOpcode::kAllReduce:
case HloOpcode::kReduceScatter:
case HloOpcode::kInfeed:
case HloOpcode::kOutfeed:
case HloOpcode::kRngBitGenerator:
case HloOpcode::kCustomCall:
case HloOpcode::kWhile:
case HloOpcode::kSend:
case HloOpcode::kRecv:
case HloOpcode::kSendDone:
case HloOpcode::kRecvDone:
case HloOpcode::kParameter: {
if (opcode == HloOpcode::kParameter &&
!context.caller_operand_handles.empty()) {
int64_t caller_operand = context.caller_operand_handles.back();
context.caller_operand_handles.pop_back();
return result.AddDependency(caller_operand, type, context)
.AddVisit([](Literal literal) { return literal; });
}
return CreateAllDynamicResult(subshape, type);
}
case HloOpcode::kSubtract:
case HloOpcode::kCos:
case HloOpcode::kSin:
case HloOpcode::kTan:
case HloOpcode::kNegate:
case HloOpcode::kAbs:
case HloOpcode::kDivide:
case HloOpcode::kGetDimensionSize: {
return InvalidArgument(
"AnalyzeConstantValueFallback can't handle opcode: %s",
root->opcode());
}
case HloOpcode::kCall: {
auto node = PostorderDFSNode();
auto* call_proto = root;
if (call_proto->operand_ids_size() != 1) {
return CreateAllDynamicResult(subshape, type);
}
int64_t called_root =
handle_to_computation(call_proto->called_computation_ids(0))
->root_id();
InferenceContext call_context = context;
call_context.caller_operand_handles.push_back(call_proto->operand_ids(0));
node.AddDependency(called_root, PostorderDFSNodeType::kConstantValue,
call_context, "callee's root instruction");
return node.AddVisit([](Literal operand) -> absl::StatusOr<Literal> {
return std::move(operand);
});
}
case HloOpcode::kConditional: {
auto node = PostorderDFSNode();
auto* conditional_proto = root;
InferenceContext predicate_context = context;
predicate_context.shape_index = {};
node.AddDependency(conditional_proto->operand_ids(0),
PostorderDFSNodeType::kConstantValue,
predicate_context)
.AddDependency(conditional_proto->operand_ids(0),
PostorderDFSNodeType::kValueIsDynamic,
predicate_context);
const int64_t branch_size =
conditional_proto->called_computation_ids_size();
for (int64_t i = 0; i < branch_size; ++i) {
int64_t branch_root =
handle_to_computation(conditional_proto->called_computation_ids(i))
->root_id();
InferenceContext branch_context = context;
branch_context.caller_operand_handles.push_back(
conditional_proto->operand_ids(i + 1));
node.AddDependency(branch_root, PostorderDFSNodeType::kConstantValue,
branch_context);
}
return node.AddVisit(
[](absl::Span<Literal> operands) -> absl::StatusOr<Literal> {
int64_t pred_is_dynamic = operands[1].Get<bool>({});
if (pred_is_dynamic) {
return std::move(operands[2]);
} else {
int64_t branch_index = 0;
if (operands[0].shape().element_type() == PRED) {
if (operands[0].Get<bool>({})) {
branch_index = 0;
} else {
branch_index = 1;
}
} else {
branch_index = operands[0].GetIntegralAsS64({}).value();
}
const int64_t branch_dynamism_index = 2 + branch_index;
return std::move(operands[branch_dynamism_index]);
}
});
}
case HloOpcode::kGetTupleElement: {
int64_t operand_handle = root->operand_ids(0);
PostorderDFSNode result;
context.shape_index.push_front(root->tuple_index());
return PostorderDFSNode()
.AddDependency(operand_handle, type, context)
.AddVisit([](Literal operand) { return operand; });
}
case HloOpcode::kReduce:
case HloOpcode::kSort:
case HloOpcode::kScatter:
case HloOpcode::kReduceWindow: {
const HloComputationProto* computation_proto =
handle_to_computation(root->called_computation_ids(0));
return result.AddVisit(
[root, computation_proto, context,
this](absl::Span<Literal> operands) -> absl::StatusOr<Literal> {
TF_ASSIGN_OR_RETURN(
auto computation,
HloComputation::CreateFromProto(*computation_proto, {}));
return std::make_unique<HloProtoEvaluator>(evaluator, *root)
->WithOperands(operands)
.WithComputation(std::move(computation))
.WithSubshape(context.shape_index)
.Evaluate();
});
}
default: {
if (opcode == HloOpcode::kTuple && !context.shape_index.empty()) {
int64_t tuple_operand_index = context.shape_index.front();
InferenceContext tuple_operand_context = context;
tuple_operand_context.shape_index.pop_front();
return PostorderDFSNode()
.AddDependency(root->operand_ids(tuple_operand_index), type,
tuple_operand_context)
.AddVisit([](Literal operand) { return operand; });
}
return result.AddVisit([root, this](absl::Span<Literal> operands) {
return std::make_unique<HloProtoEvaluator>(evaluator, *root)
->WithOperands(operands)
.Evaluate();
});
}
}
}
absl::StatusOr<PostorderDFSNode> PostorderDFSVisitor::AnalyzeUpperBound(
int64_t handle, InferenceContext context) {
TF_ASSIGN_OR_RETURN(const HloInstructionProto* root,
handle_to_instruction(handle));
TF_ASSIGN_OR_RETURN(HloOpcode opcode, StringToHloOpcode(root->opcode()));
Shape subshape =
ShapeUtil::GetSubshape(Shape(root->shape()), context.shape_index);
if (IsInstructionOverLimit(root, context)) {
return CreateAllDynamicResult(subshape,
PostorderDFSNodeType::kConstantUpperBound);
}
switch (opcode) {
case HloOpcode::kGetDimensionSize: {
int64_t dimension = root->dimensions(0);
int64_t operand_handle = root->operand_ids(0);
const HloInstructionProto* operand_proto =
handle_to_instruction(operand_handle).value();
return PostorderDFSNode().AddVisit(
[operand_proto, dimension]() -> absl::StatusOr<Literal> {
return LiteralUtil::CreateR0<int32_t>(
operand_proto->shape().dimensions(dimension));
});
}
case HloOpcode::kAbs: {
return PostorderDFSNode()
.AddDependency(root->operand_ids(0),
PostorderDFSNodeType::kConstantLowerBound, context)
.AddDependency(root->operand_ids(0),
PostorderDFSNodeType::kConstantUpperBound, context)
.AddVisit([this](Literal lower_bound,
Literal upper_bound) -> absl::StatusOr<Literal> {
TF_ASSIGN_OR_RETURN(auto lower_bound_abs,
evaluator.EvaluateElementwiseUnaryOp(
HloOpcode::kAbs, lower_bound));
TF_ASSIGN_OR_RETURN(auto upper_bound_abs,
evaluator.EvaluateElementwiseUnaryOp(
HloOpcode::kAbs, upper_bound));
return evaluator.EvaluateElementwiseBinaryOp(
HloOpcode::kMaximum, lower_bound_abs, upper_bound_abs);
});
}
case HloOpcode::kSort: {
auto dfs = PostorderDFSNode();
InferenceContext dep_context = context;
dep_context.shape_index = {};
if (!context.shape_index.empty()) {
dfs.AddDependency(root->operand_ids(context.shape_index[0]),
PostorderDFSNodeType::kConstantUpperBound,
dep_context);
} else {
for (int64_t i = 0; i < root->operand_ids_size(); ++i) {
dfs.AddDependency(root->operand_ids(i),
PostorderDFSNodeType::kConstantUpperBound,
dep_context);
}
}
return dfs.AddVisit(
[root,
context](absl::Span<Literal> operands) -> absl::StatusOr<Literal> {
std::vector<Literal> results;
results.reserve(operands.size());
for (int64_t i = 0; i < operands.size(); ++i) {
auto max = LiteralUtil::MaxElement(operands[i]);
results.emplace_back( | #include "xla/client/value_inference.h"
#include <memory>
#include <utility>
#include <vector>
#include "absl/status/statusor.h"
#include "absl/strings/match.h"
#include "absl/types/span.h"
#include "xla/client/client_library.h"
#include "xla/client/global_data.h"
#include "xla/client/lib/arithmetic.h"
#include "xla/client/lib/prng.h"
#include "xla/client/xla_builder.h"
#include "xla/client/xla_computation.h"
#include "xla/layout_util.h"
#include "xla/literal.h"
#include "xla/shape_util.h"
#include "xla/status_macros.h"
#include "xla/test.h"
#include "xla/tests/literal_test_util.h"
#include "xla/tests/test_macros.h"
#include "xla/tests/test_utils.h"
#include "xla/xla_data.pb.h"
#include "tsl/lib/core/status_test_util.h"
#include "tsl/platform/status.h"
#include "tsl/platform/statusor.h"
namespace xla {
namespace {
class ValueInferenceTest : public ::testing::Test {
public:
std::string TestName() const {
return ::testing::UnitTest::GetInstance()->current_test_info()->name();
}
};
class DynamismInferenceTest : public ValueInferenceTest {
public:
explicit DynamismInferenceTest(se::Platform* platform = nullptr)
: platform_(platform) {}
absl::StatusOr<Literal> ComputeDynamismLiteral(
XlaOp operand, XlaBuilder* builder, Layout* output_layout = nullptr) {
TF_RETURN_IF_ERROR(builder->first_error());
ValueInference value_inference(builder);
TF_ASSIGN_OR_RETURN(auto literal_slice,
value_inference.AnalyzeIsDynamic(operand));
return literal_slice.Clone();
}
absl::StatusOr<bool> ComputeDynamismScalar(XlaOp operand, XlaBuilder* builder,
ShapeIndex index = {}) {
TF_ASSIGN_OR_RETURN(auto literal,
ComputeDynamismLiteral(operand, builder, nullptr));
return literal.Get<bool>({}, index);
}
se::Platform* platform_;
};
TEST_F(DynamismInferenceTest, ScalarInt32Literal) {
XlaBuilder b(TestName());
auto computation = ConstantR0<int32_t>(&b, 42);
auto value = ComputeDynamismScalar(computation, &b);
ASSERT_TRUE(value.ok()) << value.status();
EXPECT_EQ(value.value(), false);
}
TEST_F(DynamismInferenceTest, Iota) {
XlaBuilder b(TestName());
auto computation = Iota(&b, S32, 2);
EXPECT_FALSE(ComputeDynamismLiteral(computation, &b).value().Get<bool>({0}));
}
TEST_F(DynamismInferenceTest, TupleSimple) {
XlaBuilder b(TestName());
auto c = ConstantR0<int32_t>(&b, 42);
auto p = Parameter(&b, 0, ShapeUtil::MakeScalarShape(S32), "p0");
auto tuple = Tuple(&b, {c, p});
EXPECT_EQ(ComputeDynamismScalar(tuple, &b, {0}).value(), false);
EXPECT_EQ(ComputeDynamismScalar(tuple, &b, {1}).value(), true);
}
TEST_F(DynamismInferenceTest, TupleGteKeepsDynamism) {
XlaBuilder b(TestName());
auto c = ConstantR0<int32_t>(&b, 42);
auto p = Parameter(&b, 0, ShapeUtil::MakeScalarShape(S32), "p0");
auto tuple = Tuple(&b, {c, p});
auto gte0 = GetTupleElement(tuple, 0);
auto gte1 = GetTupleElement(tuple, 1);
auto tuple_2 = Tuple(&b, {gte0, gte1});
EXPECT_EQ(ComputeDynamismScalar(tuple_2, &b, {0}).value(), false);
EXPECT_EQ(ComputeDynamismScalar(tuple_2, &b, {1}).value(), true);
}
TEST_F(DynamismInferenceTest, PredValueUsedTwice) {
XlaBuilder b(TestName());
auto c = ConstantR0<int32_t>(&b, 42);
auto p = Parameter(&b, 0, ShapeUtil::MakeScalarShape(S32), "p0");
auto pred = Eq(c, p);
auto result = Select(pred, p, c);
EXPECT_EQ(ComputeDynamismScalar(result, &b, {}).value(), true);
}
TEST_F(DynamismInferenceTest, ReduceUsedTwice) {
XlaBuilder b(TestName());
auto c = ConstantR0<int32_t>(&b, 42);
auto p = Parameter(&b, 0, ShapeUtil::MakeShape(S32, {2}), "p0");
auto zero = ConstantR0<int32_t>(&b, 0);
XlaComputation add_s32 = CreateScalarAddComputation(S32, &b);
auto reduce = Reduce(p, zero, add_s32, {0});
auto pred = Eq(c, reduce);
auto result = Select(pred, reduce, c);
EXPECT_EQ(ComputeDynamismScalar(result, &b, {}).value(), true);
}
TEST_F(DynamismInferenceTest, VariadicReduce) {
XlaBuilder b(TestName());
auto c = ConstantR2<int32_t>(&b, {{0, 0}});
auto p = Parameter(&b, 0, ShapeUtil::MakeShape(S32, {1, 2}), "p0");
auto half_dynamic = ConcatInDim(&b, {c, p}, 0);
XlaBuilder reduce_add("reduce_add");
auto p0 = Parameter(&reduce_add, 0, ShapeUtil::MakeScalarShape(S32), "p");
auto p1 = Parameter(&reduce_add, 1, ShapeUtil::MakeScalarShape(S32), "p");
auto p2 = Parameter(&reduce_add, 2, ShapeUtil::MakeScalarShape(S32), "p");
auto p3 = Parameter(&reduce_add, 3, ShapeUtil::MakeScalarShape(S32), "p");
auto reduce_result = p0;
reduce_result = Add(reduce_result, p1);
reduce_result = Add(reduce_result, p2);
reduce_result = Add(reduce_result, p3);
Tuple(&reduce_add, {reduce_result, reduce_result});
auto init = ConstantR0<int32_t>(&b, 0);
auto variadic_reduce = Reduce(&b, {half_dynamic, half_dynamic}, {init, init},
reduce_add.Build().value(), {1});
auto result = GetTupleElement(variadic_reduce, 0);
EXPECT_FALSE(ComputeDynamismLiteral(result, &b).value().Get<bool>({0}));
EXPECT_TRUE(ComputeDynamismLiteral(result, &b).value().Get<bool>({1}));
}
TEST_F(DynamismInferenceTest, DynamicSelectorWithMixedValues) {
XlaBuilder b(TestName());
auto constant_pred = ConstantR1<bool>(&b, {true});
auto dynamic_pred = Parameter(&b, 0, ShapeUtil::MakeShape(PRED, {1}), "p0");
auto concat = ConcatInDim(&b, {constant_pred, dynamic_pred}, 0);
auto constant_values = ConstantR1<bool>(&b, {true, true});
auto result = Select(concat, constant_values, constant_values);
EXPECT_FALSE(ComputeDynamismLiteral(result, &b).value().Get<bool>({0}));
EXPECT_TRUE(ComputeDynamismLiteral(result, &b).value().Get<bool>({1}));
}
TEST_F(DynamismInferenceTest, ConcatSliceReshapeKeepsDynamism) {
XlaBuilder b(TestName());
auto c = ConstantR0<int32_t>(&b, 42);
auto p = Parameter(&b, 0, ShapeUtil::MakeScalarShape(S32), "p0");
auto concat = ConcatScalars(&b, {c, p});
auto slice0 = SliceInDim(concat, 0, 1, 1, 0);
auto reshape0 = Reshape(slice0, {});
auto slice1 = SliceInDim(concat, 1, 2, 1, 0);
auto reshape1 = Reshape(slice1, {});
auto tuple_2 = Tuple(&b, {reshape0, reshape1});
EXPECT_EQ(ComputeDynamismScalar(tuple_2, &b, {0}).value(), false);
EXPECT_EQ(ComputeDynamismScalar(tuple_2, &b, {1}).value(), true);
}
TEST_F(DynamismInferenceTest, ParameterIsDynamic) {
XlaBuilder b(TestName());
auto computation = Parameter(&b, 0, ShapeUtil::MakeScalarShape(S32), "p0");
auto value = ComputeDynamismScalar(computation, &b);
ASSERT_TRUE(value.ok()) << value.status();
EXPECT_EQ(value.value(), true);
}
TEST_F(DynamismInferenceTest, UnaryOpKeepsDynamism) {
XlaBuilder b(TestName());
auto c = ConstantR0<int32_t>(&b, 42);
auto p = Parameter(&b, 0, ShapeUtil::MakeScalarShape(S32), "p0");
auto neg0 = Neg(c);
auto neg1 = Neg(p);
auto tuple_2 = Tuple(&b, {neg0, neg1});
EXPECT_EQ(ComputeDynamismScalar(tuple_2, &b, {0}).value(), false);
EXPECT_EQ(ComputeDynamismScalar(tuple_2, &b, {1}).value(), true);
}
TEST_F(DynamismInferenceTest, ParameterWithToken) {
XlaBuilder b(TestName());
auto p =
Parameter(&b, 0,
ShapeUtil::MakeTupleShape({ShapeUtil::MakeTokenShape(),
ShapeUtil::MakeScalarShape(S32)}),
"p0");
EXPECT_EQ(ComputeDynamismScalar(p, &b, {0}).value(), true);
EXPECT_EQ(ComputeDynamismScalar(p, &b, {1}).value(), true);
}
TEST_F(DynamismInferenceTest, BinaryOpsOrsDynamism) {
XlaBuilder b(TestName());
auto c = ConstantR0<int32_t>(&b, 42);
auto p = Parameter(&b, 0, ShapeUtil::MakeScalarShape(S32), "p0");
auto add1 = Add(c, c);
auto add2 = Add(p, c);
auto tuple_2 = Tuple(&b, {add1, add2});
EXPECT_EQ(ComputeDynamismScalar(tuple_2, &b, {0}).value(), false);
EXPECT_EQ(ComputeDynamismScalar(tuple_2, &b, {1}).value(), true);
}
TEST_F(DynamismInferenceTest, GetDimensionSize) {
XlaBuilder b(TestName());
auto p =
Parameter(&b, 0, ShapeUtil::MakeShape(S32, {2, 3}, {true, false}), "p0");
auto gds0 = GetDimensionSize(p, 0);
auto gds1 = GetDimensionSize(p, 1);
auto tuple_2 = Tuple(&b, {gds0, gds1});
EXPECT_EQ(ComputeDynamismScalar(tuple_2, &b, {0}).value(), true);
EXPECT_EQ(ComputeDynamismScalar(tuple_2, &b, {1}).value(), false);
}
TEST_F(DynamismInferenceTest, DynamicSliceWithConstantOperands) {
XlaBuilder b(TestName());
auto constant = ConstantR1<int32_t>(&b, {0, 1, 2, 3});
auto slice_start = ConstantR0(&b, 1);
auto dynamic_slice = DynamicSlice(constant, {slice_start}, {1});
EXPECT_FALSE(
ComputeDynamismLiteral(dynamic_slice, &b).value().Get<bool>({0}));
}
TEST_F(DynamismInferenceTest, GatherWithCommonParent) {
XlaBuilder b(TestName());
Shape indices_shape = ShapeUtil::MakeShape(S32, {2});
auto operand1 = Parameter(&b, 0, indices_shape, "p1");
auto operand2 = Parameter(&b, 1, indices_shape, "p2");
auto indices = Sub(operand1, operand2);
GatherDimensionNumbers dim_numbers;
dim_numbers.add_offset_dims(1);
dim_numbers.add_start_index_map(0);
dim_numbers.set_index_vector_dim(1);
auto gather = Gather(operand1, indices, dim_numbers, {1});
ASSERT_TRUE(b.first_error().ok()) << b.first_error().message();
EXPECT_TRUE(ComputeDynamismLiteral(gather, &b).value().Get<bool>({0, 0}));
}
TEST_F(DynamismInferenceTest, GatherWithConstantParent) {
XlaBuilder b(TestName());
Shape indices_shape = ShapeUtil::MakeShape(S32, {2});
auto data_operand = ConstantR1<int32_t>(&b, {1, 2});
auto indices = ConstantR1<int32_t>(&b, {1, 2});
GatherDimensionNumbers dim_numbers;
dim_numbers.add_offset_dims(1);
dim_numbers.add_start_index_map(0);
dim_numbers.set_index_vector_dim(1);
auto gather = Gather(data_operand, indices, dim_numbers, {1});
ASSERT_TRUE(b.first_error().ok()) << b.first_error().message();
EXPECT_FALSE(ComputeDynamismLiteral(gather, &b).value().Get<bool>({0, 0}));
}
TEST_F(DynamismInferenceTest, GatherWithSharedConstantParent) {
XlaBuilder b(TestName());
Shape indices_shape = ShapeUtil::MakeShape(S32, {2});
auto operand1 = ConstantR1<int32_t>(&b, {1, 2});
auto operand2 = ConstantR1<int32_t>(&b, {1, 2});
auto indices = Sub(operand1, operand2);
GatherDimensionNumbers dim_numbers;
dim_numbers.add_offset_dims(1);
dim_numbers.add_start_index_map(0);
dim_numbers.set_index_vector_dim(1);
auto gather = Gather(operand1, indices, dim_numbers, {1});
ASSERT_TRUE(b.first_error().ok()) << b.first_error().message();
EXPECT_FALSE(ComputeDynamismLiteral(gather, &b).value().Get<bool>({0, 0}));
}
TEST_F(DynamismInferenceTest, InferThroughPad) {
XlaBuilder b(TestName());
auto operand1 = ConstantR1<int32_t>(&b, {1, 2});
auto parameter = Parameter(&b, 0, ShapeUtil::MakeShape(S32, {}), "p0");
PaddingConfig padding_config;
padding_config.add_dimensions()->set_edge_padding_high(1);
auto pad = Pad(operand1, parameter, padding_config);
ASSERT_TRUE(b.first_error().ok()) << b.first_error().message();
EXPECT_FALSE(ComputeDynamismLiteral(pad, &b).value().Get<bool>({0}));
EXPECT_FALSE(ComputeDynamismLiteral(pad, &b).value().Get<bool>({1}));
EXPECT_TRUE(ComputeDynamismLiteral(pad, &b).value().Get<bool>({2}));
}
TEST_F(DynamismInferenceTest, InferThroughConditionalBranchesAreSame) {
auto s32_shape = ShapeUtil::MakeShape(S32, {});
auto cond_shape = ShapeUtil::MakeTupleShape({s32_shape});
XlaBuilder true_builder("true");
Parameter(&true_builder, 0, s32_shape, "cond_param");
Tuple(&true_builder, {ConstantR0<int32_t>(&true_builder, 1)});
auto true_computation = true_builder.Build().value();
XlaBuilder false_builder("false");
Parameter(&false_builder, 0, s32_shape, "cond_param");
Tuple(&false_builder, {ConstantR0<int32_t>(&false_builder, 1)});
auto false_computation = false_builder.Build().value();
XlaBuilder b(TestName());
auto parameter = Parameter(&b, 0, ShapeUtil::MakeShape(PRED, {}), "p0");
auto constant = ConstantR0<int32_t>(&b, 0);
auto cond = Conditional(parameter, constant, true_computation, constant,
false_computation);
auto gte = GetTupleElement(cond, 0);
ASSERT_TRUE(b.first_error().ok()) << b.first_error().message();
EXPECT_FALSE(ComputeDynamismLiteral(gte, &b).value().Get<bool>({}));
}
TEST_F(DynamismInferenceTest, InferThroughCall) {
auto s32_shape = ShapeUtil::MakeShape(S32, {});
XlaBuilder call_builder("call");
Parameter(&call_builder, 0, s32_shape, "call_param");
auto call_computation = call_builder.Build().value();
XlaBuilder b(TestName());
auto constant = ConstantR0<int32_t>(&b, 3);
auto call = Call(&b, call_computation, {constant});
ASSERT_TRUE(b.first_error().ok()) << b.first_error().message();
EXPECT_EQ(ComputeDynamismScalar(call, &b, {}).value(), false);
}
TEST_F(DynamismInferenceTest, InferThroughConditionalBranchesAreNotSame) {
auto s32_shape = ShapeUtil::MakeShape(S32, {});
auto cond_shape = ShapeUtil::MakeTupleShape({s32_shape});
XlaBuilder true_builder("true");
Parameter(&true_builder, 0, s32_shape, "cond_param");
Tuple(&true_builder, {ConstantR0<int32_t>(&true_builder, 1)});
auto true_computation = true_builder.Build().value();
XlaBuilder false_builder("false");
Parameter(&false_builder, 0, s32_shape, "cond_param");
Tuple(&false_builder, {ConstantR0<int32_t>(&false_builder, 2)});
auto false_computation = false_builder.Build().value();
XlaBuilder b(TestName());
auto parameter = Parameter(&b, 0, ShapeUtil::MakeShape(PRED, {}), "p0");
auto constant = ConstantR0<int32_t>(&b, 0);
auto cond = Conditional(parameter, constant, true_computation, constant,
false_computation);
auto gte = GetTupleElement(cond, 0);
ASSERT_TRUE(b.first_error().ok()) << b.first_error().message();
EXPECT_TRUE(ComputeDynamismLiteral(gte, &b).value().Get<bool>({}));
}
TEST_F(DynamismInferenceTest, InferThroughConditionalPredIsConstantTrueBranch) {
auto s32_shape = ShapeUtil::MakeShape(S32, {});
auto cond_shape = ShapeUtil::MakeTupleShape({s32_shape});
XlaBuilder true_builder("true");
Parameter(&true_builder, 0, s32_shape, "cond_param");
Tuple(&true_builder, {ConstantR0<int32_t>(&true_builder, 0)});
auto true_computation = true_builder.Build().value();
XlaBuilder false_builder("false");
Tuple(&false_builder,
{Parameter(&false_builder, 0, s32_shape, "cond_param")});
auto false_computation = false_builder.Build().value();
XlaBuilder b(TestName());
auto pred = ConstantR0<bool>(&b, true);
auto constant = ConstantR0<int32_t>(&b, 0);
auto cond = Conditional(pred, constant, true_computation, constant,
false_computation);
auto gte = GetTupleElement(cond, 0);
ASSERT_TRUE(b.first_error().ok()) << b.first_error().message();
EXPECT_FALSE(ComputeDynamismLiteral(gte, &b).value().Get<bool>({}));
}
TEST_F(DynamismInferenceTest,
InferThroughConditionalPredIsConstantFalseBranch) {
auto s32_shape = ShapeUtil::MakeShape(S32, {});
auto cond_shape = ShapeUtil::MakeTupleShape({s32_shape});
XlaBuilder true_builder("true");
Parameter(&true_builder, 0, s32_shape, "cond_param");
Tuple(&true_builder, {ConstantR0<int32_t>(&true_builder, 0)});
auto true_computation = true_builder.Build().value();
XlaBuilder false_builder("false");
Tuple(&false_builder,
{Parameter(&false_builder, 0, s32_shape, "cond_param")});
auto false_computation = false_builder.Build().value();
XlaBuilder b(TestName());
auto param = Parameter(&b, 0, s32_shape, "param");
auto pred = ConstantR0<bool>(&b, false);
auto constant = ConstantR0<int32_t>(&b, 0);
auto cond =
Conditional(pred, constant, true_computation, param, false_computation);
auto gte = GetTupleElement(cond, 0);
ASSERT_TRUE(b.first_error().ok()) << b.first_error().message();
EXPECT_TRUE(ComputeDynamismLiteral(gte, &b).value().Get<bool>({}));
}
TEST_F(DynamismInferenceTest, ArgumentForwardingNestedTuple) {
auto pred_shape = ShapeUtil::MakeShape(PRED, {});
auto s32_shape = ShapeUtil::MakeShape(S32, {});
auto tuple_shape = ShapeUtil::MakeTupleShape({pred_shape, s32_shape});
auto cond_shape = ShapeUtil::MakeTupleShape({s32_shape});
XlaBuilder inner_true_builder("inner_true");
Parameter(&inner_true_builder, 0, s32_shape, "cond_param");
Tuple(&inner_true_builder, {ConstantR0<int32_t>(&inner_true_builder, 0)});
auto inner_true_computation = inner_true_builder.Build().value();
XlaBuilder inner_false_builder("inner_false");
Tuple(&inner_false_builder,
{Parameter(&inner_false_builder, 0, s32_shape, "cond_param")});
auto inner_false_computation = inner_false_builder.Build().value();
XlaBuilder true_builder("true");
{
auto param = Parameter(&true_builder, 0, tuple_shape, "param");
auto op = GetTupleElement(param, 1);
auto pred = GetTupleElement(param, 0);
Conditional(pred, op, inner_true_computation, op, inner_false_computation);
}
auto true_computation = true_builder.Build().value();
XlaBuilder false_builder("false");
{
auto param = Parameter(&false_builder, 0, tuple_shape, "param");
auto op = GetTupleElement(param, 1);
auto pred = GetTupleElement(param, 0);
Conditional(pred, op, inner_true_computation, op, inner_false_computation);
}
auto false_computation = false_builder.Build().value();
XlaBuilder b(TestName());
auto constant = ConstantR0<int32_t>(&b, 0);
auto pred = Parameter(&b, 0, pred_shape, "param");
auto param = Tuple(&b, {pred, constant});
auto cond =
Conditional(pred, param, true_computation, param, false_computation);
auto gte = GetTupleElement(cond, 0);
ASSERT_TRUE(b.first_error().ok()) << b.first_error().message();
EXPECT_FALSE(ComputeDynamismLiteral(gte, &b).value().Get<bool>({}));
}
class UpperBoundInferenceTest : public ValueInferenceTest {
public:
explicit UpperBoundInferenceTest(se::Platform* platform = nullptr)
: platform_(platform) {}
absl::StatusOr<OptionalLiteral> ComputeUpperBoundLiteral(
XlaOp operand, XlaBuilder* builder, Layout* output_layout = nullptr) {
ValueInference value_inference(builder);
TF_ASSIGN_OR_RETURN(auto literal,
value_inference.AnalyzeConstant(
operand, ValueInferenceMode::kUpperBound));
return literal;
}
se::Platform* platform_;
};
TEST_F(UpperBoundInferenceTest, GetDimensionSize) {
XlaBuilder b(TestName());
auto p =
Parameter(&b, 0, ShapeUtil::MakeShape(S32, {2, 3}, {true, false}), "p0");
auto gds0 = GetDimensionSize(p, 0);
auto gds1 = GetDimensionSize(p, 1);
auto tuple_2 = Tuple(&b, {gds0, gds1});
EXPECT_EQ(ComputeUpperBoundLiteral(tuple_2, &b).value().Get<int32_t>({}, {0}),
2);
EXPECT_EQ(ComputeUpperBoundLiteral(tuple_2, &b).value().Get<int32_t>({}, {1}),
3);
}
TEST_F(UpperBoundInferenceTest, GetDimensionSizeSub) {
XlaBuilder b(TestName());
auto p =
Parameter(&b, 0, ShapeUtil::MakeShape(S32, {2, 3}, {true, false}), "p0");
auto gds0 = GetDimensionSize(p, 0);
auto gds1 = GetDimensionSize(p, 1);
auto sub = Sub(gds1, gds0);
EXPECT_EQ(ComputeUpperBoundLiteral(sub, &b).value().Get<int32_t>({}), 3);
}
TEST_F(UpperBoundInferenceTest, GetDimensionSizeDiv) {
XlaBuilder b(TestName());
auto p =
Parameter(&b, 0, ShapeUtil::MakeShape(S32, {2, 3}, {true, false}), "p0");
auto gds0 = GetDimensionSize(p, 0);
auto gds1 = GetDimensionSize(p, 1);
auto div = Div(gds1, gds0);
EXPECT_EQ(ComputeUpperBoundLiteral(div, &b).value().Get<int32_t>({}), 3);
}
TEST_F(UpperBoundInferenceTest, SumSubtract) {
XlaBuilder b(TestName());
auto p =
Parameter(&b, 0, ShapeUtil::MakeShape(S32, {2, 3}, {true, true}), "p0");
auto gds0 = GetDimensionSize(p, 0);
auto gds1 = GetDimensionSize(p, 1);
auto sub = Sub(gds1, gds0);
auto add = Add(sub, gds0);
EXPECT_EQ(ComputeUpperBoundLiteral(add, &b).value().Get<int32_t>({}), 3);
auto add2 = Add(gds1, gds0);
auto add3 = Add(sub, add2);
EXPECT_EQ(ComputeUpperBoundLiteral(add3, &b).value().Get<int32_t>({}), 6);
}
TEST_F(UpperBoundInferenceTest, SumSubtractWithDataShuffling) {
XlaBuilder b(TestName());
auto p =
Parameter(&b, 0, ShapeUtil::MakeShape(S32, {2, 3}, {true, true}), "p0");
auto gds0 = GetDimensionSize(p, 0);
auto gds1 = GetDimensionSize(p, 1);
auto broadcast = Broadcast(gds0, {1, 10});
auto convert = ConvertElementType(broadcast, S32);
auto slice = SliceInDim(convert, 0, 1,
1, 1);
gds0 = Reshape(slice, {});
auto sub = Sub(gds1, gds0);
auto add = Add(sub, gds0);
EXPECT_EQ(ComputeUpperBoundLiteral(add, &b).value().Get<int32_t>({}), 3);
auto add2 = Add(gds1, gds0);
auto add3 = Add(sub, add2);
EXPECT_EQ(ComputeUpperBoundLiteral(add3, &b).value().Get<int32_t>({}), 6);
}
TEST_F(UpperBoundInferenceTest, SumSubtractEquivalentGetDimensionSize) {
XlaBuilder b(TestName());
auto p =
Parameter(&b, 0, ShapeUtil::MakeShape(S32, {2, 3}, {true, true}), "p0");
auto gds0 = GetDimensionSize(p, 0);
auto gds1 = GetDimensionSize(p, 1);
auto gds2 = GetDimensionSize(p, 0);
auto sub = Sub(gds1, gds2);
auto add = Add(sub, gds0);
EXPECT_EQ(ComputeUpperBoundLiteral(add, &b).value().Get<int32_t>({}), 3);
}
TEST_F(UpperBoundInferenceTest, ParamCantInferBound) {
XlaBuilder b(TestName());
auto p0 = Parameter(&b, 0, ShapeUtil::MakeShape(S32, {2}, {true}), "p0");
auto p1 = Parameter(&b, 1, ShapeUtil::MakeShape(S32, {}, {}), "p1");
auto gds = GetDimensionSize(p0, 0);
auto sub = Div(gds, p1);
EXPECT_FALSE(
ComputeUpperBoundLiteral(sub, &b).value().Get<int32_t>({}).has_value());
}
TEST_F(UpperBoundInferenceTest, KeyValueSort) {
XlaBuilder comparator_b("comparator");
auto p0 = Parameter(&comparator_b, 0, ShapeUtil::MakeShape(S32, {}), "p0");
auto p1 = Parameter(&comparator_b, 1, ShapeUtil::MakeShape(S32, {}), "p1");
Parameter(&comparator_b, 2, ShapeUtil::MakeShape(S32, {}), "p2");
Parameter(&comparator_b, 3, ShapeUtil::MakeShape(S32, {}), "p3");
Compare(p0, p1, ComparisonDirection::kGe);
TF_ASSERT_OK_AND_ASSIGN(auto comparator, comparator_b.Build());
int64_t elem_count = 17;
XlaBuilder b(TestName());
auto param = Parameter(&b, 0, ShapeUtil::MakeShape(S32, {elem_count}), "p0");
auto iota = Iota(&b, S32, elem_count);
auto sort = Sort({param, iota}, comparator);
auto gte = GetTupleElement(sort, 1);
for (int64_t i = 0; i < elem_count; ++i) {
auto result_first_elem =
ComputeUpperBoundLiteral(gte, &b).value().Get<int32_t>({i});
EXPECT_TRUE(result_first_elem.has_value());
EXPECT_EQ(result_first_elem.value(), elem_count - 1);
}
}
class ConstValueInferenceTest : public ValueInferenceTest {
public:
explicit ConstValueInferenceTest(se::Platform* platform = nullptr)
: platform_(platform) {}
absl::StatusOr<OptionalLiteral> ComputeConstantValueLiteral(
XlaOp operand, XlaBuilder* builder, Layout* output_layout = nullptr) {
ValueInference value_inference(builder);
TF_ASSIGN_OR_RETURN(auto literal, value_inference.AnalyzeConstant(
operand, ValueInferenceMode::kValue));
return literal;
}
se::Platform* platform_;
};
TEST_F(ConstValueInferenceTest, ConstValuePassThroughSetBound) {
XlaBuilder b(TestName());
auto p0 = ConstantR0<int32_t>(&b, 32);
Shape shape = ShapeUtil::MakeShape(S32, {});
xla::Literal dynamism = xla::LiteralUtil::CreateR0<bool>(false);
xla::Literal bound = xla::LiteralUtil::CreateR0<int32_t>(32);
xla::Literal tuple =
xla::LiteralUtil::MakeTupleOwned(std::move(bound), std::move(dynamism));
auto set_bound =
CustomCall(&b, "SetBound", {p0}, shape, "", false, {}, &tuple);
auto result =
ComputeConstantValueLiteral(set_bound, &b).value().Get<int32_t>({});
EXPECT_TRUE(result.has_value());
EXPECT_EQ(result.value(), 32);
}
TEST_F(ConstValueInferenceTest, ParamaterValuePassThroughSetBound) {
XlaBuilder b(TestName());
auto p0 = Parameter(&b, 0, ShapeUtil::MakeShape(S32, {}), "p0");
Shape shape = ShapeUtil::MakeShape(S32, {});
xla::Literal dynamism = xla::LiteralUtil::CreateR0<bool>(false);
xla::Literal bound = xla::LiteralUtil::CreateR0<int32_t>(32);
xla::Literal tuple =
xla::LiteralUtil::MakeTupleOwned(std::move(bound), std::move(dynamism));
auto set_bound =
CustomCall(&b, "SetBound", {p0}, shape, "", false, {}, &tuple);
auto result =
ComputeConstantValueLiteral(set_bound, &b).value().Get<int32_t>({});
EXPECT_TRUE(result.has_value());
EXPECT_EQ(result.value(), 32);
}
}
} | 2,221 |
#ifndef XLA_CLIENT_LIB_ARITHMETIC_H_
#define XLA_CLIENT_LIB_ARITHMETIC_H_
#include <functional>
#include <memory>
#include <string>
#include "xla/client/xla_builder.h"
#include "xla/client/xla_computation.h"
#include "xla/xla_data.pb.h"
namespace xla {
using XlaOpGenerator = std::function<XlaOp(XlaOp, XlaOp)>;
XlaComputation CreateScalarComputation(const std::string& name,
PrimitiveType type, XlaBuilder* builder,
XlaOpGenerator generator);
XlaComputation CreateScalarAddComputation(PrimitiveType type,
XlaBuilder* builder);
XlaComputation CreateScalarMultiplyComputation(PrimitiveType type,
XlaBuilder* builder);
XlaComputation CreateScalarGeComputation(PrimitiveType type,
XlaBuilder* builder);
XlaComputation CreateScalarMaxComputation(PrimitiveType type,
XlaBuilder* builder);
XlaComputation CreateScalarMinComputation(PrimitiveType type,
XlaBuilder* builder);
XlaComputation CreateScalarAndComputation(PrimitiveType type,
XlaBuilder* builder);
XlaComputation CreateScalarOrComputation(PrimitiveType type,
XlaBuilder* builder);
XlaComputation CreateScalarIdentityWithZeroComputation(PrimitiveType type,
XlaBuilder* builder);
XlaOp Any(XlaOp predicates);
XlaOp ArgMax(XlaOp input, PrimitiveType output_type, int axis);
XlaOp ArgMinMax(XlaOp input, PrimitiveType output_type, int axis, bool is_min);
}
#endif
#include "xla/client/lib/arithmetic.h"
#include <cstdint>
#include <memory>
#include <numeric>
#include <string>
#include <vector>
#include "absl/status/statusor.h"
#include "absl/strings/str_cat.h"
#include "xla/client/lib/constants.h"
#include "xla/client/xla_builder.h"
#include "xla/client/xla_computation.h"
#include "xla/primitive_util.h"
#include "xla/shape.h"
#include "xla/shape_util.h"
#include "xla/xla_data.pb.h"
namespace xla {
XlaComputation CreateScalarComputation(const std::string& name,
PrimitiveType type, XlaBuilder* builder,
XlaOpGenerator generator) {
std::unique_ptr<XlaBuilder> b;
if (type == PRED) {
b = builder->CreateSubBuilder(name);
} else {
b = builder->CreateSubBuilder(
absl::StrCat(name, "_", PrimitiveType_Name(type)));
}
const Shape scalar = ShapeUtil::MakeShape(type, {});
auto lhs = Parameter(b.get(), 0, scalar, "lhs");
auto rhs = Parameter(b.get(), 1, scalar, "rhs");
generator(lhs, rhs);
return b->BuildAndNoteError();
}
XlaComputation CreateScalarAddComputation(PrimitiveType type,
XlaBuilder* builder) {
return CreateScalarComputation(
"add", type, builder, [](XlaOp lhs, XlaOp rhs) { return Add(lhs, rhs); });
}
XlaComputation CreateScalarMultiplyComputation(PrimitiveType type,
XlaBuilder* builder) {
return CreateScalarComputation(
"mul", type, builder, [](XlaOp lhs, XlaOp rhs) { return Mul(lhs, rhs); });
}
XlaComputation CreateScalarGeComputation(PrimitiveType type,
XlaBuilder* builder) {
return CreateScalarComputation(
"ge", type, builder, [](XlaOp lhs, XlaOp rhs) { return Ge(lhs, rhs); });
}
XlaComputation CreateScalarMaxComputation(PrimitiveType type,
XlaBuilder* builder) {
return CreateScalarComputation(
"max", type, builder, [](XlaOp lhs, XlaOp rhs) { return Max(lhs, rhs); });
}
XlaComputation CreateScalarMinComputation(PrimitiveType type,
XlaBuilder* builder) {
return CreateScalarComputation(
"min", type, builder, [](XlaOp lhs, XlaOp rhs) { return Min(lhs, rhs); });
}
XlaComputation CreateScalarAndComputation(PrimitiveType type,
XlaBuilder* builder) {
return CreateScalarComputation(
"and", type, builder, [](XlaOp lhs, XlaOp rhs) { return And(lhs, rhs); });
}
XlaComputation CreateScalarOrComputation(PrimitiveType type,
XlaBuilder* builder) {
return CreateScalarComputation(
"or", type, builder, [](XlaOp lhs, XlaOp rhs) { return Or(lhs, rhs); });
}
XlaComputation CreateScalarIdentityWithZeroComputation(PrimitiveType type,
XlaBuilder* builder) {
XlaComputation reducer =
(primitive_util::IsIntegralType(type) || type == PRED)
? CreateScalarOrComputation(type, builder)
: CreateScalarAddComputation(type, builder);
return reducer;
}
XlaOp Any(XlaOp predicates) {
XlaBuilder* builder = predicates.builder();
return builder->ReportErrorOrReturn([&]() -> absl::StatusOr<XlaOp> {
auto f = ConstantR0<bool>(builder, false);
XlaComputation logical_or = CreateScalarOrComputation(PRED, builder);
TF_ASSIGN_OR_RETURN(const Shape& predicates_shape,
builder->GetShape(predicates));
std::vector<int64_t> all_dimensions(predicates_shape.rank());
std::iota(all_dimensions.begin(), all_dimensions.end(), 0);
return Reduce(predicates, f, logical_or, all_dimensions);
});
}
static XlaComputation CreateMinMaxComputation(XlaBuilder* outer_builder,
PrimitiveType value_type,
PrimitiveType index_type,
bool is_min) {
auto sub_builder = outer_builder->CreateSubBuilder("minmax_func");
XlaBuilder* b = sub_builder.get();
XlaOp lhs_value =
Parameter(b, 0, ShapeUtil::MakeShape(value_type, {}), "lhs_value");
XlaOp lhs_index =
Parameter(b, 1, ShapeUtil::MakeShape(index_type, {}), "lhs_index");
XlaOp rhs_value =
Parameter(b, 2, ShapeUtil::MakeShape(value_type, {}), "rhs_value");
XlaOp rhs_index =
Parameter(b, 3, ShapeUtil::MakeShape(index_type, {}), "rhs_index");
XlaOp cmp = is_min ? Le(lhs_value, rhs_value) : Ge(lhs_value, rhs_value);
XlaOp max = Select(cmp, lhs_value, rhs_value);
XlaOp arg_max = Select(cmp, lhs_index, rhs_index);
XlaOp eq = Eq(lhs_value, rhs_value);
XlaOp tie_id = Min(lhs_index, rhs_index);
arg_max = Select(eq, tie_id, arg_max);
Tuple(b, {max, arg_max});
return b->BuildAndNoteError();
}
XlaOp ArgMinMax(XlaOp input, PrimitiveType output_type, int axis, bool is_min) {
XlaBuilder* builder = input.builder();
return builder->ReportErrorOrReturn([&]() -> absl::StatusOr<XlaOp> {
TF_ASSIGN_OR_RETURN(Shape input_shape, builder->GetShape(input));
XlaOp value_init_value;
if (is_min) {
value_init_value = MaxValue(builder, input_shape.element_type());
} else {
value_init_value = MinValue(builder, input_shape.element_type());
}
int64_t dimension_size = input_shape.dimensions(axis);
auto index_type = dimension_size <= INT32_MAX ? S32 : output_type;
XlaOp index_init_value = Zero(builder, index_type);
auto iota_shape =
ShapeUtil::MakeShape(index_type, input_shape.dimensions());
XlaOp iota = Iota(builder, iota_shape, axis);
XlaComputation reducer = CreateMinMaxComputation(
builder, input_shape.element_type(), index_type, is_min);
XlaOp max_argmax = Reduce(builder, {input, iota},
{value_init_value, index_init_value}, reducer,
{axis});
XlaOp argmax = GetTupleElement(max_argmax, 1);
if (index_type != output_type) {
argmax = ConvertElementType(argmax, output_type);
}
return argmax;
});
}
XlaOp ArgMax(XlaOp input, PrimitiveType output_type, int axis) {
return ArgMinMax(input, output_type, axis, false);
}
} | #include "xla/client/lib/arithmetic.h"
#include <functional>
#include <initializer_list>
#include "xla/client/xla_builder.h"
#include "xla/literal_util.h"
#include "xla/primitive_util.h"
#include "xla/test.h"
#include "xla/tests/client_library_test_base.h"
#include "xla/tests/test_macros.h"
#include "xla/types.h"
#include "xla/xla_data.pb.h"
namespace xla {
namespace {
class ArithmeticTest : public ClientLibraryTestBase {
public:
template <typename NativeT>
void TestArgMin(std::initializer_list<std::initializer_list<NativeT>> input,
absl::Span<NativeT const> expected_output, int axis) {
TestArgMinMax(input, expected_output, axis, true);
}
template <typename NativeT>
void TestArgMax(std::initializer_list<std::initializer_list<NativeT>> input,
absl::Span<NativeT const> expected_output, int axis) {
TestArgMinMax(input, expected_output, axis, false);
}
private:
template <typename NativeT>
void TestArgMinMax(
std::initializer_list<std::initializer_list<NativeT>> input,
absl::Span<NativeT const> expected_output, int axis, bool is_min) {
XlaBuilder builder(TestName());
XlaOp x = ConstantR2<NativeT>(&builder, input);
ArgMinMax(x, primitive_util::NativeToPrimitiveType<NativeT>(), axis,
is_min);
ComputeAndCompareR1<NativeT>(&builder, expected_output, {});
}
template <typename NativeT>
void TestArgMinMaxImpl(
std::initializer_list<std::initializer_list<NativeT>> input,
absl::Span<NativeT const> expected_output,
std::function<void(XlaOp, PrimitiveType)> MinMaxImpl) {}
};
XLA_TEST_F(ArithmeticTest, ArgMinR2Axis0) {
TestArgMin<int32_t>({{1, 7, 4}, {6, 3, 5}, {8, 3, 3}}, {0, 1, 2},
0);
}
XLA_TEST_F(ArithmeticTest, ArgMinR2Axis1) {
TestArgMin<int32_t>({{1, 7, 4}, {6, 3, 5}, {8, 3, 3}}, {0, 1, 1},
1);
}
XLA_TEST_F(ArithmeticTest, ArgMaxR2Axis0) {
TestArgMax<int32_t>({{1, 7, 4}, {6, 3, 5}, {8, 3, 3}}, {2, 0, 1},
0);
}
XLA_TEST_F(ArithmeticTest, ArgMaxR2Axis1) {
TestArgMax<int32_t>({{1, 7, 4}, {6, 3, 5}, {8, 3, 3}}, {1, 0, 0},
1);
}
}
} | 2,222 |
#ifndef XLA_CLIENT_LIB_LOGDET_H_
#define XLA_CLIENT_LIB_LOGDET_H_
#include "xla/client/xla_builder.h"
namespace xla {
struct SignAndLogDet {
XlaOp sign;
XlaOp logdet;
};
SignAndLogDet SLogDet(XlaOp a);
XlaOp LogDet(XlaOp a);
}
#endif
#include "xla/client/lib/logdet.h"
#include <limits>
#include <memory>
#include <vector>
#include "absl/status/statusor.h"
#include "xla/client/lib/arithmetic.h"
#include "xla/client/lib/constants.h"
#include "xla/client/lib/loops.h"
#include "xla/client/lib/math.h"
#include "xla/client/lib/matrix.h"
#include "xla/client/lib/qr.h"
#include "xla/client/lib/slicing.h"
#include "xla/client/xla_builder.h"
#include "xla/literal_util.h"
#include "xla/shape_util.h"
#include "xla/status_macros.h"
#include "tsl/platform/errors.h"
namespace xla {
SignAndLogDet SLogDet(XlaOp a) {
absl::StatusOr<SignAndLogDet> result =
[&]() -> absl::StatusOr<SignAndLogDet> {
TF_ASSIGN_OR_RETURN(Shape a_shape, a.builder()->GetShape(a));
auto qr = Qr(a);
int64_t m = ShapeUtil::GetDimension(a_shape, -2);
int64_t n = ShapeUtil::GetDimension(a_shape, -1);
if (m != n) {
return InvalidArgument(
"Arguments to logdet must be (batched) square matrices, got: %s",
a_shape.ToString());
}
auto log_abs_det = Einsum(Log(Abs(qr.q_and_r)), "...aa->...");
auto sign_diag = Reduce(
Sign(Einsum(qr.q_and_r, "...aa->...a")),
One(a.builder(), a_shape.element_type()),
CreateScalarMultiplyComputation(a_shape.element_type(), a.builder()),
{a_shape.rank() - 2});
auto sliced_taus = SliceInMinorDims(qr.taus, {0}, {n - 1});
auto sign_taus = Reduce(
Select(Ne(sliced_taus, ZerosLike(sliced_taus)),
FullLike(sliced_taus, -1), FullLike(sliced_taus, 1)),
One(a.builder(), a_shape.element_type()),
CreateScalarMultiplyComputation(a_shape.element_type(), a.builder()),
{a_shape.rank() - 2});
return SignAndLogDet{sign_diag * sign_taus, log_abs_det};
}();
if (!result.ok()) {
XlaOp error = a.builder()->ReportError(result.status());
return SignAndLogDet{error, error};
}
return result.value();
}
XlaOp LogDet(XlaOp a) {
SignAndLogDet slogdet = SLogDet(a);
return Select(
Ge(slogdet.sign, ZerosLike(slogdet.sign)), slogdet.logdet,
FullLike(slogdet.logdet, std::numeric_limits<float>::quiet_NaN()));
}
} | #include "xla/client/lib/logdet.h"
#include <limits>
#include "absl/status/statusor.h"
#include "xla/array2d.h"
#include "xla/array3d.h"
#include "xla/client/lib/matrix.h"
#include "xla/client/xla_builder.h"
#include "xla/literal.h"
#include "xla/test.h"
#include "xla/tests/client_library_test_base.h"
#include "xla/tests/literal_test_util.h"
#include "xla/tests/test_macros.h"
#include "tsl/lib/core/status_test_util.h"
namespace {
using LogDetTest = xla::ClientLibraryTestBase;
XLA_TEST_F(LogDetTest, Simple) {
xla::XlaBuilder builder(TestName());
xla::Array2D<float> a_vals({
{4, 6, 8, 10},
{6, 45, 54, 63},
{8, 54, 146, 166},
{10, 63, 166, 310},
});
xla::XlaOp a;
auto a_data = CreateR2Parameter<float>(a_vals, 0, "a", &builder, &a);
xla::SignAndLogDet slogdet = xla::SLogDet(a);
xla::XlaOp logdet = xla::LogDet(a);
xla::Tuple(&builder, {slogdet.sign, slogdet.logdet, logdet});
xla::Literal expected = xla::LiteralUtil::MakeTupleOwned(
xla::LiteralUtil::CreateR0<float>(1.f),
xla::LiteralUtil::CreateR0<float>(14.1601f),
xla::LiteralUtil::CreateR0<float>(14.1601f));
ComputeAndCompareLiteral(&builder, expected, {a_data.get()},
xla::ErrorSpec(1e-4));
}
XLA_TEST_F(LogDetTest, SimpleTriangle) {
xla::XlaBuilder builder(TestName());
xla::Array2D<float> a_vals({
{4, 6, 8, 10},
{4, -39, 62, 73},
{0, 0, -146, 166},
{4, 6, 8, 320},
});
xla::XlaOp a;
auto a_data = CreateR2Parameter<float>(a_vals, 0, "a", &builder, &a);
xla::SignAndLogDet slogdet = xla::SLogDet(a);
xla::XlaOp logdet = xla::LogDet(a);
xla::Tuple(&builder, {slogdet.sign, slogdet.logdet, logdet});
xla::Literal expected = xla::LiteralUtil::MakeTupleOwned(
xla::LiteralUtil::CreateR0<float>(1.f),
xla::LiteralUtil::CreateR0<float>(15.9131355f),
xla::LiteralUtil::CreateR0<float>(15.9131355f));
ComputeAndCompareLiteral(&builder, expected, {a_data.get()},
xla::ErrorSpec(1e-4));
}
XLA_TEST_F(LogDetTest, SimpleBatched) {
xla::XlaBuilder builder(TestName());
xla::Array3D<float> a_vals({
{
{4, 6, 8, 10},
{6, 45, 54, 63},
{8, 54, 146, 166},
{10, 63, 166, 310},
},
{
{16, 24, 8, 12},
{24, 61, 82, 48},
{8, 82, 456, 106},
{12, 48, 106, 62},
},
{{2, 2, 3, 4}, {4, 5, 6, 7}, {7, 8, 9, 8}, {10, 11, 12, 13}},
{{0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}},
});
xla::XlaOp a;
auto a_data = CreateR3Parameter<float>(a_vals, 0, "a", &builder, &a);
xla::SignAndLogDet slogdet = xla::SLogDet(a);
xla::XlaOp logdet = xla::LogDet(a);
xla::Tuple(&builder, {slogdet.sign, slogdet.logdet, logdet});
xla::Literal expected = xla::LiteralUtil::MakeTupleOwned(
xla::LiteralUtil::CreateR1<float>({1.f, 1.f, -1.f, 0.f}),
xla::LiteralUtil::CreateR1<float>(
{14.1601f, 14.3092f, 2.4849f,
-std::numeric_limits<float>::infinity()}),
xla::LiteralUtil::CreateR1<float>(
{14.1601f, 14.3092f, std::numeric_limits<float>::quiet_NaN(),
-std::numeric_limits<float>::infinity()}));
ComputeAndCompareLiteral(&builder, expected, {a_data.get()},
xla::ErrorSpec(1e-4));
}
XLA_TEST_F(LogDetTest, LogdetOfLargerMatricesBatched) {
xla::XlaBuilder builder(TestName());
xla::Array<float> a_vals = {
{{7.2393, 1.1413, 4.1883, -4.8272, 3.2831, -0.0568, -2.4776},
{0.4347, 3.4095, 1.6259, -4.7100, 1.5942, 1.4217, -2.8009},
{3.6964, 0.4882, 6.5276, -1.2128, 1.3851, 0.7417, -3.8515},
{-3.7986, -5.1188, -1.9410, 14.0205, -5.4515, 3.1831, 5.1488},
{1.5621, 3.0426, 1.4819, -4.5938, 10.1397, 4.9312, -2.8351},
{-1.5436, -0.0287, -0.1139, 4.4499, 2.5894, 6.1216, 2.7201},
{-3.7241, -2.7670, -3.8162, 4.5961, -1.7251, -0.4190, 8.6562}},
{{3.3789, -2.3607, -1.2471, 2.1503, 0.6062, -0.6057, 1.7748},
{-1.8670, 11.0947, 0.1229, 0.0599, 3.1714, -4.7941, -4.5442},
{-0.6905, -0.0829, 5.2156, 2.9528, 2.6200, 6.1638, 1.8652},
{3.0521, 2.2174, 0.7444, 10.7268, 0.6443, -2.7732, 1.6840},
{1.8479, 3.0821, 4.5671, 2.9254, 6.1338, 5.2066, 2.3662},
{-0.0360, -5.5341, 5.9687, -0.3297, 2.1174, 13.0016, 4.0118},
{0.4380, -4.6683, 3.1548, 0.0924, 0.7176, 6.4679, 6.1819}},
{{10.0487, 4.0350, -0.8471, -1.2887, -0.8172, -3.3698, 1.3191},
{4.8678, 4.6081, 0.8419, -0.2454, -3.2599, -1.2386, 2.4070},
{1.4877, 0.8362, 2.6077, 1.1782, -0.1116, 1.7130, -1.1883},
{-0.9245, -0.7435, -0.9456, 2.5936, 1.9887, -0.1324, -0.1453},
{0.2918, -0.5301, -0.8775, 1.0478, 8.9262, 2.4731, -0.4393},
{-3.5759, -1.5619, 2.4410, 1.3046, 4.2678, 7.3587, -4.0935},
{-1.1187, 0.9150, -1.8253, 0.0390, -2.5684, -4.0778, 4.1447}}};
xla::XlaOp a;
auto a_data = CreateParameter<float>(a_vals, 0, "a", &builder, &a);
xla::SignAndLogDet slogdet = xla::SLogDet(a);
xla::XlaOp logdet = xla::LogDet(a);
xla::Tuple(&builder, {slogdet.sign, slogdet.logdet, logdet});
xla::Literal expected = xla::LiteralUtil::MakeTupleOwned(
xla::LiteralUtil::CreateR1<float>({1.f, 1.f, 1.f}),
xla::LiteralUtil::CreateR1<float>({8.93788053, 6.77846303, 7.4852403}),
xla::LiteralUtil::CreateR1<float>({8.93788053, 6.77846303, 7.4852403}));
ComputeAndCompareLiteral(&builder, expected, {a_data.get()},
xla::ErrorSpec(1e-4));
}
} | 2,223 |
#include <functional>
#include "absl/types/span.h"
#include "xla/client/xla_builder.h"
#include "xla/types.h"
#ifndef XLA_CLIENT_LIB_SLICING_H_
#define XLA_CLIENT_LIB_SLICING_H_
namespace xla {
XlaOp DynamicStridedSlice(XlaOp input, absl::Span<const XlaOp> base_indices,
absl::Span<const int64_t> window_sizes,
absl::Span<const int64_t> strides);
XlaOp UpdateSlice(XlaOp x, XlaOp update, absl::Span<const int64_t> start);
XlaOp SliceInMinorDims(XlaOp x, absl::Span<const int64_t> start,
absl::Span<const int64_t> end);
XlaOp UpdateSliceInMinorDims(XlaOp x, XlaOp update,
absl::Span<const int64_t> start);
XlaOp DynamicSliceInMinorDims(XlaOp x, absl::Span<const XlaOp> starts,
absl::Span<const int64_t> sizes);
XlaOp DynamicUpdateSliceInMinorDims(XlaOp x, XlaOp update,
absl::Span<const XlaOp> starts);
XlaOp TorchGather(XlaOp input, XlaOp index, int64_t dim, bool sparse = true);
XlaOp TorchScatterDense(XlaOp input, XlaOp index, XlaOp src, int64_t dim,
const std::function<XlaOp(XlaOp, XlaOp)>& combiner);
XlaOp TorchIndexSelect(XlaOp input, XlaOp index, int64_t dim,
int64_t batch_dims = 0);
}
#endif
#include "xla/client/lib/slicing.h"
#include <algorithm>
#include <cstdint>
#include <functional>
#include <limits>
#include <vector>
#include "absl/status/statusor.h"
#include "absl/types/span.h"
#include "xla/client/lib/arithmetic.h"
#include "xla/client/lib/constants.h"
#include "xla/client/xla_builder.h"
#include "xla/shape.h"
#include "xla/shape_util.h"
#include "xla/status_macros.h"
#include "xla/util.h"
namespace xla {
XlaOp DynamicStridedSlice(XlaOp input, absl::Span<const XlaOp> base_indices,
absl::Span<const int64_t> window_sizes,
absl::Span<const int64_t> strides) {
XlaOp sliced_input = DynamicSlice(input, base_indices, window_sizes);
if (std::any_of(strides.begin(), strides.end(),
[](int64_t stride) { return stride != 1; })) {
sliced_input =
Slice(sliced_input, std::vector<int64_t>(window_sizes.size()),
window_sizes, strides);
}
return sliced_input;
}
XlaOp SliceInMinorDims(XlaOp x, absl::Span<const int64_t> start,
absl::Span<const int64_t> end) {
XlaBuilder* builder = x.builder();
return builder->ReportErrorOrReturn([&]() -> absl::StatusOr<XlaOp> {
TF_RET_CHECK(start.size() == end.size());
int64_t n_minor_dims = start.size();
TF_ASSIGN_OR_RETURN(Shape shape, builder->GetShape(x));
const int64_t n_dims = shape.rank();
TF_RET_CHECK(n_minor_dims <= n_dims);
auto major_dims = shape.dimensions().subspan(
0,
n_dims - n_minor_dims);
std::vector<int64_t> padded_start(n_dims, 0);
std::copy(start.begin(), start.end(),
padded_start.begin() + major_dims.size());
std::vector<int64_t> padded_end(n_dims);
std::copy(major_dims.begin(), major_dims.end(), padded_end.begin());
std::copy(end.begin(), end.end(), padded_end.begin() + major_dims.size());
std::vector<int64_t> strides(n_dims, 1);
return Slice(x, padded_start, padded_end, strides);
});
}
XlaOp UpdateSlice(XlaOp x, XlaOp update, absl::Span<const int64_t> start) {
XlaBuilder* builder = x.builder();
return builder->ReportErrorOrReturn([&]() -> absl::StatusOr<XlaOp> {
TF_ASSIGN_OR_RETURN(Shape shape, builder->GetShape(x));
const int64_t n_dims = shape.rank();
const int64_t start_size = start.size();
TF_RET_CHECK(start_size == n_dims);
std::vector<int32_t> start_as_int32(start.begin(), start.end());
std::vector<XlaOp> start_ops(start.size());
for (int i = 0, end = start.size(); i < end; ++i) {
start_ops[i] = ConstantR0(builder, start_as_int32[i]);
}
return DynamicUpdateSlice(x, update, start_ops);
});
}
XlaOp UpdateSliceInMinorDims(XlaOp x, XlaOp update,
absl::Span<const int64_t> start) {
XlaBuilder* builder = x.builder();
return builder->ReportErrorOrReturn([&]() -> absl::StatusOr<XlaOp> {
TF_ASSIGN_OR_RETURN(Shape shape, builder->GetShape(x));
const int64_t n_dims = shape.rank();
const int64_t n_minor_dims = start.size();
TF_RET_CHECK(n_minor_dims <= n_dims);
std::vector<int64_t> padded_start(n_dims, 0);
std::copy(start.begin(), start.end(),
padded_start.begin() + (n_dims - n_minor_dims));
return UpdateSlice(x, update, padded_start);
});
}
namespace {
std::vector<int64_t> ConcatVectors(absl::Span<const int64_t> xs,
absl::Span<const int64_t> ys) {
std::vector<int64_t> output(xs.size() + ys.size());
std::copy(xs.begin(), xs.end(), output.begin());
std::copy(ys.begin(), ys.end(), output.begin() + xs.size());
return output;
}
absl::StatusOr<std::vector<XlaOp>> PrependZerosInMajorDims(
XlaOp x, absl::Span<const XlaOp> starts) {
XlaBuilder* builder = x.builder();
TF_ASSIGN_OR_RETURN(Shape shape, builder->GetShape(x));
const int64_t n_dims = shape.rank();
auto zero = ConstantR0<int32_t>(builder, 0);
std::vector<XlaOp> padded_starts(n_dims, zero);
for (int i = 0; i < starts.size(); ++i) {
padded_starts[n_dims - starts.size() + i] = starts[i];
}
return padded_starts;
}
}
XlaOp DynamicSliceInMinorDims(XlaOp x, absl::Span<const XlaOp> starts,
absl::Span<const int64_t> sizes) {
XlaBuilder* builder = x.builder();
return builder->ReportErrorOrReturn([&]() -> absl::StatusOr<XlaOp> {
TF_ASSIGN_OR_RETURN(Shape shape, builder->GetShape(x));
const int64_t n_dims = shape.rank();
int64_t n_minor_dims = starts.size();
TF_RET_CHECK(n_minor_dims == sizes.size());
TF_RET_CHECK(n_minor_dims <= n_dims);
auto major_dims = shape.dimensions().subspan(
0,
n_dims - sizes.size());
TF_ASSIGN_OR_RETURN(auto padded_starts, PrependZerosInMajorDims(x, starts));
auto padded_sizes = ConcatVectors(major_dims, sizes);
return DynamicSlice(x, padded_starts, padded_sizes);
});
}
XlaOp DynamicUpdateSliceInMinorDims(XlaOp x, XlaOp update,
absl::Span<const XlaOp> starts) {
XlaBuilder* builder = x.builder();
return builder->ReportErrorOrReturn([&]() -> absl::StatusOr<XlaOp> {
TF_ASSIGN_OR_RETURN(auto padded_starts, PrependZerosInMajorDims(x, starts));
return DynamicUpdateSlice(x, update, padded_starts);
});
}
XlaOp TorchGather(XlaOp input, XlaOp index, int64_t dim, bool sparse) {
XlaBuilder* builder = input.builder();
return builder->ReportErrorOrReturn([&]() -> absl::StatusOr<XlaOp> {
TF_ASSIGN_OR_RETURN(Shape index_shape, builder->GetShape(index));
TF_ASSIGN_OR_RETURN(Shape input_shape, builder->GetShape(input));
if (ShapeUtil::ElementHasBitWidth(index_shape, 64) &&
input_shape.dimensions(dim) < std::numeric_limits<uint32_t>::max()) {
index = ConvertElementType(index, U32);
index_shape.set_element_type(U32);
}
if (index_shape.rank() == 1) {
return TorchIndexSelect(input, index, 0);
}
if (!sparse) {
std::vector<int64_t> index_broadcast_dims;
std::vector<int64_t> input_broadcast_dims;
std::vector<int64_t> sizes;
sizes.reserve(index_shape.rank());
for (int64_t i = 0; i < index_shape.rank(); ++i) {
if (i < dim) {
input_broadcast_dims.push_back(i);
index_broadcast_dims.push_back(i);
} else if (i == dim) {
sizes.push_back(input_shape.dimensions(i));
input_broadcast_dims.push_back(i);
index_broadcast_dims.push_back(i + 1);
} else {
input_broadcast_dims.push_back(i + 1);
index_broadcast_dims.push_back(i + 1);
}
sizes.push_back(index_shape.dimensions(i));
}
auto mask = Eq(
BroadcastInDim(index, sizes, index_broadcast_dims),
Iota(builder, ShapeUtil::MakeShape(index_shape.element_type(), sizes),
dim));
auto masked_input = Select(
mask, BroadcastInDim(input, sizes, input_broadcast_dims),
Zeros(builder,
ShapeUtil::MakeShape(input_shape.element_type(), sizes)));
return Reduce(masked_input, Zero(builder, input_shape.element_type()),
CreateScalarIdentityWithZeroComputation(
input_shape.element_type(), builder),
{dim});
}
ShapeUtil::AppendMajorDimension(1, &index_shape);
std::vector<XlaOp> to_concat;
to_concat.reserve(input_shape.rank());
for (int64_t i = 0; i < input_shape.rank(); ++i) {
if (i == dim) {
to_concat.push_back(Reshape(index, index_shape.dimensions()));
} else {
to_concat.push_back(Iota(builder, index_shape, i));
}
}
XlaOp gather_indices = ConcatInDim(builder, to_concat, input_shape.rank());
std::vector<int64_t> slice_sizes(input_shape.rank(), 1);
GatherDimensionNumbers gather_dnums;
gather_dnums.set_index_vector_dim(input_shape.rank());
for (int64_t i = 0; i < input_shape.rank(); ++i) {
gather_dnums.add_collapsed_slice_dims(i);
gather_dnums.add_start_index_map(i);
}
return Gather(input, gather_indices, gather_dnums, slice_sizes);
});
}
XlaOp TorchScatterDense(XlaOp input, XlaOp index, XlaOp src, int64_t dim,
const std::function<XlaOp(XlaOp, XlaOp)>& combiner) {
XlaBuilder* builder = input.builder();
return builder->ReportErrorOrReturn([&]() -> absl::StatusOr<XlaOp> {
TF_ASSIGN_OR_RETURN(Shape index_shape, builder->GetShape(index));
TF_ASSIGN_OR_RETURN(Shape input_shape, builder->GetShape(input));
std::vector<int64_t> index_broadcast_dims;
std::vector<int64_t> sizes;
const auto rank = index_shape.rank();
sizes.reserve(rank + 1);
for (int64_t i = 0; i < index_shape.rank(); ++i) {
if (i < dim) {
index_broadcast_dims.push_back(i);
} else {
if (i == dim) {
sizes.push_back(input_shape.dimensions(i));
}
index_broadcast_dims.push_back(i + 1);
}
sizes.push_back(index_shape.dimensions(i));
}
auto mask =
Eq(BroadcastInDim(index, sizes, index_broadcast_dims),
Iota(builder,
ShapeUtil::MakeShape(index_shape.element_type(), sizes), dim));
auto masked_src =
Select(mask, BroadcastInDim(src, sizes, index_broadcast_dims),
Zeros(builder,
ShapeUtil::MakeShape(input_shape.element_type(), sizes)));
return combiner(
input,
Reduce(masked_src, Zero(builder, input_shape.element_type()),
CreateScalarComputation("reducer", input_shape.element_type(),
builder, combiner),
{dim + 1}));
});
}
XlaOp TorchIndexSelect(XlaOp input, XlaOp index, int64_t dim,
int64_t batch_dims) {
XlaBuilder* builder = input.builder();
return builder->ReportErrorOrReturn([&]() -> absl::StatusOr<XlaOp> {
TF_ASSIGN_OR_RETURN(Shape input_shape, builder->GetShape(input));
TF_ASSIGN_OR_RETURN(Shape index_shape, builder->GetShape(index));
if (dim < batch_dims) {
return InvalidArgument(
"Gather dim must be greater than or equal to the number of batch "
"dims");
}
if (ShapeUtil::ElementHasBitWidth(index_shape, 64) &&
input_shape.dimensions(dim) < std::numeric_limits<uint32_t>::max()) {
index = ConvertElementType(index, U32);
index_shape.set_element_type(U32);
}
std::vector<int64_t> slice_sizes = SpanToVector(input_shape.dimensions());
GatherDimensionNumbers gather_dnums;
gather_dnums.set_index_vector_dim(index_shape.rank());
if (batch_dims > 0) {
ShapeUtil::AppendMajorDimension(1, &index_shape);
std::vector<XlaOp> to_concat;
to_concat.reserve(batch_dims + 1);
xla::Shape iota_shape = xla::ShapeUtil::MakeStaticShape(index_shape);
for (int64_t batch_dim = 0; batch_dim < batch_dims; ++batch_dim) {
to_concat.push_back(Iota(builder, iota_shape, batch_dim));
}
to_concat.push_back(Reshape(index, index_shape.dimensions()));
index = ConcatInDim(builder, to_concat, gather_dnums.index_vector_dim());
}
for (int64_t i = 0; i < input_shape.rank(); ++i) {
if (i < batch_dims || i == dim) {
slice_sizes[i] = std::min<int64_t>(slice_sizes[i], 1);
gather_dnums.add_collapsed_slice_dims(i);
gather_dnums.add_start_index_map(i);
} else {
if (i < dim) {
gather_dnums.add_offset_dims(i);
} else {
gather_dnums.add_offset_dims(i + gather_dnums.index_vector_dim() -
(1 + batch_dims));
}
}
}
return Gather(input, index, gather_dnums, slice_sizes);
});
}
} | #include "xla/client/lib/slicing.h"
#include "xla/client/xla_builder.h"
#include "xla/literal.h"
#include "xla/literal_util.h"
#include "xla/shape_util.h"
#include "xla/test.h"
#include "xla/tests/client_library_test_base.h"
#include "xla/tests/test_macros.h"
#include "xla/types.h"
namespace xla {
namespace {
using SlicingTest = xla::ClientLibraryTestBase;
xla::Array2D<float> BValsRight() {
return {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};
}
xla::Array2D<float> BValsLeft() {
return {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12}};
}
xla::Array2D<float> AValsFull() {
return {{2, 0, 1, 2}, {3, 6, 0, 1}, {4, 7, 9, 0}, {5, 8, 10, 11}};
}
xla::Array3D<float> BatchedAValsFull() {
return {{
{2, 0, 1, 2},
{3, 6, 0, 1},
{4, 7, 9, 0},
{5, 8, 10, 11},
},
{
{16, 24, 8, 12},
{24, 61, 82, 48},
{8, 82, 456, 106},
{12, 48, 106, 62},
}};
}
XLA_TEST_F(SlicingTest, Simple2dLookup) {
xla::XlaBuilder builder(TestName());
xla::XlaOp a, x, y;
auto a_data = CreateR2Parameter<float>(BValsRight(), 0, "a", &builder, &a);
auto x_data = CreateR0Parameter<int>(2, 1, "x", &builder, &x);
auto y_data = CreateR0Parameter<int>(1, 2, "y", &builder, &y);
DynamicSliceInMinorDims(a, {x, y}, {1, 1});
ComputeAndCompareR2<float>(&builder, {{10}},
{a_data.get(), x_data.get(), y_data.get()},
xla::ErrorSpec(1e-2, 1e-2));
}
XLA_TEST_F(SlicingTest, Simple3dLookup) {
xla::XlaBuilder builder(TestName());
xla::XlaOp a, index;
auto a_data =
CreateR3Parameter<float>(BatchedAValsFull(), 0, "a", &builder, &a);
auto index_data = CreateR0Parameter<int>(1, 1, "index", &builder, &index);
DynamicSliceInMinorDims(a, {index, xla::ConstantR0<int32_t>(&builder, 0)},
{1, 4});
ComputeAndCompareR3<float>(&builder, {{{3, 6, 0, 1}}, {{24, 61, 82, 48}}},
{a_data.get(), index_data.get()});
}
XLA_TEST_F(SlicingTest, NestedLookup) {
xla::XlaBuilder builder(TestName());
xla::XlaOp a, index;
auto a_data =
CreateR3Parameter<float>(BatchedAValsFull(), 0, "a", &builder, &a);
auto index_data = CreateR0Parameter<int>(1, 1, "index", &builder, &index);
auto slice = DynamicSliceInMinorDims(
a, {index, xla::ConstantR0<int32_t>(&builder, 0)}, {1, 4});
DynamicSliceInMinorDims(slice, {xla::ConstantR0<int32_t>(&builder, 0), index},
{1, 1});
ComputeAndCompareR3<float>(&builder, {{{6}}, {{61}}},
{a_data.get(), index_data.get()});
}
XLA_TEST_F(SlicingTest, SimpleSliceUpdate) {
xla::XlaBuilder builder(TestName());
xla::XlaOp a, b, x, y;
auto a_data = CreateR2Parameter<float>(AValsFull(), 0, "a", &builder, &a);
auto b_data = CreateR2Parameter<float>({{9, 1, -10}}, 1, "b", &builder, &b);
auto x_data = CreateR0Parameter<int>(2, 2, "x", &builder, &x);
auto y_data = CreateR0Parameter<int>(1, 3, "y", &builder, &y);
DynamicUpdateSliceInMinorDims(a, b, {x, y});
xla::Array2D<float> expected(
{{{2, 0, 1, 2}, {3, 6, 0, 1}, {4, 9, 1, -10}, {5, 8, 10, 11}}});
ComputeAndCompareR2<float>(
&builder, expected,
{a_data.get(), b_data.get(), x_data.get(), y_data.get()});
}
XLA_TEST_F(SlicingTest, NestedSliceUpdate) {
xla::XlaBuilder builder(TestName());
xla::XlaOp a, b, x, y;
auto a_data = CreateR2Parameter<float>(AValsFull(), 0, "a", &builder, &a);
auto b_data = CreateR2Parameter<float>({{1, -10}}, 1, "b", &builder, &b);
auto x_data = CreateR0Parameter<int>(2, 2, "x", &builder, &x);
auto y_data = CreateR0Parameter<int>(1, 3, "y", &builder, &y);
auto z = xla::ConstantR0<int32_t>(&builder, 0);
auto slice = DynamicSliceInMinorDims(a, {x, z}, {1, 4});
auto inner = DynamicUpdateSliceInMinorDims(slice, b, {z, y});
DynamicUpdateSlice(a, inner, {x, z});
xla::Array2D<float> expected(
{{{2, 0, 1, 2}, {3, 6, 0, 1}, {4, 1, -10, 0}, {5, 8, 10, 11}}});
ComputeAndCompareR2<float>(
&builder, expected,
{a_data.get(), b_data.get(), x_data.get(), y_data.get()});
}
XLA_TEST_F(SlicingTest, TorchGatherSparse) {
xla::XlaBuilder builder(TestName());
xla::XlaOp input, index;
auto input_data =
CreateR2Parameter<int>({{1, 2}, {3, 4}}, 0, "input", &builder, &input);
auto index_data =
CreateR2Parameter<int>({{0, 0}, {1, 0}}, 1, "index", &builder, &index);
TorchGather(input, index, 1);
ComputeAndCompareR2<int>(&builder, {{1, 1}, {4, 3}},
{input_data.get(), index_data.get()});
}
XLA_TEST_F(SlicingTest, TorchGatherDense) {
xla::XlaBuilder builder(TestName());
xla::XlaOp input, index;
auto input_data =
CreateR2Parameter<int>({{1, 2}, {3, 4}}, 0, "input", &builder, &input);
auto index_data =
CreateR2Parameter<int>({{0, 0}, {1, 0}}, 1, "index", &builder, &index);
TorchGather(input, index, 1, false);
ComputeAndCompareR2<int>(&builder, {{1, 1}, {4, 3}},
{input_data.get(), index_data.get()});
}
XLA_TEST_F(SlicingTest, TorchScatterDense) {
xla::XlaBuilder builder(TestName());
xla::XlaOp src, index, input;
auto input_data = CreateR2Parameter<int>({{0, 0, 0}, {0, 0, 0}}, 0, "input",
&builder, &input);
auto index_data =
CreateR2Parameter<int>({{1, 0}, {1, 2}}, 1, "index", &builder, &index);
auto src_data =
CreateR2Parameter<int>({{1, 2}, {3, 4}}, 2, "src", &builder, &src);
TorchScatterDense(input, index, src, 1,
[](XlaOp l, XlaOp r) { return l + r; });
ComputeAndCompareR2<int>(
&builder, {{2, 1, 0}, {0, 3, 4}},
{input_data.get(), index_data.get(), src_data.get()});
}
XLA_TEST_F(SlicingTest, TorchIndexSelectOn0) {
xla::XlaBuilder builder(TestName());
xla::XlaOp input, index;
auto input_data =
CreateR2Parameter<float>({{0.1427, 0.0231, -0.5414, -1.0009},
{-0.4664, 0.2647, -0.1228, -1.1068},
{-1.1734, -0.6571, 0.7230, -0.6004}},
0, "input", &builder, &input);
auto index_data =
CreateR1Parameter<int>({0, 2}, 1, "index", &builder, &index);
TorchIndexSelect(input, index, 0);
ComputeAndCompareR2<float>(
&builder,
{{0.1427, 0.0231, -0.5414, -1.0009}, {-1.1734, -0.6571, 0.7230, -0.6004}},
{input_data.get(), index_data.get()});
}
XLA_TEST_F(SlicingTest, TorchIndexSelectOn0Size1) {
xla::XlaBuilder builder(TestName());
xla::XlaOp input, index;
auto input_data = CreateR2Parameter<float>(
{{-1.1734, -0.6571, 0.7230, -0.6004}}, 0, "input", &builder, &input);
auto index_data =
CreateR1Parameter<int>({0, 0, 0, 0, 0, 0}, 1, "index", &builder, &index);
TorchIndexSelect(input, index, 0);
ComputeAndCompareR2<float>(&builder,
{{-1.1734, -0.6571, 0.7230, -0.6004},
{-1.1734, -0.6571, 0.7230, -0.6004},
{-1.1734, -0.6571, 0.7230, -0.6004},
{-1.1734, -0.6571, 0.7230, -0.6004},
{-1.1734, -0.6571, 0.7230, -0.6004},
{-1.1734, -0.6571, 0.7230, -0.6004}},
{input_data.get(), index_data.get()});
}
XLA_TEST_F(SlicingTest, TorchIndexSelectOn1) {
xla::XlaBuilder builder(TestName());
xla::XlaOp input, index;
auto input_data =
CreateR2Parameter<float>({{0.1427, 0.0231, -0.5414, -1.0009},
{-0.4664, 0.2647, -0.1228, -1.1068},
{-1.1734, -0.6571, 0.7230, -0.6004}},
0, "input", &builder, &input);
auto index_data =
CreateR1Parameter<int>({0, 2}, 1, "index", &builder, &index);
TorchIndexSelect(input, index, 1);
ComputeAndCompareR2<float>(
&builder, {{0.1427, -0.5414}, {-0.4664, -0.1228}, {-1.1734, 0.7230}},
{input_data.get(), index_data.get()});
}
XLA_TEST_F(SlicingTest, EmptyIndexSelect) {
xla::XlaBuilder builder(TestName());
xla::XlaOp input, index;
auto input_data =
CreateR2Parameter<float>({{0}, {0}, {0}}, 0, "input", &builder, &input);
auto index_data = CreateR1Parameter<int>({}, 1, "index", &builder, &index);
TorchIndexSelect(input, index, 1);
ComputeAndCompareR2<float>(&builder, {{}, {}, {}},
{input_data.get(), index_data.get()});
}
XLA_TEST_F(SlicingTest, DoubleEmptyIndexSelect) {
xla::XlaBuilder builder(TestName());
xla::XlaOp input, index;
Literal l(ShapeUtil::MakeShape(F32, {0, 1, 2, 0}));
Literal i(ShapeUtil::MakeShape(S32, {0}));
TF_ASSERT_OK_AND_ASSIGN(
auto input_data,
CreateParameterAndTransferLiteral(0, l, "input", &builder, &input));
TF_ASSERT_OK_AND_ASSIGN(
auto index_data,
CreateParameterAndTransferLiteral(1, i, "index", &builder, &index));
TorchIndexSelect(input, index, 0);
ComputeAndCompareLiteral(&builder, l, {input_data.get(), index_data.get()});
}
XLA_TEST_F(SlicingTest, EmptyIndexSelectNonZero) {
xla::XlaBuilder builder(TestName());
xla::XlaOp input, index;
Literal l(ShapeUtil::MakeShape(F32, {0, 2}));
TF_ASSERT_OK_AND_ASSIGN(
auto input_data,
CreateParameterAndTransferLiteral(0, l, "input", &builder, &input));
auto index_data =
CreateR1Parameter<int>({0, 0, 0}, 1, "index", &builder, &index);
TorchIndexSelect(input, index, 0);
ComputeAndCompareR2<float>(&builder,
{{0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}},
{input_data.get(), index_data.get()});
}
XLA_TEST_F(SlicingTest, BatchTorchIndexSelectOn0) {
xla::XlaBuilder builder(TestName());
xla::XlaOp input, index;
auto input_data =
CreateR3Parameter<int>({{{0, 1, 2, 3}, {4, 5, 6, 7}, {8, 9, 10, 11}},
{{3, 2, 1, 0}, {7, 6, 5, 4}, {11, 10, 9, 8}}},
0, "input", &builder, &input);
auto index_data =
CreateR2Parameter<int>({{0, 2}, {1, 2}}, 1, "index", &builder, &index);
TorchIndexSelect(input, index, 1, 1);
ComputeAndCompareR3<int>(
&builder,
{{{0, 1, 2, 3}, {8, 9, 10, 11}}, {{7, 6, 5, 4}, {11, 10, 9, 8}}},
{input_data.get(), index_data.get()});
}
}
} | 2,224 |
#ifndef XLA_CLIENT_LIB_QR_H_
#define XLA_CLIENT_LIB_QR_H_
#include "xla/client/xla_builder.h"
#include "xla/xla_data.pb.h"
namespace xla {
struct QrDecomposition {
XlaOp q_and_r;
XlaOp taus;
};
QrDecomposition Qr(XlaOp a);
XlaOp ProductOfElementaryHouseholderReflectors(XlaOp a, XlaOp taus);
void QrExplicit(XlaOp a, bool full_matrices, XlaOp& q, XlaOp& r);
}
#endif
#include "xla/client/lib/qr.h"
#include <algorithm>
#include <memory>
#include <vector>
#include "absl/status/statusor.h"
#include "xla/client/lib/arithmetic.h"
#include "xla/client/lib/constants.h"
#include "xla/client/lib/loops.h"
#include "xla/client/lib/math.h"
#include "xla/client/lib/matrix.h"
#include "xla/client/lib/slicing.h"
#include "xla/client/xla_builder.h"
#include "xla/literal_util.h"
#include "xla/shape_util.h"
#include "xla/status_macros.h"
#include "tsl/platform/errors.h"
namespace xla {
QrDecomposition Qr(XlaOp a) {
auto result = [&]() -> absl::StatusOr<QrDecomposition> {
XlaBuilder* builder = a.builder();
TF_ASSIGN_OR_RETURN(Shape a_shape, builder->GetShape(a));
const int num_dims = a_shape.rank();
if (num_dims < 2) {
return InvalidArgument(
"Arguments to QR must have rank >= 2: got shape %s",
a_shape.ToString());
}
const int64_t m = ShapeUtil::GetDimension(a_shape, -2);
const int64_t n = ShapeUtil::GetDimension(a_shape, -1);
std::vector<int64_t> taus_dims(a_shape.dimensions().begin(),
a_shape.dimensions().end());
taus_dims.pop_back();
taus_dims.back() = std::min(m, n);
auto taus_shape = ShapeUtil::MakeShape(a_shape.element_type(), taus_dims);
Shape qr_shape = ShapeUtil::MakeTupleShape({a_shape, taus_shape});
auto qr = CustomCall(a.builder(), "Qr", {a}, qr_shape);
a = GetTupleElement(qr, 0);
auto taus = GetTupleElement(qr, 1);
return QrDecomposition{a, taus};
}();
if (!result.ok()) {
XlaOp error = a.builder()->ReportError(result.status());
return QrDecomposition{error, error};
}
return result.value();
}
XlaOp ProductOfElementaryHouseholderReflectors(XlaOp a, XlaOp taus) {
XlaBuilder* builder = a.builder();
return builder->ReportErrorOrReturn([&]() -> absl::StatusOr<XlaOp> {
TF_ASSIGN_OR_RETURN(Shape a_shape, builder->GetShape(a));
TF_ASSIGN_OR_RETURN(Shape taus_shape, builder->GetShape(taus));
if (a_shape.rank() < 2) {
return InvalidArgument(
"Matrix `a` must have >= 2 dimensions: got shape %s",
a_shape.ToString());
}
if (taus_shape.rank() + 1 != a_shape.rank()) {
return InvalidArgument(
"Matrix `taus` must have one fewer dimension than `a`: got shapes "
"%s and %s",
taus_shape.ToString(), a_shape.ToString());
}
const int64_t m = ShapeUtil::GetDimension(a_shape, -2);
const int64_t n = ShapeUtil::GetDimension(a_shape, -1);
if (m < n) {
return InvalidArgument(
"Argument to product of elementary Householder "
"reflectors must have m >= n, got shape %s",
a_shape.ToString());
}
absl::Span<const int64_t> a_batch_dims =
absl::MakeConstSpan(a_shape.dimensions().begin(),
a_shape.dimensions().begin() + a_shape.rank() - 2);
absl::Span<const int64_t> taus_batch_dims = absl::MakeConstSpan(
taus_shape.dimensions().begin(),
taus_shape.dimensions().begin() + taus_shape.rank() - 1);
const int64_t k = ShapeUtil::GetDimension(taus_shape, -1);
if (a_shape.element_type() != taus_shape.element_type() ||
a_batch_dims != taus_batch_dims || k > n) {
return InvalidArgument("Invalid shape for `taus`, got a=%s and taus=%s",
taus_shape.ToString(), a_shape.ToString());
}
return CustomCall(a.builder(), "ProductOfElementaryHouseholderReflectors",
{a, taus}, a_shape);
});
}
void QrExplicit(XlaOp a, bool full_matrices, XlaOp& q, XlaOp& r) {
absl::StatusOr<Shape> a_shape_or = a.builder()->GetShape(a);
if (!a_shape_or.ok()) {
q = a.builder()->ReportError(a_shape_or.status());
r = q;
return;
}
Shape a_shape = a_shape_or.value();
const int64_t m = ShapeUtil::GetDimension(a_shape, -2);
const int64_t n = ShapeUtil::GetDimension(a_shape, -1);
const int64_t p = std::min(m, n);
auto qr = Qr(a);
if (full_matrices) {
XlaOp t;
if (m < n) {
t = SliceInMinorDims(qr.q_and_r, {0, 0}, {m, m});
} else {
t = PadInDim(qr.q_and_r, Zero(a.builder(), a_shape.element_type()),
a_shape.dimensions_size() - 1, 0,
m - n);
}
q = ProductOfElementaryHouseholderReflectors(t, qr.taus);
r = UpperTriangle(qr.q_and_r);
} else {
XlaOp t;
if (m < n) {
t = SliceInMinorDims(qr.q_and_r, {0, 0}, {m, m});
} else {
t = qr.q_and_r;
}
q = ProductOfElementaryHouseholderReflectors(t, qr.taus);
q = SliceInMinorDims(q, {0, 0}, {m, p});
r = UpperTriangle(SliceInMinorDims(qr.q_and_r, {0, 0}, {p, n}));
}
}
} | #include "xla/client/lib/qr.h"
#include "absl/status/statusor.h"
#include "xla/array2d.h"
#include "xla/array3d.h"
#include "xla/client/lib/constants.h"
#include "xla/client/lib/matrix.h"
#include "xla/client/xla_builder.h"
#include "xla/literal.h"
#include "xla/test.h"
#include "xla/tests/client_library_test_base.h"
#include "xla/tests/literal_test_util.h"
#include "xla/tests/test_macros.h"
#include "xla/types.h"
#include "xla/xla_data.pb.h"
#include "tsl/lib/core/status_test_util.h"
namespace {
using QrTest = xla::ClientLibraryTestBase;
XLA_TEST_F(QrTest, Simple) {
xla::Array2D<float> data({
{4, 6, 8, 10},
{6, 45, 54, 63},
{8, 54, 146, 166},
{10, 63, 166, 310},
});
for (bool full_matrices : {false, true}) {
for (int64_t m : {3, 4}) {
for (int64_t n : {3, 4}) {
xla::XlaBuilder builder(TestName());
xla::XlaOp a, q, r;
xla::Array<float> a_vals = data.Slice({0, 0}, {m, n});
auto a_data = CreateParameter<float>(a_vals, 0, "a", &builder, &a);
xla::QrExplicit(a, full_matrices, q, r);
xla::BatchDot(q, r, xla::PrecisionConfig::HIGHEST);
TF_ASSERT_OK_AND_ASSIGN(xla::Shape q_shape, builder.GetShape(q));
TF_ASSERT_OK_AND_ASSIGN(xla::Shape r_shape, builder.GetShape(r));
EXPECT_EQ(q_shape,
xla::ShapeUtil::MakeShape(
xla::F32, {m, full_matrices ? m : std::min(m, n)}));
EXPECT_EQ(r_shape,
xla::ShapeUtil::MakeShape(
xla::F32, {full_matrices ? m : std::min(m, n), n}));
ComputeAndCompare<float>(&builder, a_vals, {a_data.get()},
xla::ErrorSpec(1e-4, 1e-4));
}
}
}
}
XLA_TEST_F(QrTest, ZeroDiagonal) {
xla::XlaBuilder builder(TestName());
xla::Array2D<float> a_vals({
{0, 1, 1},
{1, 0, 1},
{1, 1, 0},
});
xla::XlaOp a, q, r;
auto a_data = CreateR2Parameter<float>(a_vals, 0, "a", &builder, &a);
xla::QrExplicit(a, true, q, r);
xla::BatchDot(q, r, xla::PrecisionConfig::HIGHEST);
ComputeAndCompareR2<float>(&builder, a_vals, {a_data.get()},
xla::ErrorSpec(1e-4, 1e-4));
}
XLA_TEST_F(QrTest, SimpleBatched) {
xla::XlaBuilder builder(TestName());
xla::Array3D<float> a_vals({
{
{4, 6, 8, 10},
{6, 45, 54, 63},
{8, 54, 146, 166},
{10, 63, 166, 310},
},
{
{16, 24, 8, 12},
{24, 61, 82, 48},
{8, 82, 456, 106},
{12, 48, 106, 62},
},
});
xla::XlaOp a, q, r;
auto a_data = CreateR3Parameter<float>(a_vals, 0, "a", &builder, &a);
xla::QrExplicit(a, true, q, r);
xla::BatchDot(q, r, xla::PrecisionConfig::HIGHEST);
ComputeAndCompareR3<float>(&builder, a_vals, {a_data.get()},
xla::ErrorSpec(1e-4, 1e-4));
}
XLA_TEST_F(QrTest, SubnormalComplex) {
xla::Array2D<xla::complex64> a_vals({
{xla::complex64(4e-20, 5e-23), 6, 80},
{0, 45, 54},
{0, 54, 146},
});
xla::XlaBuilder builder(TestName());
xla::XlaOp a, q, r;
auto a_data = CreateParameter<xla::complex64>(a_vals, 0, "a", &builder, &a);
xla::QrExplicit(a, true, q, r);
xla::BatchDot(q, r, xla::PrecisionConfig::HIGHEST);
ComputeAndCompare<xla::complex64>(&builder, a_vals, {a_data.get()},
xla::ErrorSpec(1e-4, 1e-4));
}
XLA_TEST_F(QrTest, DuplicateHouseholderExpansion) {
xla::XlaBuilder builder(TestName());
xla::Array2D<float> a0_vals({
{0, 1, 1},
{1, 0, 1},
{1, 1, 0},
});
xla::Array2D<float> a1_vals({
{1, 0},
{0, 1},
{1, 0},
});
xla::XlaOp a0, q0, r0;
auto a0_data = CreateR2Parameter<float>(a0_vals, 0, "a0", &builder, &a0);
xla::QrExplicit(a0, true, q0, r0);
xla::XlaOp a1, q1, r1;
auto a1_data = CreateR2Parameter<float>(a1_vals, 1, "a1", &builder, &a1);
xla::QrExplicit(a1, true, q1, r1);
xla::BatchDot(q1, r1, xla::PrecisionConfig::HIGHEST);
ComputeAndCompareR2<float>(&builder, a1_vals, {a0_data.get(), a1_data.get()},
xla::ErrorSpec(1e-4, 1e-4));
}
} | 2,225 |
#ifndef XLA_CLIENT_LIB_MATRIX_H_
#define XLA_CLIENT_LIB_MATRIX_H_
#include <array>
#include <optional>
#include <string>
#include <vector>
#include "absl/status/statusor.h"
#include "absl/strings/string_view.h"
#include "absl/types/span.h"
#include "xla/client/xla_builder.h"
#include "xla/types.h"
#include "xla/xla_data.pb.h"
namespace xla {
XlaOp IdentityMatrix(XlaBuilder* builder, PrimitiveType type, int64_t m,
int64_t n);
XlaOp GetDiagonalMask(XlaOp x, int diagonal = 0);
XlaOp GetMatrixDiagonal(XlaOp x, int k = 0);
XlaOp GetMatrixDiagonalViaGather(XlaOp x, int k = 0);
XlaOp SetMatrixDiagonal(XlaOp matrix, XlaOp diag, int k = 0);
XlaOp TriangleMask(XlaOp x, int diagonal);
XlaOp Triangle(XlaOp x, bool lower);
XlaOp UpperTriangle(XlaOp x);
XlaOp LowerTriangle(XlaOp x);
XlaOp Symmetrize(XlaOp x, bool lower);
xla::XlaOp BatchDot(
xla::XlaOp x, xla::XlaOp y,
xla::PrecisionConfig::Precision precision = xla::PrecisionConfig::DEFAULT,
std::optional<PrimitiveType> preferred_element_type = std::nullopt);
xla::XlaOp BatchDot(
xla::XlaOp x, bool transpose_x, xla::XlaOp y, bool transpose_y,
xla::PrecisionConfig::Precision precision = xla::PrecisionConfig::DEFAULT,
std::optional<PrimitiveType> preferred_element_type = std::nullopt,
bool grad_x = false, bool grad_y = false);
absl::StatusOr<std::array<std::vector<int64_t>, 3>> ParseEinsumString(
absl::string_view einsum_config, int64_t x_rank, int64_t y_rank);
std::string NormalizeEinsumString(absl::string_view einsum_config);
xla::XlaOp Einsum(
xla::XlaOp x, xla::XlaOp y, absl::string_view einsum_config,
xla::PrecisionConfig::Precision precision = xla::PrecisionConfig::DEFAULT,
std::optional<PrimitiveType> preferred_element_type = std::nullopt,
bool grad_x = false, bool grad_y = false);
xla::XlaOp Einsum(
xla::XlaOp x, absl::string_view einsum_config,
xla::PrecisionConfig::Precision precision = xla::PrecisionConfig::DEFAULT);
xla::XlaOp Einsum(
xla::XlaOp x, absl::Span<const int64_t> x_config, xla::XlaOp y,
absl::Span<const int64_t> y_config, absl::Span<const int64_t> output_config,
xla::PrecisionConfig::Precision precision = xla::PrecisionConfig::DEFAULT,
std::optional<PrimitiveType> preferred_element_type = std::nullopt,
bool grad_x = false, bool grad_y = false);
xla::XlaOp TransposeInMinorDims(xla::XlaOp x);
xla::XlaOp MaybeTransposeInMinorDims(xla::XlaOp x, bool transpose);
}
#endif
#include "xla/client/lib/matrix.h"
#include <algorithm>
#include <array>
#include <cstdint>
#include <map>
#include <numeric>
#include <optional>
#include <string>
#include <tuple>
#include <utility>
#include <vector>
#include "absl/algorithm/container.h"
#include "absl/container/flat_hash_set.h"
#include "absl/container/inlined_vector.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/ascii.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_split.h"
#include "absl/strings/string_view.h"
#include "absl/types/span.h"
#include "xla/client/lib/arithmetic.h"
#include "xla/client/lib/constants.h"
#include "xla/client/lib/slicing.h"
#include "xla/client/xla_builder.h"
#include "xla/literal.h"
#include "xla/primitive_util.h"
#include "xla/shape.h"
#include "xla/shape_util.h"
#include "xla/status_macros.h"
#include "xla/util.h"
#include "xla/xla_data.pb.h"
#include "tsl/platform/errors.h"
namespace xla {
XlaOp IdentityMatrix(XlaBuilder* builder, PrimitiveType type, int64_t m,
int64_t n) {
auto a = Iota(builder, U32, m);
auto b = Iota(builder, U32, n);
auto indicator = Eq(a, Broadcast(b, {m}), {0});
return ConvertElementType(indicator, type);
}
XlaOp GetDiagonalMask(XlaOp x, int diagonal) {
XlaBuilder* builder = x.builder();
return builder->ReportErrorOrReturn([&]() -> absl::StatusOr<XlaOp> {
TF_ASSIGN_OR_RETURN(Shape shape, builder->GetShape(x));
auto n_dims = static_cast<int32_t>(shape.rank());
TF_RET_CHECK(n_dims >= 2);
auto m = shape.dimensions(n_dims - 2);
auto n = shape.dimensions(n_dims - 1);
absl::Span<const int64_t> major_dims =
shape.dimensions().subspan(0, n_dims - 2);
auto a = Iota(builder, S32, n);
auto b = Iota(builder, S32, m) + ConstantR0WithType(builder, S32, diagonal);
auto indicator = Eq(b, Broadcast(a, {m}), {0});
auto mask = Broadcast(indicator, major_dims);
return mask;
});
}
XlaOp GetMatrixDiagonal(XlaOp x, int k) {
XlaBuilder* builder = x.builder();
return builder->ReportErrorOrReturn([&]() -> absl::StatusOr<XlaOp> {
TF_ASSIGN_OR_RETURN(Shape shape, builder->GetShape(x));
auto n_dims = static_cast<int32_t>(shape.rank());
TF_RET_CHECK(n_dims >= 2);
const int64_t m = shape.dimensions(n_dims - 2);
const int64_t n = shape.dimensions(n_dims - 1);
if (k <= -m || k >= n) {
auto zero_size_shape = shape;
zero_size_shape.DeleteDimension(n_dims - 1);
zero_size_shape.set_dimensions(n_dims - 2, 0);
return ConstantLiteral(builder, Literal{zero_size_shape});
}
auto mask = GetDiagonalMask(x, k);
int64_t reduce_dim = n_dims - 1;
if ((k == 0 && m >= n) || k < 0) {
reduce_dim = n_dims - 2;
}
auto result = Reduce(
Select(mask, x, Zeros(builder, shape)), ScalarLike(x, 0),
CreateScalarIdentityWithZeroComputation(shape.element_type(), builder),
{reduce_dim});
if (k == 0) {
return result;
}
return SliceInMinorDims(result, {0},
{k > 0 ? std::min(m, n - k) : std::min(n, m + k)});
});
}
XlaOp GetMatrixDiagonalViaGather(XlaOp x, int k) {
XlaBuilder* builder = x.builder();
return builder->ReportErrorOrReturn([&]() -> absl::StatusOr<XlaOp> {
TF_ASSIGN_OR_RETURN(Shape shape, builder->GetShape(x));
auto n_dims = static_cast<int32_t>(shape.rank());
TF_RET_CHECK(n_dims >= 2);
const int64_t m = shape.dimensions(n_dims - 2);
const int64_t n = shape.dimensions(n_dims - 1);
const int64_t num_index_dims = 2;
const int64_t axis = n_dims - num_index_dims;
const int64_t diag_len =
std::max(std::min(m + std::min(k, 0), n - std::max(k, 0)), int64_t{0});
XlaOp diag_base_indices = BroadcastInDim(Iota(builder, S32, diag_len),
{diag_len, num_index_dims}, {0});
XlaOp diag_offset =
Broadcast(ConstantR1<int>(builder, {std::max(-k, 0), std::max(k, 0)}),
{diag_len});
XlaOp start_indices = Add(diag_base_indices, diag_offset);
xla::GatherDimensionNumbers dim_numbers;
std::vector<int64_t> slice_sizes;
slice_sizes.reserve(n_dims);
for (int64_t i = 0; i < n_dims; i++) {
int64_t window_bound;
if (axis <= i) {
dim_numbers.add_collapsed_slice_dims(i);
dim_numbers.add_start_index_map(i);
window_bound = (shape.dimensions(i) != 0) ? 1 : 0;
} else {
dim_numbers.add_offset_dims(i);
window_bound = shape.dimensions(i);
}
slice_sizes.push_back(window_bound);
}
dim_numbers.set_index_vector_dim(1);
return Gather(x, start_indices, dim_numbers, slice_sizes,
true);
});
}
XlaOp SetMatrixDiagonal(XlaOp matrix, XlaOp diag, int k) {
XlaBuilder* builder = matrix.builder();
return builder->ReportErrorOrReturn([&]() -> absl::StatusOr<XlaOp> {
TF_ASSIGN_OR_RETURN(Shape shape, builder->GetShape(matrix));
TF_ASSIGN_OR_RETURN(Shape diag_shape, builder->GetShape(diag));
auto n_dims = static_cast<int32_t>(shape.rank());
TF_RET_CHECK(n_dims >= 2);
const int64_t m = shape.dimensions(n_dims - 2);
const int64_t n = shape.dimensions(n_dims - 1);
const int64_t d = diag_shape.dimensions(n_dims - 2);
std::vector<int64_t> broadcast_dims(n_dims - 1);
absl::c_iota(broadcast_dims, 0);
int64_t pad_high = m - d;
if (k < 0) {
++(broadcast_dims.back());
pad_high = n - d;
}
if (pad_high != 0) {
PaddingConfig padding_config;
for (int64_t i = 0; i < diag_shape.rank() - 1; ++i) {
auto* dims = padding_config.add_dimensions();
dims->set_edge_padding_low(0);
dims->set_interior_padding(0);
dims->set_edge_padding_high(0);
}
auto* dims = padding_config.add_dimensions();
dims->set_edge_padding_low(0);
dims->set_interior_padding(0);
dims->set_edge_padding_high(pad_high);
diag = Pad(diag, ScalarLike(diag, 0), padding_config);
}
return Select(GetDiagonalMask(matrix, k),
BroadcastInDim(diag, shape.dimensions(), broadcast_dims),
matrix);
});
}
XlaOp TriangleMask(XlaOp x, int diagonal) {
XlaBuilder* builder = x.builder();
return builder->ReportErrorOrReturn([&]() -> absl::StatusOr<XlaOp> {
TF_ASSIGN_OR_RETURN(Shape shape, builder->GetShape(x));
const int64_t n_dims = shape.rank();
TF_RET_CHECK(n_dims >= 2);
const int64_t m = shape.dimensions(n_dims - 2);
const int64_t n = shape.dimensions(n_dims - 1);
absl::Span<const int64_t> major_dims =
shape.dimensions().subspan(0, n_dims - 2);
auto a = Iota(builder, S32, n);
auto b = Iota(builder, S32, m) + ConstantR0<int32_t>(builder, diagonal);
XlaOp indicator;
indicator = Ge(b, Broadcast(a, {m}), {0});
return Broadcast(indicator, major_dims);
});
}
XlaOp Triangle(XlaOp x, bool lower) {
return lower ? Select(TriangleMask(x, 0), x, ZerosLike(x))
: Select(TriangleMask(x, -1), ZerosLike(x), x);
}
XlaOp UpperTriangle(XlaOp x) { return Triangle(x, false); }
XlaOp LowerTriangle(XlaOp x) { return Triangle(x, true); }
XlaOp Symmetrize(XlaOp x, bool lower) {
XlaBuilder* builder = x.builder();
return builder->ReportErrorOrReturn([&]() -> absl::StatusOr<XlaOp> {
TF_ASSIGN_OR_RETURN(Shape shape, builder->GetShape(x));
if (shape.rank() < 2) {
return InvalidArgument(
"Argument to symmetrize must have >= 2 dimensions, got %s",
shape.ToString());
}
const int64_t m = ShapeUtil::GetDimension(shape, -2);
const int64_t n = ShapeUtil::GetDimension(shape, -1);
if (m != n) {
return InvalidArgument(
"The two most minor dimensions of the argument to symmetrize must be "
"equal size, got %s",
shape.ToString());
}
auto mask = lower ? TriangleMask(x, 0) : Not(TriangleMask(x, -1));
if (primitive_util::IsComplexType(shape.element_type())) {
auto re = Select(mask, Real(x), TransposeInMinorDims(Real(x)));
auto im_mask = lower ? TriangleMask(x, -1) : Not(TriangleMask(x, 0));
auto im = Select(im_mask, Imag(x), ZerosLike(Imag(x)));
im = Select(mask, im, -TransposeInMinorDims(im));
return Complex(re, im);
} else {
return Select(mask, x, TransposeInMinorDims(x));
}
});
}
namespace {
std::optional<std::array<std::vector<int64_t>, 3>> EinsumDiagonalLabels(
absl::Span<const int64_t> config) {
std::vector<int64_t> unique_labels;
std::vector<int64_t> reduce_dims;
std::vector<int64_t> broadcast_dims;
for (auto label = config.begin(); label != config.end(); ++label) {
auto first_label = absl::c_find(config, *label);
auto dim = label - config.begin();
if (first_label == label) {
unique_labels.push_back(*label);
broadcast_dims.push_back(dim);
} else {
reduce_dims.push_back(dim);
}
}
if (unique_labels.size() == config.size()) {
return std::nullopt;
}
return {{unique_labels, reduce_dims, broadcast_dims}};
}
xla::XlaOp EinsumDiagonalMask(XlaOp x, absl::Span<const int64_t> config) {
XlaBuilder* builder = x.builder();
return builder->ReportErrorOrReturn([&]() -> absl::StatusOr<XlaOp> {
TF_ASSIGN_OR_RETURN(Shape x_shape, builder->GetShape(x));
Shape iota_shape = ShapeUtil::MakeShape(S32, x_shape.dimensions());
XlaOp mask = ConstantR0(builder, true);
for (auto label = config.begin(); label != config.end(); ++label) {
const int64_t dim = label - config.begin();
auto first_label = absl::c_find(config, *label);
if (first_label != label) {
const int64_t first_dim = first_label - config.begin();
mask = And(mask, Eq(Iota(builder, iota_shape, first_dim),
Iota(builder, iota_shape, dim)));
}
}
return Select(mask, x, ZerosLike(x));
});
}
xla::XlaOp EinsumDiagonal(XlaOp x, absl::Span<const int64_t> config) {
XlaBuilder* builder = x.builder();
return builder->ReportErrorOrReturn([&]() -> absl::StatusOr<XlaOp> {
auto labels = EinsumDiagonalLabels(config);
if (!labels) {
return x;
}
auto zero = ScalarLike(x, 0);
TF_ASSIGN_OR_RETURN(Shape x_shape, builder->GetShape(x));
return Reduce(EinsumDiagonalMask(x, config), zero,
CreateScalarIdentityWithZeroComputation(
x_shape.element_type(), builder),
labels->at(1));
});
}
xla::XlaOp EinsumInverseDiagonal(XlaOp x, absl::Span<const int64_t> config) {
XlaBuilder* builder = x.builder();
return builder->ReportErrorOrReturn([&]() -> absl::StatusOr<XlaOp> {
auto labels = EinsumDiagonalLabels(config);
if (!labels) {
return x;
}
TF_ASSIGN_OR_RETURN(Shape x_shape, builder->GetShape(x));
std::vector<int64_t> broadcast_sizes;
int64_t x_dim = 0;
for (auto label = config.begin(); label != config.end(); ++label) {
auto first_label = absl::c_find(config, *label);
if (first_label == label) {
broadcast_sizes.push_back(x_shape.dimensions(x_dim));
++x_dim;
} else {
broadcast_sizes.push_back(
broadcast_sizes[first_label - config.begin()]);
}
}
x = BroadcastInDim(x, broadcast_sizes, labels->at(2));
return EinsumDiagonalMask(x, config);
});
}
}
namespace {
template <typename C>
void DeleteDimsFromContainer(absl::Span<const int64_t> to_delete, Shape* shape,
C* batch_dims, C* contracting_dims) {
if (to_delete.empty()) {
return;
}
for (int64_t i = to_delete.size() - 1; i >= 0; --i) {
int64_t dim = to_delete[i];
shape->DeleteDimension(dim);
for (auto& b : *batch_dims) {
if (b > dim) {
--b;
}
}
for (auto& c : *contracting_dims) {
if (c > dim) {
--c;
}
}
}
}
}
xla::XlaOp Einsum(xla::XlaOp x, absl::Span<const int64_t> x_config,
xla::XlaOp y, absl::Span<const int64_t> y_config,
absl::Span<const int64_t> output_config,
xla::PrecisionConfig::Precision precision,
std::optional<PrimitiveType> preferred_element_type,
bool grad_x, bool grad_y) {
XlaBuilder* builder = x.builder();
return builder->ReportErrorOrReturn([&]() -> absl::StatusOr<XlaOp> {
auto x_diagonal_labels = EinsumDiagonalLabels(x_config);
if (x_diagonal_labels) {
return Einsum(EinsumDiagonal(x, x_config), x_diagonal_labels->at(0), y,
y_config, output_config, precision, preferred_element_type,
grad_x, grad_y);
}
auto y_diagonal_labels = EinsumDiagonalLabels(y_config);
if (y_diagonal_labels) {
return Einsum(x, x_config, EinsumDiagonal(y, y_config),
y_diagonal_labels->at(0), output_config, precision,
preferred_element_type, grad_x, grad_y);
}
auto output_diagonal_labels = EinsumDiagonalLabels(output_config);
if (output_diagonal_labels) {
return EinsumInverseDiagonal(
Einsum(x, x_config, y, y_config, output_diagonal_labels->at(0),
precision, preferred_element_type, grad_x, grad_y),
output_config);
}
TF_ASSIGN_OR_RETURN(Shape x_shape, builder->GetShape(x));
TF_ASSIGN_OR_RETURN(Shape y_shape, builder->GetShape(y));
const int64_t x_rank = x_config.size();
const int64_t y_rank = y_config.size();
const int64_t output_rank = output_config.size();
absl::flat_hash_set<int64_t> x_map;
absl::flat_hash_set<int64_t> y_map;
absl::flat_hash_set<int64_t> output_map;
for (auto d : x_config) {
x_map.insert(d);
}
for (auto d : y_config) {
y_map.insert(d);
}
for (auto d : output_config) {
output_map.insert(d);
}
DotDimensionNumbers dnums;
auto is_batch_dim = [&](int64_t d) {
return x_map.contains(d) && y_map.contains(d) && output_map.contains(d);
};
auto is_contracting = [&](int64_t d) {
return x_map.contains(d) && y_map.contains(d);
};
auto rhs_dimension_number = [&](int64_t d) {
return absl::c_find(y_config, d) - y_config.begin();
};
absl::InlinedVector<int64_t, 8> rhs_outer_dims;
absl::InlinedVector<int64_t, 8> lhs_outer_dims;
absl::InlinedVector<int64_t, 8> rhs_delete_dims;
absl::InlinedVector<int64_t, 8> lhs_delete_dims;
for (int64_t i = 0; i < x_rank; ++i) {
auto dim_name = x_config[i];
const int64_t rhs_dim = rhs_dimension_number(dim_name);
if (is_batch_dim(dim_name)) {
if (x_shape.dimensions(i) == y_shape.dimensions(rhs_dim)) {
dnums.add_lhs_batch_dimensions(i);
dnums.add_rhs_batch_dimensions(rhs_dim);
} else if (x_shape.dimensions(i) == 1) {
rhs_outer_dims.push_back(rhs_dim);
lhs_delete_dims.push_back(i);
} else {
lhs_outer_dims.push_back(i);
rhs_delete_dims.push_back(rhs_dim);
}
} else if (is_contracting(dim_name)) {
if (x_shape.dimensions(i) == y_shape.dimensions(rhs_dim)) {
dnums.add_lhs_contracting_dimensions(i);
dnums.add_rhs_contracting_dimensions(rhs_dim);
} else if (x_shape.dimensions(i) == 1) {
rhs_outer_dims.push_back(rhs_dim);
lhs_delete_dims.push_back(i);
} else {
lhs_outer_dims.push_back(i);
rhs_delete_dims.push_back(rhs_dim);
}
} else {
lhs_outer_dims.push_back(i);
}
}
for (int64_t i = 0; i < y_rank; ++i) {
auto dim_name = y_config[i];
if (!is_batch_dim(dim_name) && !is_contracting(dim_name)) {
rhs_outer_dims.push_back(i);
}
}
absl::c_sort(rhs_outer_dims);
absl::InlinedVector<int64_t, 8> output_transpose_dims;
auto output_dimension_number = [&](int64_t d) -> std::optional<int64_t> {
auto pos = absl::c_find(output_config, d);
if (pos == output_config.end()) {
return std::nullopt;
}
return pos - output_config.begin();
};
for (auto d : dnums.lhs_batch_dimensions()) {
output_transpose_dims.push_back(*output_dimension_number(x_config[d]));
}
for (auto d : lhs_outer_dims) {
if (auto output_dim = output_dimension_number(x_config[d])) {
output_transpose_dims.push_back(*output_dim);
continue;
}
lhs_delete_dims.push_back(d);
}
for (auto d : rhs_outer_dims) {
if (auto output_dim = output_dimension_number(y_config[d])) {
output_transpose_dims.push_back(*output_dim);
continue;
}
rhs_delete_dims.push_back(d);
}
const int64_t transpose_rank = output_transpose_dims.size();
std::vector<int64_t> transpose_dims(output_rank);
for (int64_t i = 0; i < transpose_rank; ++i) {
transpose_dims[output_transpose_dims[i]] = i;
}
absl::c_sort(lhs_delete_dims);
DeleteDimsFromContainer(lhs_delete_dims, &x_shape,
dnums.mutable_lhs_batch_dimensions(),
dnums.mutable_lhs_contracting_dimensions());
absl::c_sort(rhs_delete_dims);
DeleteDimsFromContainer(rhs_delete_dims, &y_shape,
dnums.mutable_rhs_batch_dimensions(),
dnums.mutable_rhs_contracting_dimensions());
if (!lhs_delete_dims.empty()) {
x = Reduce(x, ScalarLike(x, 0),
CreateScalarAddComputation(x_shape.element_type(), builder),
lhs_delete_dims);
}
if (!rhs_delete_dims.empty()) {
y = Reduce(y, ScalarLike(y, 0),
CreateScalarAddComputation(y_shape.element_type(), builder),
rhs_delete_dims);
}
PrecisionConfig precision_proto;
precision_proto.add_operand_precision(precision);
precision_proto.add_operand_precision(precision);
auto dot =
DotGeneral(x, y, dnums, &precision_proto, preferred_element_type);
TF_RETURN_IF_ERROR(builder->SetInstructionFrontendAttribute(
dot, "grad_x", (grad_x ? "true" : "false")));
TF_RETURN_IF_ERROR(builder->SetInstructionFrontendAttribute(
dot, "grad_y", (grad_y ? "true" : "false")));
dot = Transpose(dot, transpose_dims);
if (transpose_rank == output_rank) {
return dot;
}
auto is_output_only = [&](int64_t d) {
return output_map.contains(d) && !x_map.contains(d) && !y_map.contains(d);
};
int64_t dot_dim = 0;
std::vector<int64_t> new_dims;
new_dims.reserve(output_rank);
TF_ASSIGN_OR_RETURN(Shape dot_shape, builder->GetShape(dot));
for (auto d : output_config) {
if (is_output_only(d)) {
new_dims.push_back(1);
} else {
new_dims.push_back(dot_shape.dimensions(dot_dim));
}
}
return Reshape(dot, new_dims);
});
}
XlaOp BatchDot(XlaOp x, XlaOp y, PrecisionConfig::Precision precision,
std::optional<PrimitiveType> preferred_element_type) {
return BatchDot(x, false, y, false, precision, preferred_element_type);
}
XlaOp BatchDot(XlaOp x, bool transpose_x, XlaOp y, bool transpose_y,
PrecisionConfig::Precision precision,
std::optional<PrimitiveType> preferred_element_type, bool grad_x,
bool grad_y) {
XlaBuilder* builder = x.builder();
return builder->ReportErrorOrReturn([&]() -> absl::StatusOr<XlaOp> {
std::string string("...mk,...kn->...mn");
if (transpose_x) {
std::swap(string[3], string[4]);
}
if (transpose_y) {
std::swap(string[6 + 3], string[6 + 4]);
}
return Einsum(x, y, string, precision, preferred_element_type, grad_x,
grad_y);
});
}
absl::StatusOr<std::array<std::vector<int64_t>, 3>> ParseEinsumString(
absl::string_view einsum_config, int64_t x_rank, int64_t y_rank) {
std::array<std::vector<int64_t>, 3> einsum_config_numeric;
std::vector<absl::string_view> main_split =
absl::StrSplit(einsum_config, ',');
if (main_split.size() != 2) {
return InvalidArgument("Expected one \",\" in einsum_config.");
}
auto maybe_invalid_character = [](char d) -> absl::Status {
if (absl::ascii_isalpha(d)) {
return absl::OkStatus();
}
if (d == '.') {
return InvalidArgument("Unsupported \".\" in einsum config.");
}
return InvalidArgument("Unexpected character in einsum config.");
};
auto string_config_to_numeric =
[&](absl::string_view config, bool is_input_config, int64_t input_rank,
int64_t ellipsis_rank,
std::vector<int64_t>* numeric_config) -> absl::StatusOr<int64_t> {
std::vector<absl::string_view> splits = absl::StrSplit(config, "...");
if (splits.empty()) {
return ellipsis_rank;
}
if (splits.size() > 2) {
return InvalidArgument("Too many ellipses (\"...\") in einsum config.");
}
const bool has_ellipsis = splits.size() > 1;
if (is_input_config && has_ellipsis) {
ellipsis_rank = input_rank -
static_cast<int64_t>(splits[0].size() + splits[1].size());
if (ellipsis_rank < 0) {
return InvalidArgument(
"Too few dimensions in the input for the given einsum config.");
}
}
for (char d : splits[0]) {
TF_RETURN_IF_ERROR(maybe_invalid_character(d));
numeric_config->push_back(static_cast<int64_t>(d));
}
if (has_ellipsis) {
for (int64_t i = ellipsis_rank; i > 0; --i) {
numeric_config->push_back(-i);
}
for (char d : splits[1]) {
TF_RETURN_IF_ERROR(maybe_invalid_character(d));
numeric_config->push_back(static_cast<int64_t>(d));
}
}
return ellipsis_rank;
};
TF_ASSIGN_OR_RETURN(
const int64_t x_ellipsis_rank,
string_config_to_numeric(main_split[0],
true, x_rank,
0, &einsum_config_numeric[0]));
std::vector<absl::string_view> y_output_split =
absl::StrSplit(main_split[1], "->");
if (y_output_split.size() != 2) {
return InvalidArgument("Expected one \"->\" in einsum_config.");
}
TF_ASSIGN_OR_RETURN(
const int64_t y_ellipsis_rank,
string_config_to_numeric(y_output_split[0],
true, y_rank,
0, &einsum_config_numeric[1]));
TF_ASSIGN_OR_RETURN(
std::ignore,
string_config_to_numeric(
y_output_split[1], false,
0,
std::max(x_ellipsis_rank, y_ellipsis_rank),
&einsum_config_numeric[2]));
return einsum_config_numeric;
}
std::string NormalizeEinsumString(absl::string_view einsum_config) {
if (einsum_config.find("->") != einsum_config.npos) {
return "";
}
bool has_ellipsis = einsum_config.find("...") != einsum_config.npos;
std::map<char, int64_t> chars;
for (char c : einsum_config) {
if (absl::ascii_isalpha(c)) {
++chars[c];
}
}
std::string new_config(einsum_config.begin(), einsum_config.end());
new_config.append("->");
if (has_ellipsis) {
new_config.append("...");
}
for (auto p : chars) {
if (p.second == 1) {
new_config.push_back(p.first);
}
}
return new_config;
}
XlaOp Einsum(XlaOp x, XlaOp y, absl::string_view einsum_config,
PrecisionConfig::Precision precision,
std::optional<PrimitiveType> preferred_element_type, bool grad_x,
bool grad_y) {
XlaBuilder* builder = x.builder();
return builder->ReportErrorOrReturn([&]( | #include "xla/client/lib/matrix.h"
#include <limits>
#include <map>
#include <string>
#include <vector>
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/string_view.h"
#include "xla/client/lib/constants.h"
#include "xla/client/lib/slicing.h"
#include "xla/client/xla_builder.h"
#include "xla/test.h"
#include "xla/tests/client_library_test_base.h"
#include "xla/tests/test_macros.h"
#include "xla/types.h"
namespace xla {
namespace {
class MatrixTest : public ClientLibraryTestBase {
protected:
template <typename T>
void TestMatrixDiagonal();
template <typename T>
void TestMatrixDiagonal4D();
template <typename T>
void TestSetMatrixDiagonal();
template <typename T>
std::map<int, Array2D<T>> k_and_expected() const {
return std::map<int, Array2D<T>>{
{0, {{0, 5, 10}, {12, 17, 22}}},
{1, {{1, 6, 11}, {13, 18, 23}}},
{2, {{2, 7}, {14, 19}}},
{3, {{3}, {15}}},
{4, {{}, {}}},
{-1, {{4, 9}, {16, 21}}},
{-2, {{8}, {20}}},
{-3, {{}, {}}},
{-4, {{}, {}}},
};
}
};
XLA_TEST_F(MatrixTest, Triangle) {
XlaBuilder builder(TestName());
Array3D<int32_t> input(2, 3, 4);
input.FillIota(0);
XlaOp a;
auto a_data = CreateR3Parameter<int32_t>(input, 0, "a", &builder, &a);
LowerTriangle(a);
Array3D<int32_t> expected({{{0, 0, 0, 0}, {4, 5, 0, 0}, {8, 9, 10, 0}},
{{12, 0, 0, 0}, {16, 17, 0, 0}, {20, 21, 22, 0}}});
ComputeAndCompareR3<int32_t>(&builder, expected, {a_data.get()});
}
XLA_TEST_F(MatrixTest, Symmetrize) {
for (bool lower : {false, true}) {
XlaBuilder builder(TestName());
float nan = std::numeric_limits<float>::quiet_NaN();
Array<float> input = {
{1, nan, nan},
{2, 3, nan},
{4, 5, 6},
};
XlaOp a;
auto a_data = CreateParameter<float>(input, 0, "a", &builder, &a);
Symmetrize(lower ? a : TransposeInMinorDims(a), lower);
Array<float> expected = {
{1, 2, 4},
{2, 3, 5},
{4, 5, 6},
};
ComputeAndCompare<float>(&builder, expected, {a_data.get()});
}
}
XLA_TEST_F(MatrixTest, SymmetrizeComplex) {
for (bool lower : {false, true}) {
XlaBuilder builder(TestName());
float nan = std::numeric_limits<float>::quiet_NaN();
Array<complex64> input = {
{complex64{1, nan}, nan, nan},
{complex64{2, 7}, complex64{3, nan}, nan},
{complex64{4, 8}, complex64{5, 9}, complex64{6, nan}},
};
XlaOp a;
auto a_data = CreateParameter<complex64>(input, 0, "a", &builder, &a);
Symmetrize(lower ? a : Conj(TransposeInMinorDims(a)), lower);
Array<complex64> expected = {
{1, complex64{2, -7}, complex64{4, -8}},
{complex64{2, 7}, 3, complex64{5, -9}},
{complex64{4, 8}, complex64{5, 9}, 6},
};
ComputeAndCompare<complex64>(&builder, expected, {a_data.get()});
}
}
template <typename T>
void MatrixTest::TestMatrixDiagonal() {
XlaBuilder builder("SetMatrixDiagonal");
Array3D<T> input(2, 3, 4);
input.FillIota(0);
for (const auto& kv : k_and_expected<T>()) {
XlaOp a;
auto a_data = CreateR3Parameter<T>(input, 0, "a", &builder, &a);
GetMatrixDiagonal(a, kv.first);
ComputeAndCompareR2<T>(&builder, kv.second, {a_data.get()});
}
}
template <typename T>
void MatrixTest::TestSetMatrixDiagonal() {
XlaBuilder builder("GetMatrixDiagonal");
Array3D<T> input(2, 3, 4);
input.FillIota(0);
for (const auto& kv : k_and_expected<T>()) {
XlaOp a;
XlaOp b;
auto a_data = CreateR3Parameter<T>(input, 0, "a", &builder, &a);
auto new_diag =
CreateR2Parameter<T>(Array2D<T>{kv.second}, 1, "d", &builder, &b);
GetMatrixDiagonal(SetMatrixDiagonal(a, b + ScalarLike(b, 1), kv.first),
kv.first) -
ScalarLike(b, 1);
ComputeAndCompareR2<T>(&builder, kv.second, {a_data.get(), new_diag.get()});
}
}
XLA_TEST_F(MatrixTest, SetMatrixDiagonal_S32) {
TestSetMatrixDiagonal<int32_t>();
}
XLA_TEST_F(MatrixTest, SetMatrixDiagonal_S64) {
TestSetMatrixDiagonal<int64_t>();
}
XLA_TEST_F(MatrixTest, SetMatrixDiagonal_F32) {
TestSetMatrixDiagonal<float>();
}
XLA_TEST_F(MatrixTest, GetMatrixDiagonal_S32) { TestMatrixDiagonal<int32_t>(); }
XLA_TEST_F(MatrixTest, GetMatrixDiagonal_S64) { TestMatrixDiagonal<int64_t>(); }
XLA_TEST_F(MatrixTest, GetMatrixDiagonal_F32) { TestMatrixDiagonal<float>(); }
template <typename T>
void MatrixTest::TestMatrixDiagonal4D() {
XlaBuilder builder("GetMatrixDiagonal");
Array4D<T> input(2, 2, 4, 3);
input.FillIota(0);
std::map<int, Array3D<T>> k_and_expected = {
{0, {{{0, 4, 8}, {12, 16, 20}}, {{24, 28, 32}, {36, 40, 44}}}},
{1, {{{1, 5}, {13, 17}}, {{25, 29}, {37, 41}}}},
{2, {{{2}, {14}}, {{26}, {38}}}},
{3, {{{}, {}}, {{}, {}}}},
{4, {{{}, {}}, {{}, {}}}},
{-1, {{{3, 7, 11}, {15, 19, 23}}, {{27, 31, 35}, {39, 43, 47}}}},
{-2, {{{6, 10}, {18, 22}}, {{30, 34}, {42, 46}}}},
{-3, {{{9}, {21}}, {{33}, {45}}}},
{-4, {{{}, {}}, {{}, {}}}},
};
for (const auto& kv : k_and_expected) {
XlaOp a;
auto a_data = CreateR4Parameter<T>(input, 0, "a", &builder, &a);
GetMatrixDiagonal(a, kv.first);
ComputeAndCompareR3<T>(&builder, kv.second, {a_data.get()});
}
}
XLA_TEST_F(MatrixTest, GetMatrixDiagonal4D_S32) {
TestMatrixDiagonal4D<int32_t>();
}
XLA_TEST_F(MatrixTest, GetMatrixDiagonal4D_S64) {
TestMatrixDiagonal4D<int64_t>();
}
XLA_TEST_F(MatrixTest, GetMatrixDiagonal4D_F32) {
TestMatrixDiagonal4D<float>();
}
Array3D<float> BatchedAValsFull() {
return {{
{2, 0, 1, 2},
{3, 6, 0, 1},
{4, 7, 9, 0},
{5, 8, 10, 11},
},
{
{16, 24, 8, 12},
{24, 61, 82, 48},
{8, 82, 456, 106},
{12, 48, 106, 62},
}};
}
XLA_TEST_F(MatrixTest, RowBatchDot) {
XlaBuilder builder(TestName());
int n = 4;
XlaOp a, row, index;
auto a_data =
CreateR3Parameter<float>(BatchedAValsFull(), 0, "a", &builder, &a);
auto row_data = CreateR3Parameter<float>({{{9, 1, 0, 0}}, {{2, 4, 0, 0}}}, 1,
"row", &builder, &row);
auto index_data = CreateR0Parameter<int>(1, 2, "index", &builder, &index);
auto l_index = DynamicSliceInMinorDims(
a, {index, ConstantR0<int32_t>(&builder, 0)}, {1, n});
BatchDot(l_index, TransposeInMinorDims(row));
ComputeAndCompareR3<float>(&builder, {{{33}}, {{292}}},
{a_data.get(), row_data.get(), index_data.get()});
}
XLA_TEST_F(MatrixTest, Einsum) {
XlaBuilder builder(TestName());
int n = 4;
XlaOp a, row, index;
auto a_data =
CreateR3Parameter<float>(BatchedAValsFull(), 0, "a", &builder, &a);
auto row_data = CreateR3Parameter<float>({{{9, 1, 0, 0}}, {{2, 4, 0, 0}}}, 1,
"row", &builder, &row);
auto index_data = CreateR0Parameter<int>(1, 2, "index", &builder, &index);
auto l_index = DynamicSliceInMinorDims(
a, {index, ConstantR0<int32_t>(&builder, 0)}, {1, n});
Einsum(l_index, row, "abc,adc->abd");
ComputeAndCompareR3<float>(&builder, {{{33}}, {{292}}},
{a_data.get(), row_data.get(), index_data.get()});
}
XLA_TEST_F(MatrixTest, ParseEinsumString) {
auto to_vec = [](absl::string_view s) {
std::vector<int64_t> v;
v.reserve(s.size());
int e = -3;
for (auto c : s) {
v.push_back(c == '.' ? e++ : int64_t{c});
}
return v;
};
auto to_string = [&](absl::string_view x, absl::string_view y,
absl::string_view o) {
return absl::StrCat(x, ",", y, "->", o);
};
std::vector<std::vector<std::string>> good_test_cases = {
{"ab", "bc", "ac"},
{"Bab", "Bbc", "Bac"},
{"ab", "cd", "dcba"},
{"abc", "abd", "cbd"},
{"...ab", "...bc", "...ac"},
{"a...bc", "...abd", "cbd..."},
{"...ab", "...bc", "ac"},
{"...b", "...bc", "...c"},
{"...abz", "...bc", "...ac"},
{"...ab", "...bcz", "...ac"},
{"abz", "bc", "ac"},
{"ab", "bcz", "ac"},
{"a", "b", "c"},
{"...a", "...b", "...c"},
{"abb", "bcc", "ac"},
{"ab", "bc", "ad"},
};
for (auto test_case : good_test_cases) {
auto parse_result_or_status =
ParseEinsumString(to_string(test_case[0], test_case[1], test_case[2]),
test_case[0].size(), test_case[1].size());
EXPECT_TRUE(parse_result_or_status.status().ok());
auto parse_result = parse_result_or_status.value();
for (int i = 0; i < 3; ++i) {
EXPECT_EQ(parse_result[i], to_vec(test_case[i]));
}
}
std::vector<std::string> einsum_strings_that_fail_parsing = {
"", "a", "ab->ba", "ab,bc,cd->ad", "a...b...,bc->a...c",
};
for (auto test_case : einsum_strings_that_fail_parsing) {
auto parse_result_or_status = ParseEinsumString(test_case, 3, 3);
EXPECT_FALSE(parse_result_or_status.status().ok());
}
}
XLA_TEST_F(MatrixTest, NormalizeEinsumString) {
EXPECT_EQ(NormalizeEinsumString("a,b->ab"), "");
EXPECT_EQ(NormalizeEinsumString("ba"), "ba->ab");
EXPECT_EQ(NormalizeEinsumString("ab,dc"), "ab,dc->abcd");
EXPECT_EQ(NormalizeEinsumString("a,b"), "a,b->ab");
EXPECT_EQ(NormalizeEinsumString("...ba,ca..."), "...ba,ca...->...bc");
}
}
} | 2,226 |
#ifndef XLA_CLIENT_LIB_MATH_H_
#define XLA_CLIENT_LIB_MATH_H_
#include "xla/client/xla_builder.h"
namespace xla {
XlaOp IsPosInf(XlaOp operand);
XlaOp IsNegInf(XlaOp operand);
XlaOp IsInf(XlaOp operand);
XlaOp IsNan(XlaOp operand);
XlaOp IsNegZero(XlaOp operand);
XlaOp NextAfter(XlaOp from, XlaOp to);
XlaOp Square(XlaOp operand);
XlaOp Reciprocal(XlaOp operand);
XlaOp Erfc(XlaOp x);
XlaOp ErfInv(XlaOp x);
XlaOp Lgamma(XlaOp input);
XlaOp Digamma(XlaOp input);
XlaOp Igamma(XlaOp a, XlaOp x);
XlaOp IgammaGradA(XlaOp a, XlaOp x);
XlaOp RandomGammaGrad(XlaOp a, XlaOp x);
XlaOp Igammac(XlaOp a, XlaOp x);
XlaOp Polygamma(XlaOp n, XlaOp x);
XlaOp Zeta(XlaOp x, XlaOp q);
XlaOp RoundToEven(XlaOp x);
XlaOp Acos(XlaOp x);
XlaOp Asin(XlaOp x);
XlaOp Atan(XlaOp x);
XlaOp Acosh(XlaOp x);
XlaOp Asinh(XlaOp x);
XlaOp Atanh(XlaOp x);
XlaOp Cosh(XlaOp x);
XlaOp Sinh(XlaOp x);
xla::XlaOp MaybeConjugate(xla::XlaOp x, bool conjugate);
XlaOp BesselI0e(XlaOp x);
XlaOp BesselI1e(XlaOp x);
XlaOp RegularizedIncompleteBeta(XlaOp a, XlaOp b, XlaOp x);
}
#endif
#include "xla/mlir/tools/mlir_interpreter/dialects/cwise_math.h"
#include "xla/mlir/tools/mlir_interpreter/framework/interpreter_value_util.h"
#include "xla/mlir/tools/mlir_interpreter/framework/registration.h"
namespace mlir {
namespace interpreter {
namespace {
struct CopySign : CwiseFloat {
template <typename T>
static T Apply(T a, T b) {
return std::copysign(a, b);
}
};
REGISTER_MLIR_INTERPRETER_OP("math.absf", ApplyCwiseMap<Abs>);
REGISTER_MLIR_INTERPRETER_OP("math.absi", ApplyCwiseMap<Abs>);
REGISTER_MLIR_INTERPRETER_OP("math.atan", ApplyCwiseMap<ATan>);
REGISTER_MLIR_INTERPRETER_OP("math.atan2", ApplyCwiseBinaryMap<ATan2>);
REGISTER_MLIR_INTERPRETER_OP("math.cbrt", ApplyCwiseMap<Cbrt>);
REGISTER_MLIR_INTERPRETER_OP("math.ceil", ApplyCwiseMap<Ceil>);
REGISTER_MLIR_INTERPRETER_OP("math.copysign", ApplyCwiseBinaryMap<CopySign>);
REGISTER_MLIR_INTERPRETER_OP("math.cos", ApplyCwiseMap<Cos>);
REGISTER_MLIR_INTERPRETER_OP("math.ctlz", ApplyCwiseMap<Clz>);
REGISTER_MLIR_INTERPRETER_OP("math.ctpop", ApplyCwiseMap<PopCount>);
REGISTER_MLIR_INTERPRETER_OP("math.cttz", ApplyCwiseMap<Ctz>);
REGISTER_MLIR_INTERPRETER_OP("math.erf", ApplyCwiseMap<Erf>);
REGISTER_MLIR_INTERPRETER_OP("math.exp", ApplyCwiseMap<Exp>);
REGISTER_MLIR_INTERPRETER_OP("math.exp2", ApplyCwiseMap<Exp2>);
REGISTER_MLIR_INTERPRETER_OP("math.expm1", ApplyCwiseMap<ExpM1>);
REGISTER_MLIR_INTERPRETER_OP("math.floor", ApplyCwiseMap<Floor>);
REGISTER_MLIR_INTERPRETER_OP("math.ipowi", ApplyCwiseBinaryMap<Power>);
REGISTER_MLIR_INTERPRETER_OP("math.log", ApplyCwiseMap<Log>);
REGISTER_MLIR_INTERPRETER_OP("math.log10", ApplyCwiseMap<Log10>);
REGISTER_MLIR_INTERPRETER_OP("math.log1p", ApplyCwiseMap<Log1P>);
REGISTER_MLIR_INTERPRETER_OP("math.log2", ApplyCwiseMap<Log2>);
REGISTER_MLIR_INTERPRETER_OP("math.powf", ApplyCwiseBinaryMap<Power>);
REGISTER_MLIR_INTERPRETER_OP("math.round", ApplyCwiseMap<Round>);
REGISTER_MLIR_INTERPRETER_OP("math.roundeven", ApplyCwiseMap<NearbyInt>);
REGISTER_MLIR_INTERPRETER_OP("math.rsqrt", ApplyCwiseMap<RSqrt>);
REGISTER_MLIR_INTERPRETER_OP("math.sin", ApplyCwiseMap<Sin>);
REGISTER_MLIR_INTERPRETER_OP("math.sqrt", ApplyCwiseMap<Sqrt>);
REGISTER_MLIR_INTERPRETER_OP("math.tan", ApplyCwiseMap<Tan>);
REGISTER_MLIR_INTERPRETER_OP("math.tanh", ApplyCwiseMap<TanH>);
REGISTER_MLIR_INTERPRETER_OP("math.trunc", ApplyCwiseMap<Trunc>);
}
}
} | #include "xla/client/lib/math.h"
#include <cmath>
#include <complex>
#include <functional>
#include <limits>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "xla/client/lib/constants.h"
#include "xla/client/xla_builder.h"
#include "xla/literal_util.h"
#include "xla/primitive_util.h"
#include "xla/test.h"
#include "xla/tests/client_library_test_base.h"
#include "xla/tests/test_macros.h"
#include "xla/types.h"
#include "xla/xla_data.pb.h"
#include "tsl/lib/core/status_test_util.h"
namespace xla {
namespace {
class MathTest : public ClientLibraryTestBase {
public:
ErrorSpec error_spec_{0.0001};
};
template <typename T>
class MathTypedTest : public MathTest {
public:
void TestLogEdgeCases() {
SetFastMathDisabled(true);
XlaBuilder b(TestName());
Log(AddParam(LiteralUtil::CreateR1<T>({T{0.0}, T{-0.0}}), &b));
ComputeAndCompareR1<T>(&b,
{-std::numeric_limits<T>::infinity(),
-std::numeric_limits<T>::infinity()},
{}, error_spec_);
}
void TestLog1pEdgeCases() {
SetFastMathDisabled(true);
XlaBuilder b(TestName());
Log1p(AddParam(LiteralUtil::CreateR1<T>({T{0.0}, T{-0.0}, T{-1.0}}), &b));
ComputeAndCompareR1<T>(
&b, {T{0.0}, T{-0.0}, -std::numeric_limits<T>::infinity()}, {},
error_spec_);
}
void TestIsInfOrNan() {
SetFastMathDisabled(true);
XlaBuilder b(TestName());
auto x =
ConstantR1<T>(&b, {
T{0},
T{100},
T{-1000},
T{std::numeric_limits<T>::max()},
T{std::numeric_limits<T>::lowest()},
T{std::numeric_limits<float>::infinity()},
T{-std::numeric_limits<float>::infinity()},
T{std::numeric_limits<float>::quiet_NaN()},
T{std::numeric_limits<float>::signaling_NaN()},
});
Tuple(&b, {IsFinite(x), IsInf(x), IsPosInf(x), IsNegInf(x), IsNan(x)});
auto expected = LiteralUtil::MakeTupleOwned(
LiteralUtil::CreateR1<bool>(
{true, true, true, true, true, false, false, false, false}),
LiteralUtil::CreateR1<bool>(
{false, false, false, false, false, true, true, false, false}),
LiteralUtil::CreateR1<bool>(
{false, false, false, false, false, true, false, false, false}),
LiteralUtil::CreateR1<bool>(
{false, false, false, false, false, false, true, false, false}),
LiteralUtil::CreateR1<bool>(
{false, false, false, false, false, false, false, true, true}));
ComputeAndCompareLiteral(&b, expected, {});
}
void TestIsNegZero() {
SetFastMathDisabled(true);
XlaBuilder b(TestName());
T inf(std::numeric_limits<float>::infinity());
T nan(std::numeric_limits<float>::quiet_NaN());
IsNegZero(AddParam(
LiteralUtil::CreateR1<T>({T{-0.0}, T{0}, T{1}, T{-1}, inf, -inf, nan}),
&b));
ComputeAndCompareLiteral(
&b,
LiteralUtil::CreateR1<bool>(
{true, false, false, false, false, false, false}),
{}, error_spec_);
}
void TestSqrtPowInequivalence() {
SetFastMathDisabled(true);
mutable_debug_options()->clear_xla_disable_hlo_passes();
const T inf(std::numeric_limits<float>::infinity());
const T nan(std::numeric_limits<float>::quiet_NaN());
XlaBuilder b(TestName());
auto x = AddParam(LiteralUtil::CreateR1<T>({-inf}), &b);
ConcatInDim(
&b, {Sqrt(x), Pow(x, ScalarLike(x, 0.5)), Pow(x, ScalarLike(x, 0.3))},
0);
std::vector<T> expected = {nan, inf, inf};
ComputeAndCompareR1<T>(&b, expected, {}, error_spec_);
}
void TestErfInvEdgeCases() {
SetFastMathDisabled(true);
XlaBuilder b(TestName());
auto x = AddParam(LiteralUtil::CreateR1<T>({T{-1}, T{1}, T{0}}), &b);
ErfInv(x);
const T inf(std::numeric_limits<float>::infinity());
std::vector<T> expected = {-inf, inf, T{0}};
ComputeAndCompareR1<T>(&b, expected, {}, error_spec_);
}
void TestErfEdgeCases() {
SetFastMathDisabled(true);
const T kErfInvOneMinusHalfULP = T(3.832506856900711);
const T inf(std::numeric_limits<float>::infinity());
XlaBuilder b(TestName());
auto x = AddParam(LiteralUtil::CreateR1<T>({T{-inf}, T{inf}, T{-0}, T{0},
T{-kErfInvOneMinusHalfULP},
T{kErfInvOneMinusHalfULP}}),
&b);
Erf(x);
std::vector<T> expected = {T(-1), T(1), T(-0), T(0), T(-1), T(1)};
ComputeAndCompareR1<T>(&b, expected, {}, error_spec_);
}
};
using TestTypes = ::testing::Types<float
#ifndef XLA_BACKEND_DOES_NOT_SUPPORT_FLOAT16
,
Eigen::half
#endif
#ifndef XLA_BACKEND_DOES_NOT_SUPPORT_FLOAT64
,
double
#endif
>;
TYPED_TEST_CASE(MathTypedTest, TestTypes);
XLA_TYPED_TEST(MathTypedTest, LogEdgeCases) { this->TestLogEdgeCases(); }
XLA_TYPED_TEST(MathTypedTest, Log1pEdgeCases) { this->TestLog1pEdgeCases(); }
XLA_TYPED_TEST(MathTypedTest, IsInfOrNan) { this->TestIsInfOrNan(); }
XLA_TYPED_TEST(MathTypedTest, IsNegZero) { this->TestIsNegZero(); }
XLA_TYPED_TEST(MathTypedTest, DISABLED_ON_TPU(SqrtPowInequivalence)) {
this->TestSqrtPowInequivalence();
}
XLA_TYPED_TEST(MathTypedTest, ErfInvEdgeCases) { this->TestErfInvEdgeCases(); }
XLA_TYPED_TEST(MathTypedTest, ErfEdgeCases) { this->TestErfEdgeCases(); }
XLA_TEST_F(MathTest, RealFpOnlyOps) {
for (int64_t i = PrimitiveType_MIN; i <= PrimitiveType_MAX; ++i) {
auto ty = static_cast<PrimitiveType>(i);
SCOPED_TRACE(PrimitiveType_Name(ty));
Shape shape;
if (ty == U4 || ty == S4) {
continue;
}
if (primitive_util::IsArrayType(ty)) {
shape = ShapeUtil::MakeShape(ty, {42});
} else if (ty == PrimitiveType::TUPLE) {
shape = ShapeUtil::MakeTupleShape({});
} else if (ty == PrimitiveType::OPAQUE_TYPE) {
shape = ShapeUtil::MakeOpaqueShape();
} else if (ty == PrimitiveType::TOKEN) {
shape = ShapeUtil::MakeTokenShape();
} else {
continue;
}
for (const auto& test :
std::vector<std::pair<std::function<XlaOp(XlaOp)>, std::string>>({
{IsFinite, "is_finite"},
{IsInf, "is_inf"},
{IsPosInf, "is_pos_inf"},
{IsNegInf, "is_neg_inf"},
{IsNan, "is_nan"},
{Erf, "erf"},
{Erfc, "erfc"},
{Lgamma, "lgamma"},
{Digamma, "digamma"},
{RoundToEven, "round_to_even"},
})) {
SCOPED_TRACE(test.second);
XlaBuilder b(TestName());
XlaOp p = Parameter(&b, 0, shape, "p0");
test.first(p);
if (primitive_util::IsFloatingPointType(ty)) {
TF_EXPECT_OK(b.first_error());
} else {
EXPECT_FALSE(b.first_error().ok());
}
}
}
}
XLA_TEST_F(MathTest, SqrtF32) {
XlaBuilder builder(TestName());
Literal zero_literal = LiteralUtil::Zero(PrimitiveType::F32);
std::unique_ptr<GlobalData> zero_data =
client_->TransferToServer(zero_literal).value();
XlaOp zero = Parameter(&builder, 0, zero_literal.shape(), "zero");
Sqrt(zero);
ComputeAndCompareR0<float>(&builder, 0.0f, {zero_data.get()}, error_spec_);
}
XLA_TEST_F(MathTest, SqrtF64) {
XlaBuilder builder(TestName());
Literal zero_literal = LiteralUtil::Zero(PrimitiveType::F64);
std::unique_ptr<GlobalData> zero_data =
client_->TransferToServer(zero_literal).value();
XlaOp zero = Parameter(&builder, 0, zero_literal.shape(), "zero");
Sqrt(zero);
ComputeAndCompareR0<double>(&builder, 0.0f, {zero_data.get()}, error_spec_);
}
#ifndef XLA_BACKEND_DOES_NOT_SUPPORT_FLOAT64
XLA_TEST_F(MathTest, ErfInvF64) {
XlaBuilder builder(TestName());
auto x = ConstantR1<double>(
&builder, {-0.9, -0.8, -0.7, -0.6, -0.5, -0.4, -0.3, -0.2, -0.1, 0.0, 0.1,
0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9});
ErfInv(x);
std::vector<double> expected = {-1.163087153676674, -0.9061938024368231,
-0.732869077959217, -0.5951160814499948,
-0.4769362762044698, -0.37080715859355795,
-0.27246271472675443, -0.1791434546212916,
-0.08885599049425767, 0.,
0.08885599049425777, 0.1791434546212916,
0.27246271472675443, 0.37080715859355784,
0.4769362762044698, 0.5951160814499948,
0.732869077959217, 0.9061938024368231,
1.1630871536766736};
ComputeAndCompareR1<double>(&builder, expected, {}, ErrorSpec{1e-15});
}
#endif
XLA_TEST_F(MathTest, SquareTenValues) {
XlaBuilder builder(TestName());
auto x = ConstantR1<float>(
&builder, {2.1, -2.6, 2.6, -4.0, 2.1, 2.3, -5.0, -0.9, -2.4, 1.6});
Square(x);
std::vector<float> expected = {4.41, 6.76, 6.76, 16., 4.41,
5.29, 25., 0.81, 5.76, 2.56};
ComputeAndCompareR1<float>(&builder, expected, {}, error_spec_);
}
XLA_TEST_F(MathTest, ReciprocalTenValues) {
XlaBuilder builder(TestName());
auto x = ConstantR1<float>(
&builder, {2.1, -2.6, 2.6, -4.0, 2.1, 2.3, -5.0, -0.9, -2.4, 1.6});
Reciprocal(x);
std::vector<float> expected = {
0.47619048, -0.38461538, 0.38461538, -0.25, 0.47619048,
0.43478261, -0.2, -1.11111111, -0.41666667, 0.625};
ComputeAndCompareR1<float>(&builder, expected, {}, error_spec_);
}
XLA_TEST_F(MathTest, SqrtZeroes) {
XlaBuilder builder(TestName());
auto x = ConstantR1<float>(&builder, {0.0, -0.0});
Sqrt(x);
ComputeAndCompareR1<float>(&builder, {0, 0}, {}, error_spec_);
}
XLA_TEST_F(MathTest, SqrtSixValues) {
XlaBuilder builder(TestName());
auto x = ConstantR1<float>(&builder, {16.0, 1.0, 1024.0, 0.16, 0.2, 12345});
Sqrt(x);
std::vector<float> expected = {4, 1, 32, 0.4, 0.4472, 111.1080};
ComputeAndCompareR1<float>(&builder, expected, {}, error_spec_);
}
XLA_TEST_F(MathTest, CbrtSixF32Values) {
XlaBuilder builder(TestName());
auto x = ConstantR1<float>(&builder, {8.0, 1.0, 4096.0, -64.0, 1.728, 1331});
Cbrt(x);
std::vector<float> expected = {2, 1, 16, -4, 1.2, 11};
ComputeAndCompareR1<float>(&builder, expected, {}, ErrorSpec(0.001));
}
XLA_TEST_F(MathTest, CbrtSixF64Values) {
XlaBuilder builder(TestName());
auto x = ConstantR1<double>(&builder, {8.0, 1.0, 4096.0, -64.0, 1.728, 1331});
Cbrt(x);
std::vector<double> expected = {2, 1, 16, -4, 1.2, 11};
ComputeAndCompareR1<double>(&builder, expected, {}, ErrorSpec(0.001));
}
XLA_TEST_F(MathTest, SinhSmallValues) {
XlaBuilder builder(TestName());
auto x = ConstantR1<float>(&builder, {1e-3, 1e-5, 1e-7, 1e-9, 1e-11});
Sinh(x);
std::vector<float> expected = {1e-3, 1e-5, 1e-7, 1e-9, 1e-11};
ComputeAndCompareR1<float>(&builder, expected, {}, error_spec_);
}
XLA_TEST_F(MathTest, AsinhSmallValues) {
XlaBuilder builder(TestName());
auto x = ConstantR1<float>(&builder, {1e-3, 1e-5, 1e-7, 1e-9, 1e-11});
Asinh(x);
std::vector<float> expected = {1e-3, 1e-5, 1e-7, 1e-9, 1e-11};
ComputeAndCompareR1<float>(&builder, expected, {}, error_spec_);
}
XLA_TEST_F(MathTest, AtanhSmallValues) {
XlaBuilder builder(TestName());
auto x = ConstantR1<float>(&builder, {1e-8, 1e-9, 1e-10, 1e-11});
Atanh(x);
std::vector<float> expected = {1e-8, 1e-9, 1e-10, 1e-11};
ComputeAndCompareR1<float>(&builder, expected, {}, error_spec_);
}
XLA_TEST_F(MathTest, Lgamma) {
XlaBuilder builder(TestName());
auto x = ConstantR1<float>(&builder, {1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 0.5, 1.5,
2.5, -1.5, -3.5, -5.5});
Lgamma(x);
std::vector<float> expected = {
0,
0,
static_cast<float>(std::log(2)),
static_cast<float>(std::log(6)),
static_cast<float>(std::log(24)),
static_cast<float>(std::log(120)),
static_cast<float>(std::log(M_PI) / 2),
static_cast<float>(std::log(M_PI) / 2 - std::log(2)),
static_cast<float>(std::log(M_PI) / 2 - std::log(4) + std::log(3)),
static_cast<float>(std::log(M_PI) / 2 - std::log(3) + std::log(4)),
static_cast<float>(std::log(M_PI) / 2 - std::log(105) + std::log(16)),
static_cast<float>(std::log(M_PI) / 2 - std::log(10395) + std::log(64))};
error_spec_ = ErrorSpec{0.001};
ComputeAndCompareR1<float>(&builder, expected, {}, error_spec_);
}
#if !defined(XLA_BACKEND_DOES_NOT_SUPPORT_FLOAT16)
XLA_TEST_F(MathTest, LgammaF16) {
SetFastMathDisabled(true);
XlaBuilder b(TestName());
auto x = ConstantR1<half>(&b, {
half(-7360.0),
half(-4066.0),
half(-5.9605e-08),
});
Lgamma(x);
std::vector<half> expected = {
std::numeric_limits<half>::infinity(),
std::numeric_limits<half>::infinity(),
half(16.64),
};
ComputeAndCompareR1<half>(&b, expected, {}, ErrorSpec{0.1});
}
#endif
XLA_TEST_F(MathTest, Digamma) {
XlaBuilder builder(TestName());
auto x = ConstantR1<float>(&builder, {1.0, 0.5, 1 / 3.0, 0.25, 1 / 6.0, 0.125,
2.0, 3.0, 4.0, 6.0, 8.0, 9.0});
Digamma(x);
constexpr double euler_mascheroni =
0.57721566490153286060651209008240243104215933593992;
std::vector<float> expected = {
static_cast<float>(-euler_mascheroni),
static_cast<float>(-2 * std::log(2) - euler_mascheroni),
static_cast<float>(-M_PI / 2 / std::sqrt(3) - 3 * std::log(3) / 2 -
euler_mascheroni),
static_cast<float>(-M_PI / 2 - 3 * std::log(2) - euler_mascheroni),
static_cast<float>(-M_PI * std::sqrt(3) / 2 - 2 * std::log(2) -
3 * std::log(3) / 2 - euler_mascheroni),
static_cast<float>(
-M_PI / 2 - 4 * std::log(2) -
(M_PI + std::log(2 + std::sqrt(2)) - std::log(2 - std::sqrt(2))) /
std::sqrt(2) -
euler_mascheroni),
static_cast<float>(1 - euler_mascheroni),
static_cast<float>(1.5 - euler_mascheroni),
static_cast<float>(11 / 6.0 - euler_mascheroni),
static_cast<float>(137 / 60.0 - euler_mascheroni),
static_cast<float>(363 / 140.0 - euler_mascheroni),
static_cast<float>(761 / 280.0 - euler_mascheroni)};
ComputeAndCompareR1<float>(&builder, expected, {}, error_spec_);
}
XLA_TEST_F(MathTest, Igamma) {
XlaBuilder builder(TestName());
auto a = ConstantR3FromArray3D<float>(
&builder,
{{{0.3760359, 1.62685306, 0.53327996, 1.5111382, 0.3521143},
{1.79378175, 1.05317882, 0.85049253, 1.399534, 0.22073882},
{1.17725309, 0.90727209, 1.32418503, 1.53238533, 0.51984756}}});
auto x = ConstantR3FromArray3D<float>(
&builder,
{{{0.56420934, 8.97671773, 2.81068609, 4.50655124, 2.88178617},
{1.01795164, 8.86298411, 0.29232942, 8.17661015, 5.67652269},
{1.59959565, 0.54463897, 0.6585252, 9.83192283, 3.93372669}}});
Igamma(a, x);
Array3D<float> expected = {
{{0.78746926, 0.99940502, 0.98028261, 0.97033807, 0.99054696},
{0.33265522, 0.99983558, 0.32599159, 0.99923275, 0.99980893},
{0.74343963, 0.46703197, 0.33923541, 0.99978511, 0.99460685}}};
ComputeAndCompareR3<float>(&builder, expected, {}, error_spec_);
}
XLA_TEST_F(MathTest, IgammaSpecialValues) {
SetFastMathDisabled(true);
XlaBuilder builder(TestName());
const float nan = std::numeric_limits<float>::quiet_NaN();
auto a =
ConstantR1<float>(&builder, {nan, nan, 0.53327996, -6.00773744602e+37,
-1.3937809742e+31, -23.351348877});
auto x = ConstantR1<float>(
&builder, {nan, 8.97671773, nan, nan, 0.0, 6.02455484352e-39});
Igamma(a, x);
std::vector<float> expected = {nan, nan, nan, nan, nan, nan};
ComputeAndCompareR1<float>(&builder, expected, {}, error_spec_);
}
#if !defined(XLA_BACKEND_DOES_NOT_SUPPORT_FLOAT16)
XLA_TEST_F(MathTest, IgammaF16) {
SetFastMathDisabled(true);
XlaBuilder builder(TestName());
auto a = ConstantR3FromArray3D<half>(
&builder,
{{{half(0.37603), half(1.6268), half(0.53327), half(1.5111)},
{half(1.79378), half(1.05317), half(0.85049), half(1.3995)},
{half(1.17725), half(0.90727), half(1.32418), half(1.5323)}}});
Igamma(a, a);
Array3D<half> expected = {
{{half(0.7068214), half(0.6041154), half(0.67748886), half(0.60799426)},
{half(0.599202), half(0.6288743), half(0.64280254), half(0.6121421)},
{half(0.6220287), half(0.6384635), half(0.6152258), half(0.6072449)}}};
ComputeAndCompareR3<half>(&builder, expected, {}, ErrorSpec{1e-3});
}
#endif
XLA_TEST_F(MathTest, Igammac) {
XlaBuilder builder(TestName());
auto a = ConstantR3FromArray3D<float>(
&builder,
{{{0.3760359, 1.62685306, 0.53327996, 1.5111382, 0.3521143},
{1.79378175, 1.05317882, 0.85049253, 1.399534, 0.22073882},
{1.17725309, 0.90727209, 1.32418503, 1.53238533, 0.51984756}}});
auto x = ConstantR3FromArray3D<float>(
&builder,
{{{0.56420934, 8.97671773, 2.81068609, 4.50655124, 2.88178617},
{1.01795164, 8.86298411, 0.29232942, 8.17661015, 5.67652269},
{1.59959565, 0.54463897, 0.6585252, 9.83192283, 3.93372669}}});
Igammac(a, x);
Array3D<float> expected = {{{2.12530741e-01, 5.94977775e-04, 1.97173867e-02,
2.96619296e-02, 9.45303689e-03},
{6.67344782e-01, 1.64421996e-04, 6.74008406e-01,
7.67252602e-04, 1.91071108e-04},
{2.56560373e-01, 5.32968026e-01, 6.60764593e-01,
2.14889688e-04, 5.39314824e-03}}};
ComputeAndCompareR3<float>(&builder, expected, {}, error_spec_);
}
#if !defined(XLA_BACKEND_DOES_NOT_SUPPORT_FLOAT16)
XLA_TEST_F(MathTest, IgammacF16) {
SetFastMathDisabled(true);
XlaBuilder builder(TestName());
auto a = ConstantR3FromArray3D<half>(
&builder,
{{{half(0.37603), half(1.6268), half(0.53327), half(1.5111)},
{half(1.79378), half(1.05317), half(0.85049), half(1.3995)},
{half(1.17725), half(0.90727), half(1.32418), half(1.5323)}}});
Igammac(a, a);
Array3D<half> expected = {
{{half(0.29317862), half(0.39588454), half(0.32251117), half(0.39200574)},
{half(0.40079802), half(0.37112573), half(0.35719746), half(0.3878579)},
{half(0.3779713), half(0.36153653), half(0.38477424),
half(0.39275512)}}};
ComputeAndCompareR3<half>(&builder, expected, {}, ErrorSpec{1e-4});
}
#endif
XLA_TEST_F(MathTest, RoundToEven) {
XlaBuilder builder(TestName());
auto x = ConstantR1<float>(
&builder, {-1.4, -1.5, -2.5, -0.5, 0, 0.5, 1.5, 2.5, 3.5, 4.5});
RoundToEven(x);
std::vector<float> expected = {-1.0, -2.0, -2.0, -0.0, 0,
0.0, 2.0, 2.0, 4.0, 4.0};
ComputeAndCompareR1<float>(&builder, expected, {}, error_spec_);
}
XLA_TEST_F(MathTest, ErfRejectsComplexInputs) {
XlaBuilder b(TestName());
auto x = ConstantR1<std::complex<float>>(&b, {{0, 0}});
Erf(x);
EXPECT_FALSE(b.Build().status().ok());
}
XLA_TEST_F(MathTest, ErfcRejectsComplexInputs) {
XlaBuilder b(TestName());
auto x = ConstantR1<std::complex<float>>(&b, {{0, 0}});
Erfc(x);
EXPECT_FALSE(b.Build().status().ok());
}
XLA_TEST_F(MathTest, LgammaRejectsComplexInputs) {
XlaBuilder b(TestName());
auto x = ConstantR1<std::complex<float>>(&b, {{0, 0}});
Lgamma(x);
EXPECT_FALSE(b.Build().status().ok());
}
XLA_TEST_F(MathTest, DigammaRejectsComplexInputs) {
XlaBuilder b(TestName());
auto x = ConstantR1<std::complex<float>>(&b, {{0, 0}});
Digamma(x);
EXPECT_FALSE(b.Build().status().ok());
}
XLA_TEST_F(MathTest, RoundToEvenRejectsComplexInputs) {
XlaBuilder b(TestName());
auto x = ConstantR1<std::complex<float>>(&b, {{0, 0}});
RoundToEven(x);
EXPECT_FALSE(b.Build().status().ok());
}
XLA_TEST_F(MathTest, BesselI0eFloat) {
XlaBuilder builder(TestName());
auto x = ConstantR1<float>(
&builder,
{-20.0, -18.0, -16.0, -14.0, -12.0, -10.0, -8.0, -6.0, -4.0, -2.0, 0.0,
2.0, 4.0, 6.0, 8.0, 10.0, 12.0, 14.0, 16.0, 18.0, 20.0});
BesselI0e(x);
std::vector<float> expected = {0.0897803118848,
0.0947062952128,
0.100544127361,
0.107615251671,
0.116426221213,
0.127833337163,
0.143431781857,
0.16665743264,
0.207001921224,
0.308508322554,
1.0,
0.308508322554,
0.207001921224,
0.16665743264,
0.143431781857,
0.127833337163,
0.116426221213,
0.107615251671,
0.100544127361,
0.0947062952128,
0.0897803118848};
ComputeAndCompareR1<float>(&builder, expected, {}, error_spec_);
}
XLA_TEST_F(MathTest, DISABLED_ON_TPU(BesselI0eDouble)) {
XlaBuilder builder(TestName());
auto x = ConstantR1<double>(
&builder,
{-20.0, -18.0, -16.0, -14.0, -12.0, -10.0, -8.0, -6.0, -4.0, -2.0, 0.0,
2.0, 4.0, 6.0, 8.0, 10.0, 12.0, 14.0, 16.0, 18.0, 20.0});
BesselI0e(x);
std::vector<double> expected = {0.0897803118848,
0.0947062952128,
0.100544127361,
0.107615251671,
0.116426221213,
0.127833337163,
0.143431781857,
0.16665743264,
0.207001921224,
0.308508322554,
1.0,
0.308508322554,
0.207001921224,
0.16665743264,
0.143431781857,
0.127833337163,
0.116426221213,
0.107615251671,
0.100544127361,
0.0947062952128,
0.0897803118848};
ComputeAndCompareR1<double>(&builder, expected, {}, error_spec_);
}
XLA_TEST_F(MathTest, BesselI1eFloat) {
XlaBuilder builder(TestName());
auto x = ConstantR1<float>(
&builder,
{-20.0, -18.0, -16.0, -14.0, -12.0, -10.0, -8.0, -6.0, -4.0, -2.0, 0.0,
2.0, 4.0, 6.0, 8.0, 10.0, 12.0, 14.0, 16.0, 18.0, 20.0});
BesselI1e(x);
std::vector<float> expected = {-0.0875062221833,
-0.092036796872,
-0.0973496147565,
-0.103697667463,
-0.11146429929,
-0.121262681384,
-0.134142493293,
-0.152051459309,
-0.178750839502,
-0.215269289249,
0.0,
0.215269289249,
0.178750839502,
0.152051459309,
0.134142493293,
0.121262681384,
0.11146429929,
0.103697667463,
0.0973496147565,
0.092036796872,
0.0875062221833};
ComputeAndCompareR1<float>(&builder, expected, {}, error_spec_);
}
XLA_TEST_F(MathTest, DISABLED_ON_TPU(BesselI1eDouble)) {
XlaBuilder builder(TestName());
auto x = ConstantR1<double>(
&builder,
{-20.0, -18.0, -16.0, -14.0, -12.0, -10.0, -8.0, -6.0, -4.0, -2.0, 0.0,
2.0, 4.0, 6.0, 8.0, 10.0, 12.0, 14.0, 16.0, 18.0, 20.0});
BesselI1e(x);
std::vector<double> expected = {-0.0875062221833,
-0.092036796872,
-0.0973496147565,
-0.103697667463,
-0.11146429929,
-0.121262681384,
-0.134142493293,
-0.152051459309,
-0.178750839502,
-0.215269289249,
0.0,
0.215269289249,
0.178750839502,
0.152051459309,
0.134142493293,
0.121262681384,
0.11146429929,
0.103697667463,
0.0973496147565,
0.092036796872,
0.0875062221833};
ComputeAndCompareR1<double>(&builder, expected, {}, error_spec_);
}
XLA_TEST_F(MathTest, AcosComplexValues) {
XlaBuilder builder(TestName());
auto x = ConstantR1<std::complex<float>>(
&builder, {{0, 0}, {0, 1}, {1, 1}, {0.8, 0.2}});
Acos(x);
std::vector<std::complex<float>> expected = {
{1.5707963267948966, 0},
{1.5707963267948966, -0.881373587019543},
{0.9045568943023814, -1.0612750619050357},
{0.7011246914497526, -0.30527648462436596}};
ComputeAndCompareR1<std::complex<float>>(&builder, expected, {}, error_spec_);
}
XLA_TEST_F(MathTest, ZetaF64) {
XlaBuilder builder(TestName());
auto x = ConstantR1<double>(&builder, {2.0});
auto q = ConstantR1<double>(&builder, {1.0});
Zeta(x, q);
std::vector<double> expected = {1.64493406684823};
ComputeAndCompareR1<double>(&builder, expected, {},
ErrorSpec{0.00000000000001});
}
}
} | 2,227 |
#ifndef XLA_CLIENT_LIB_SVD_H_
#define XLA_CLIENT_LIB_SVD_H_
#include "xla/client/xla_builder.h"
#include "xla/xla_data.pb.h"
namespace xla {
struct SVDResult {
XlaOp u;
XlaOp d;
XlaOp v;
};
SVDResult SVD(XlaOp a, int64_t max_iter = 100, float epsilon = 1e-6,
PrecisionConfig::Precision precision = PrecisionConfig::HIGHEST);
}
#endif
#include "xla/client/lib/svd.h"
#include <memory>
#include <numeric>
#include <utility>
#include <vector>
#include "absl/status/statusor.h"
#include "xla/client/lib/arithmetic.h"
#include "xla/client/lib/comparators.h"
#include "xla/client/lib/constants.h"
#include "xla/client/lib/loops.h"
#include "xla/client/lib/math.h"
#include "xla/client/lib/matrix.h"
#include "xla/client/lib/slicing.h"
#include "xla/client/xla_builder.h"
#include "xla/literal_util.h"
#include "xla/shape_util.h"
#include "xla/status_macros.h"
#include "xla/xla_data.pb.h"
#include "tsl/platform/errors.h"
namespace xla {
namespace {
struct HouseHolderResult {
XlaOp v;
XlaOp beta;
XlaOp a;
};
struct JacobiRotation {
XlaOp c;
XlaOp s;
};
struct JacobiUpdate {
XlaOp v;
XlaOp w;
};
struct OneSidedJacobiRotation {
JacobiRotation rot_l;
JacobiRotation rot_r;
};
absl::StatusOr<HouseHolderResult> HouseRow(
XlaOp a, XlaOp i, XlaOp j, XlaOp eps,
PrecisionConfig::Precision precision) {
XlaBuilder* builder = a.builder();
TF_ASSIGN_OR_RETURN(Shape a_shape, builder->GetShape(a));
const int64_t num_dims = a_shape.rank();
const int64_t n = ShapeUtil::GetDimension(a_shape, -1);
XlaOp zero = ScalarLike(i, 0);
XlaOp x = DynamicSliceInMinorDims(a, {i, zero}, {1, n});
const int64_t num_batch_dims = num_dims - 2;
std::vector<int64_t> batch_dims(num_batch_dims);
for (int k = 0; k < num_batch_dims; ++k) {
batch_dims[k] = ShapeUtil::GetDimension(a_shape, k);
}
TF_ASSIGN_OR_RETURN(Shape x_shape, builder->GetShape(x));
auto idx = Iota(builder, ShapeUtil::MakeShape(S32, x_shape.dimensions()),
num_dims - 1);
auto zeros = ZerosLike(x);
auto v = Select(Gt(idx, j), x, zeros);
auto one = ScalarLike(v, 1.0);
auto sigma =
Sqrt(Reduce(Square(v), ScalarLike(v, 0.0),
CreateScalarAddComputation(x_shape.element_type(), builder),
{num_dims - 1}));
std::vector<int64_t> broadcast_dims(num_dims - 1);
std::iota(broadcast_dims.begin(), broadcast_dims.end(), 0);
auto x_0j = DynamicSliceInMinorDims(x, {zero, j}, {1, 1});
auto mu = Mul(sigma, Sqrt(Square(Div(x_0j, sigma, broadcast_dims)) + one),
broadcast_dims);
auto v_0j = Select(
Le(x_0j, ScalarLike(x_0j, 0.0)), Sub(x_0j, mu),
-Mul(sigma, Div(sigma, Add(x_0j, mu), broadcast_dims), broadcast_dims));
auto beta = Div(ScalarLike(v_0j, 2.0),
(Square(Div(sigma, v_0j, broadcast_dims)) + one));
v = Select(
BroadcastInDim(Lt(sigma, eps), x_shape.dimensions(), broadcast_dims), v,
v / v_0j);
v = Select(Eq(idx, j), zeros + one, v);
beta = Select(Lt(Add(sigma, ZerosLike(beta), broadcast_dims), eps),
ZerosLike(beta), beta);
HouseHolderResult result;
result.v = v;
result.beta = beta;
result.a = Sub(a, Mul(beta, BatchDot(BatchDot(a, false, v, true, precision),
v, precision)));
return result;
}
absl::StatusOr<HouseHolderResult> HouseCol(
XlaOp a, XlaOp i, XlaOp j, XlaOp eps,
PrecisionConfig::Precision precision) {
XlaBuilder* builder = a.builder();
TF_ASSIGN_OR_RETURN(Shape a_shape, builder->GetShape(a));
const int64_t num_dims = a_shape.rank();
const int64_t m = ShapeUtil::GetDimension(a_shape, -2);
XlaOp zero = ScalarLike(i, 0);
XlaOp x = DynamicSliceInMinorDims(a, {zero, j}, {m, 1});
const int64_t num_batch_dims = num_dims - 2;
std::vector<int64_t> batch_dims(num_batch_dims);
for (int k = 0; k < num_batch_dims; ++k) {
batch_dims[k] = ShapeUtil::GetDimension(a_shape, k);
}
TF_ASSIGN_OR_RETURN(Shape x_shape, builder->GetShape(x));
auto idx = Iota(builder, ShapeUtil::MakeShape(S32, x_shape.dimensions()),
num_dims - 2);
auto zeros = ZerosLike(x);
auto v = Select(Gt(idx, i), x, zeros);
auto one = ScalarLike(v, 1.0);
auto sigma =
Sqrt(Reduce(Square(v), ScalarLike(v, 0.0),
CreateScalarAddComputation(x_shape.element_type(), builder),
{num_dims - 2}));
std::vector<int64_t> broadcast_dims(num_dims - 1);
std::iota(broadcast_dims.begin(), broadcast_dims.end(), 0);
broadcast_dims[num_dims - 2] = num_dims - 1;
auto x_0i = DynamicSliceInMinorDims(x, {i, zero}, {1, 1});
auto mu = Mul(sigma, Sqrt(Square(Div(x_0i, sigma, broadcast_dims)) + one),
broadcast_dims);
auto v_0i = Select(
Le(x_0i, ScalarLike(x_0i, 0.0)), Sub(x_0i, mu),
-Mul(sigma, Div(sigma, Add(x_0i, mu), broadcast_dims), broadcast_dims));
auto beta = Div(ScalarLike(v_0i, 2.0),
(Square(Div(sigma, v_0i, broadcast_dims)) + one));
v = Select(
BroadcastInDim(Lt(sigma, eps), x_shape.dimensions(), broadcast_dims), v,
v / v_0i);
v = Select(Eq(idx, i), zeros + one, v);
beta = Select(Lt(Add(sigma, ZerosLike(beta), broadcast_dims), eps),
ZerosLike(beta), beta);
HouseHolderResult result;
result.v = v;
result.beta = beta;
result.a = Sub(
a, Mul(beta, BatchDot(v, false, BatchDot(v, true, a, false, precision),
false, precision)));
return result;
}
absl::StatusOr<SVDResult> HouseHolderBidiagonalization(
XlaOp a, XlaOp eps, PrecisionConfig::Precision precision) {
XlaBuilder* builder = a.builder();
TF_ASSIGN_OR_RETURN(Shape a_shape, builder->GetShape(a));
const int64_t num_dims = a_shape.rank();
const int64_t num_batch_dims = num_dims - 2;
std::vector<int64_t> batch_dims(num_batch_dims);
for (int i = 0; i < num_batch_dims; ++i) {
batch_dims[i] = ShapeUtil::GetDimension(a_shape, i);
}
const int64_t m = ShapeUtil::GetDimension(a_shape, -2);
const int64_t n = ShapeUtil::GetDimension(a_shape, -1);
XlaOp u_init = Broadcast(
IdentityMatrix(builder, a_shape.element_type(), m, m), batch_dims);
XlaOp v_init = Broadcast(
IdentityMatrix(builder, a_shape.element_type(), n, n), batch_dims);
auto while_cond_fn = [&](absl::Span<const XlaOp> values,
XlaBuilder* cond_builder) -> absl::StatusOr<XlaOp> {
auto i = values[0];
return Lt(i, ScalarLike(i, n - 2));
};
auto while_body_fn =
[&](absl::Span<const XlaOp> values,
XlaBuilder* body_builder) -> absl::StatusOr<std::vector<XlaOp>> {
auto i = values[0];
auto one = ScalarLike(i, 1);
auto u = values[1];
auto v = values[2];
auto a = values[3];
auto eps = values[4];
TF_ASSIGN_OR_RETURN(HouseHolderResult house_col,
HouseCol(a, i, i, eps, precision));
u = Sub(u,
Mul(house_col.beta, BatchDot(BatchDot(u, house_col.v, precision),
false, house_col.v, true, precision)));
a = house_col.a;
TF_ASSIGN_OR_RETURN(HouseHolderResult house_row,
HouseRow(a, i, i + one, eps, precision));
v = Sub(v, Mul(house_row.beta,
BatchDot(BatchDot(v, false, house_row.v, true, precision),
house_row.v, precision)));
a = house_row.a;
std::vector<XlaOp> updated_values;
updated_values.reserve(values.size());
updated_values.push_back(i + one);
updated_values.push_back(u);
updated_values.push_back(v);
updated_values.push_back(a);
updated_values.push_back(eps);
return updated_values;
};
std::vector<XlaOp> values(5);
values[0] = Zero(builder, S32);
values[1] = u_init;
values[2] = v_init;
values[3] = a;
values[4] = eps;
TF_ASSIGN_OR_RETURN(values,
WhileLoopHelper(while_cond_fn, while_body_fn, values,
"HouseHolderBidiagonalization", builder));
for (int k = 2; k > 0; --k) {
if (n - k >= 0) {
XlaOp index = ScalarLike(values[0], n - k);
TF_ASSIGN_OR_RETURN(HouseHolderResult house_col,
HouseCol(values[3], index, index, eps, precision));
values[1] = Sub(values[1],
Mul(house_col.beta,
BatchDot(BatchDot(values[1], house_col.v, precision),
false, house_col.v, true, precision)));
values[3] = house_col.a;
}
}
SVDResult result;
result.u = values[1];
result.v = values[2];
result.d = values[3];
return result;
}
absl::StatusOr<JacobiRotation> MakeJacobi(XlaOp ps, XlaOp qs, XlaOp pqs,
XlaOp eps) {
auto zero = ScalarLike(ps, 0.0);
auto one = ScalarLike(ps, 1.0);
auto two = ScalarLike(ps, 2.0);
auto tau = (qs - ps) / (pqs * two);
auto t_pos = one / (tau + Sqrt(one + Square(tau)));
auto t_neg = -one / (-tau + Sqrt(one + Square(tau)));
auto t = Select(Ge(tau, zero), t_pos, t_neg);
auto c_temp = Rsqrt(one + Square(t));
auto s_temp = t * c_temp;
auto c = Select(Ge(Abs(pqs), eps), c_temp, ZerosLike(c_temp) + one);
auto s = Select(Ge(Abs(pqs), eps), s_temp, ZerosLike(s_temp));
auto rnorm = Rsqrt(Square(c) + Square(s));
JacobiRotation rot;
rot.c = c * rnorm;
rot.s = s * rnorm;
return rot;
}
absl::StatusOr<OneSidedJacobiRotation> GetOneSidedJacobiRotation(XlaOp a,
XlaOp p,
XlaOp q,
XlaOp eps) {
XlaOp a_pp = DynamicSliceInMinorDims(a, {p, p}, {1, 1});
XlaOp a_pq = DynamicSliceInMinorDims(a, {p, q}, {1, 1});
XlaOp a_qp = DynamicSliceInMinorDims(a, {q, p}, {1, 1});
XlaOp a_qq = DynamicSliceInMinorDims(a, {q, q}, {1, 1});
XlaOp one = ScalarLike(a, 1.0);
XlaOp t = a_pp + a_qq;
XlaOp d = a_qp - a_pq;
XlaOp u = Div(t, d);
XlaOp tmp = Rsqrt(one + Square(u));
JacobiRotation rot;
XlaOp zeros = ZerosLike(tmp);
XlaOp ones = zeros + one;
rot.s = Select(Lt(Abs(d), eps), zeros, -tmp);
rot.c = Select(Lt(Abs(d), eps), ones, Mul(u, tmp));
XlaOp a_pp_new = rot.c * a_pp - rot.s * a_qp;
XlaOp a_pq_new = rot.c * a_pq - rot.s * a_qq;
XlaOp a_qq_new = rot.s * a_pq + rot.c * a_qq;
OneSidedJacobiRotation rots;
TF_ASSIGN_OR_RETURN(rots.rot_r,
MakeJacobi(a_pp_new, a_qq_new, a_pq_new, eps));
rots.rot_l.c = rot.c * rots.rot_r.c - rot.s * rots.rot_r.s;
rots.rot_l.s = rot.s * rots.rot_r.c + rot.c * rots.rot_r.s;
return rots;
}
absl::StatusOr<SVDResult> OneSidedJacobiUpdate(SVDResult svd_result, XlaOp p,
XlaOp q, XlaOp eps) {
XlaOp u = svd_result.u;
XlaOp v = svd_result.v;
XlaOp d = svd_result.d;
XlaBuilder* builder = d.builder();
TF_ASSIGN_OR_RETURN(Shape d_shape, builder->GetShape(d));
const int64_t num_dims = d_shape.rank();
const int64_t num_batch_dims = num_dims - 2;
std::vector<int64_t> batch_dims(num_batch_dims);
for (int i = 0; i < num_batch_dims; ++i) {
batch_dims[i] = ShapeUtil::GetDimension(d_shape, i);
}
const int64_t m = ShapeUtil::GetDimension(d_shape, -2);
const int64_t n = ShapeUtil::GetDimension(d_shape, -1);
TF_ASSIGN_OR_RETURN(OneSidedJacobiRotation onesided_jacobi,
GetOneSidedJacobiRotation(d, p, q, eps));
auto zero = ScalarLike(p, 0);
std::vector<int64_t> pq_dims(batch_dims.begin(), batch_dims.end());
pq_dims.push_back(1);
pq_dims.push_back(1);
auto pq_zero = ScalarLike(d, 0.0);
auto pq_zeros = Broadcast(pq_zero, pq_dims);
std::vector<int64_t> broadcast_dims(batch_dims.size());
std::iota(broadcast_dims.begin(), broadcast_dims.end(), 0);
broadcast_dims.push_back(num_dims - 1);
auto slice_p = DynamicSliceInMinorDims(d, {p, zero}, {1, n});
auto slice_q = DynamicSliceInMinorDims(d, {q, zero}, {1, n});
auto slice_p_new =
onesided_jacobi.rot_l.c * slice_p - onesided_jacobi.rot_l.s * slice_q;
auto slice_q_new =
onesided_jacobi.rot_l.s * slice_p + onesided_jacobi.rot_l.c * slice_q;
d = DynamicUpdateSliceInMinorDims(d, slice_p_new, {p, zero});
d = DynamicUpdateSliceInMinorDims(d, slice_q_new, {q, zero});
slice_p = DynamicSliceInMinorDims(d, {zero, p}, {m, 1});
slice_q = DynamicSliceInMinorDims(d, {zero, q}, {m, 1});
slice_p_new =
onesided_jacobi.rot_r.c * slice_p - onesided_jacobi.rot_r.s * slice_q;
slice_q_new =
onesided_jacobi.rot_r.s * slice_p + onesided_jacobi.rot_r.c * slice_q;
d = DynamicUpdateSliceInMinorDims(d, slice_p_new, {zero, p});
d = DynamicUpdateSliceInMinorDims(d, slice_q_new, {zero, q});
d = DynamicUpdateSliceInMinorDims(d, pq_zeros, {p, q});
d = DynamicUpdateSliceInMinorDims(d, pq_zeros, {q, p});
slice_p = DynamicSliceInMinorDims(u, {zero, p}, {m, 1});
slice_q = DynamicSliceInMinorDims(u, {zero, q}, {m, 1});
slice_p_new =
onesided_jacobi.rot_l.c * slice_p - onesided_jacobi.rot_l.s * slice_q;
slice_p_new = Mul(
slice_p_new,
Rsqrt(Reduce(Square(slice_p_new), pq_zero,
CreateScalarAddComputation(d_shape.element_type(), builder),
{num_dims - 2})),
broadcast_dims);
slice_q_new =
onesided_jacobi.rot_l.s * slice_p + onesided_jacobi.rot_l.c * slice_q;
slice_q_new = Mul(
slice_q_new,
Rsqrt(Reduce(Square(slice_q_new), pq_zero,
CreateScalarAddComputation(d_shape.element_type(), builder),
{num_dims - 2})),
broadcast_dims);
u = DynamicUpdateSliceInMinorDims(u, slice_p_new, {zero, p});
u = DynamicUpdateSliceInMinorDims(u, slice_q_new, {zero, q});
slice_p = DynamicSliceInMinorDims(v, {zero, p}, {n, 1});
slice_q = DynamicSliceInMinorDims(v, {zero, q}, {n, 1});
slice_p_new =
onesided_jacobi.rot_r.c * slice_p - onesided_jacobi.rot_r.s * slice_q;
slice_p_new = Mul(
slice_p_new,
Rsqrt(Reduce(Square(slice_p_new), pq_zero,
CreateScalarAddComputation(d_shape.element_type(), builder),
{num_dims - 2})),
broadcast_dims);
slice_q_new =
onesided_jacobi.rot_r.s * slice_p + onesided_jacobi.rot_r.c * slice_q;
slice_q_new = Mul(
slice_q_new,
Rsqrt(Reduce(Square(slice_q_new), pq_zero,
CreateScalarAddComputation(d_shape.element_type(), builder),
{num_dims - 2})),
broadcast_dims);
v = DynamicUpdateSliceInMinorDims(v, slice_p_new, {zero, p});
v = DynamicUpdateSliceInMinorDims(v, slice_q_new, {zero, q});
svd_result.d = d;
svd_result.u = u;
svd_result.v = v;
return svd_result;
}
absl::StatusOr<XlaOp> ComputeToleranceComparison(XlaOp w, XlaOp epsilon) {
XlaBuilder* builder = w.builder();
TF_ASSIGN_OR_RETURN(Shape shape, builder->GetShape(w));
auto num_dims = static_cast<int32_t>(shape.rank());
int64_t n = shape.dimensions(num_dims - 1);
shape.set_dimensions(num_dims - 2, n);
auto w_sliced = SliceInMinorDims(w, {0, 0}, {n, n});
auto diag = GetMatrixDiagonal(w_sliced);
diag = Select(Lt(diag, ZerosLike(diag)), -diag, diag);
std::vector<int64_t> broadcasted_dims(num_dims - 1);
std::iota(broadcasted_dims.begin(), broadcasted_dims.end(), 0);
auto broadcast_to_rows =
BroadcastInDim(diag, shape.dimensions(), broadcasted_dims);
broadcasted_dims.back() = num_dims - 1;
auto broadcast_to_columns =
BroadcastInDim(diag, shape.dimensions(), broadcasted_dims);
XlaOp tolerance;
if (builder->GetShape(epsilon)->element_type() == BF16 ||
builder->GetShape(epsilon)->element_type() == F16) {
auto upscale_eps = ConvertElementType(epsilon, F32);
tolerance = ConvertElementType(broadcast_to_rows, F32) *
ConvertElementType(broadcast_to_columns, F32) * upscale_eps *
upscale_eps;
tolerance = ConvertElementType(tolerance,
builder->GetShape(epsilon)->element_type());
} else {
tolerance = broadcast_to_rows * broadcast_to_columns * epsilon * epsilon;
}
return Lt(tolerance, Square(Select(GetDiagonalMask(w_sliced),
ZerosLike(w_sliced), w_sliced)));
}
absl::StatusOr<std::vector<XlaOp>> WhileLoopFn(
absl::Span<const XlaOp> initial_values,
int matrix_dimension,
int max_sweep_updates,
absl::string_view name,
XlaBuilder* builder) {
auto while_cond_fn = [&](absl::Span<const XlaOp> values,
XlaBuilder* cond_builder) -> absl::StatusOr<XlaOp> {
auto k = values[0];
auto max_sweeps = ScalarLike(k, max_sweep_updates);
auto sweep_update_cond = Gt(max_sweeps, k);
TF_ASSIGN_OR_RETURN(auto tolerance_comparison,
ComputeToleranceComparison(values[3], values[4]));
auto tolerance_cond = ReduceAll(
tolerance_comparison, xla::ConstantR0<bool>(cond_builder, false),
CreateScalarOrComputation(PRED, cond_builder));
return And(sweep_update_cond, tolerance_cond);
};
auto while_body_fn =
[&](absl::Span<const XlaOp> values,
XlaBuilder* body_builder) -> absl::StatusOr<std::vector<XlaOp>> {
auto while_cond_fn_inner =
[&](absl::Span<const XlaOp> values_inner,
XlaBuilder* inner_cond_builder) -> absl::StatusOr<XlaOp> {
auto p = values_inner[0];
return Lt(p, ScalarLike(p, matrix_dimension - 1));
};
auto while_body_fn_inner = [&](absl::Span<const XlaOp> values_inner,
XlaBuilder* inner_body_builder)
-> absl::StatusOr<std::vector<XlaOp>> {
auto while_cond_fn_innermost =
[&](absl::Span<const XlaOp> values_innermost,
XlaBuilder* innermost_cond_builder) -> absl::StatusOr<XlaOp> {
auto q = values_innermost[1];
return Lt(q, ScalarLike(q, matrix_dimension));
};
auto while_body_fn_innermost =
[&](absl::Span<const XlaOp> values_innermost,
XlaBuilder* innermost_body_builder)
-> absl::StatusOr<std::vector<XlaOp>> {
auto p = values_innermost[0];
auto q = values_innermost[1];
SVDResult onesided_jacobi_update;
onesided_jacobi_update.u = values_innermost[2];
onesided_jacobi_update.v = values_innermost[3];
onesided_jacobi_update.d = values_innermost[4];
auto eps = values_innermost[5];
TF_ASSIGN_OR_RETURN(
onesided_jacobi_update,
OneSidedJacobiUpdate(onesided_jacobi_update, p, q, eps));
std::vector<XlaOp> updated_values_innermost;
updated_values_innermost.reserve(values_innermost.size());
updated_values_innermost.push_back(p);
updated_values_innermost.push_back(q + ScalarLike(q, 1));
updated_values_innermost.push_back(onesided_jacobi_update.u);
updated_values_innermost.push_back(onesided_jacobi_update.v);
updated_values_innermost.push_back(onesided_jacobi_update.d);
updated_values_innermost.push_back(eps);
return updated_values_innermost;
};
std::vector<XlaOp> values_innermost(6);
auto p = values_inner[0];
auto q = p + ScalarLike(p, 1);
values_innermost[0] = p;
values_innermost[1] = q;
values_innermost[2] = values_inner[1];
values_innermost[3] = values_inner[2];
values_innermost[4] = values_inner[3];
values_innermost[5] = values_inner[4];
TF_ASSIGN_OR_RETURN(
values_innermost,
WhileLoopHelper(while_cond_fn_innermost, while_body_fn_innermost,
values_innermost, absl::StrCat(name, "-Innermost"),
inner_body_builder));
std::vector<XlaOp> updated_values_inner;
updated_values_inner.reserve(values_inner.size());
updated_values_inner.push_back(p + ScalarLike(p, 1));
updated_values_inner.push_back(values_innermost[2]);
updated_values_inner.push_back(values_innermost[3]);
updated_values_inner.push_back(values_innermost[4]);
updated_values_inner.push_back(values_innermost[5]);
return updated_values_inner;
};
XlaOp k = values[0];
std::vector<XlaOp> values_inner(5);
values_inner[0] = ScalarLike(k, 0);
values_inner[1] = values[1];
values_inner[2] = values[2];
values_inner[3] = values[3];
values_inner[4] = values[4];
TF_ASSIGN_OR_RETURN(
values_inner,
WhileLoopHelper(while_cond_fn_inner, while_body_fn_inner, values_inner,
absl::StrCat(name, "-Inner"), body_builder));
std::vector<XlaOp> updated_values;
updated_values.reserve(values_inner.size());
updated_values.push_back(k + ScalarLike(k, 1));
updated_values.push_back(values_inner[1]);
updated_values.push_back(values_inner[2]);
updated_values.push_back(values_inner[3]);
updated_values.push_back(values_inner[4]);
return updated_values;
};
std::vector<XlaOp> values;
TF_ASSIGN_OR_RETURN(values, WhileLoopHelper(while_cond_fn, while_body_fn,
initial_values, name, builder));
return values;
}
absl::StatusOr<SVDResult> SortBySingularValuesAndPostProcessing(
SVDResult result) {
XlaBuilder* builder = result.d.builder();
TF_ASSIGN_OR_RETURN(Shape shape, builder->GetShape(result.d));
const int64_t num_dims = shape.rank();
auto dimensions = shape.dimensions();
const int64_t m = ShapeUtil::GetDimension(shape, -2);
const int64_t n = ShapeUtil::GetDimension(shape, -1);
std::vector<int64_t> broadcast_dims(num_dims - 1);
std::iota(broadcast_dims.begin(), broadcast_dims.end(), 0);
broadcast_dims[num_dims - 2] = num_dims - 1;
auto d = GetMatrixDiagonal(result.d);
auto zeros = ZerosLike(d);
auto one = ScalarLike(d, 1.0);
auto sign = Select(Ge(d, zeros), zeros + one, zeros - one);
d = Select(Ge(d, zeros), d, -d);
result.v = Mul(result.v, sign, broadcast_dims);
d = BroadcastInDim(d, dimensions, broadcast_dims);
XlaOp sort_u_result =
Sort({d, SliceInMinorDims(result.u, {0, 0}, {m, n})},
CreateScalarGtComputation(
{shape.element_type(), shape.element_type()}, builder),
num_dims - 1);
XlaOp sort_v_result =
Sort({SliceInMinorDims(d, {0, 0}, {n, n}), result.v},
CreateScalarGtComputation(
{shape.element_type(), shape.element_type()}, builder),
num_dims - 1);
result.d = GetMatrixDiagonal(GetTupleElement(sort_v_result, 0));
result.v = GetTupleElement(sort_v_result, 1);
result.v = Mul(
result.v,
Rsqrt(Reduce(Square(result.v), ScalarLike(d, 0.0),
CreateScalarAddComputation(shape.element_type(), builder),
{num_dims - 2})),
broadcast_dims);
result.u = ConcatInDim(builder,
{GetTupleElement(sort_u_result, 1),
SliceInMinorDims(result.u, {0, n}, {m, m})},
num_dims - 1);
result.u = Mul(
result.u,
Rsqrt(Reduce(Square(result.u), ScalarLike(d, 0.0),
CreateScalarAddComputation(shape.element_type(), builder),
{num_dims - 2})),
broadcast_dims);
return result;
}
}
SVDResult SVD(XlaOp a, int64_t max_iter, float epsilon,
PrecisionConfig::Precision precision) {
XlaBuilder* builder = a.builder();
auto return_error = [&](const absl::Status& status) {
SVDResult result;
result.u = builder->ReportError(status);
result.v = builder->ReportError(status);
result.d = builder->ReportError(status);
return result;
};
auto shape_with_status = builder->GetShape(a);
if (!shape_with_status.status().ok()) {
return return_error(shape_with_status.status());
}
Shape a_shape = shape_with_status.value();
const int64_t num_dims = a_shape.rank();
const int64_t num_batch_dims = num_dims - 2;
std::vector<int64_t> batch_dims(num_batch_dims);
for (int i = 0; i < num_batch_dims; ++i) {
batch_dims[i] = ShapeUtil::GetDimension(a_shape, i);
}
int64_t m = ShapeUtil::GetDimension(a_shape, -2);
int64_t n = ShapeUtil::GetDimension(a_shape, -1);
bool maybe_transpose = m < n;
if (maybe_transpose) {
a = TransposeInMinorDims(a);
std::swap( | #include "xla/client/lib/svd.h"
#include <numeric>
#include <utility>
#include <vector>
#include "absl/status/statusor.h"
#include "xla/array2d.h"
#include "xla/array3d.h"
#include "xla/client/lib/arithmetic.h"
#include "xla/client/lib/constants.h"
#include "xla/client/lib/matrix.h"
#include "xla/client/lib/slicing.h"
#include "xla/client/xla_builder.h"
#include "xla/literal.h"
#include "xla/shape_util.h"
#include "xla/test.h"
#include "xla/tests/client_library_test_base.h"
#include "xla/tests/literal_test_util.h"
#include "xla/tests/test_macros.h"
#include "xla/xla_data.pb.h"
#include "tsl/lib/core/status_test_util.h"
namespace xla {
class SVDTest : public ClientLibraryTestBase {
protected:
void SetUp() override {
ClientLibraryTestBase::SetUp();
batch_3d_4x5_ = Array3D<float>{
{
{4, 6, 8, 10, 1},
{6, 45, 54, 63, 1},
{8, 54, 146, 166, 1},
{10, 63, 166, 310, 1},
},
{
{16, 24, 8, 12, 6},
{24, 61, 82, 48, 5},
{8, 82, 100, 6, 4},
{12, 48, 6, 62, 3},
},
};
}
void TearDown() override { ClientLibraryTestBase::TearDown(); }
Array3D<float> GetUnitMatrix3D(int32_t batch_dim, int32_t mat_dim) {
Array3D<float> result(batch_dim, mat_dim, mat_dim, 0.0);
for (int i = 0; i < batch_dim; ++i) {
for (int j = 0; j < mat_dim; ++j) {
result({i, j, j}) = 1.0;
}
}
return result;
}
XlaOp ComputeMatmulUDVT(SVDResult result, XlaBuilder* builder) {
Shape u_shape = builder->GetShape(result.u).value();
Shape v_shape = builder->GetShape(result.v).value();
int64_t m = ShapeUtil::GetDimension(u_shape, -1);
int64_t n = ShapeUtil::GetDimension(v_shape, -1);
auto v = result.v;
auto u = result.u;
auto d = result.d;
if (m > n) {
u = SliceInMinorDims(u, {0, 0}, {m, n});
} else if (m < n) {
v = SliceInMinorDims(v, {0, 0}, {n, m});
}
int num_dims = u_shape.rank();
std::vector<int64_t> broadcast_dims(num_dims - 1);
std::iota(broadcast_dims.begin(), broadcast_dims.end(), 0);
broadcast_dims[num_dims - 2] = num_dims - 1;
return BatchDot(Mul(u, d, broadcast_dims), TransposeInMinorDims(v),
PrecisionConfig::HIGHEST);
}
XlaOp GetAverageAbsoluteError(XlaOp m1, XlaOp m2, XlaBuilder* builder) {
Shape shape = builder->GetShape(m1).value();
int64_t size = 1;
for (auto d : shape.dimensions()) {
size *= d;
}
return ReduceAll(Abs(m1 - m2), ConstantR0WithType(builder, F32, 0),
CreateScalarAddComputation(F32, builder)) /
ConstantR0WithType(builder, F32, size);
}
Array2D<float> GenerateRandomMatrix(int xsize, int ysize) {
Array2D<float> result{xsize, ysize, 0.0};
result.FillRandom(10 , 2 );
return result;
}
Array3D<float> batch_3d_4x5_;
};
XLA_TEST_F(SVDTest, Simple2D) {
XlaBuilder builder(TestName());
Array2D<float> simple_2d_4x4_ = Array2D<float>{
{4, 6, 8, 10},
{6, 45, 54, 63},
{8, 54, 146, 166},
{10, 63, 166, 310},
};
XlaOp a;
auto a_data = CreateR2Parameter<float>(simple_2d_4x4_, 0, "a", &builder, &a);
auto result = SVD(a, 100, 1e-6);
ComputeMatmulUDVT(result, &builder);
ComputeAndCompareR2<float>(&builder, simple_2d_4x4_, {a_data.get()},
ErrorSpec(1e-3, 1e-3));
}
XLA_TEST_F(SVDTest, Test_VWVt_EQ_A_2x4x5) {
XlaBuilder builder(TestName());
XlaOp a;
auto a_data = CreateR3Parameter<float>(batch_3d_4x5_, 0, "a", &builder, &a);
auto result = SVD(a, 100, 1e-8);
ComputeMatmulUDVT(result, &builder);
ComputeAndCompareR3<float>(&builder, batch_3d_4x5_, {a_data.get()},
ErrorSpec(1e-3, 1e-3));
}
XLA_TEST_F(SVDTest, Test_Orthogonality_U) {
XlaBuilder builder(TestName());
XlaOp a;
auto a_data = CreateR3Parameter<float>(batch_3d_4x5_, 0, "a", &builder, &a);
auto result = SVD(a, 100, 1e-8);
ComputeMatmulUDVT(result, &builder);
BatchDot(result.u, TransposeInMinorDims(result.u));
ComputeAndCompareR3<float>(&builder, GetUnitMatrix3D(2, 4), {a_data.get()},
ErrorSpec(1e-2, 1e-2));
}
XLA_TEST_F(SVDTest, Test_Orthogonality_V) {
XlaBuilder builder(TestName());
XlaOp a;
auto a_data = CreateR3Parameter<float>(batch_3d_4x5_, 0, "a", &builder, &a);
auto result = SVD(a, 100, 1e-8);
BatchDot(result.v, TransposeInMinorDims(result.v), PrecisionConfig::HIGHEST);
ComputeAndCompareR3<float>(&builder, GetUnitMatrix3D(2, 5), {a_data.get()},
ErrorSpec(1e-3, 1e-3));
}
XLA_TEST_F(SVDTest, TestSingleValuesMatchNumpy) {
XlaBuilder builder(TestName());
auto singular_values = Array2D<float>{
{431.05153007, 49.88334164, 20.94464584, 3.24845468},
{179.73128591, 68.05162245, 21.77679503, 13.94319712},
};
XlaOp a;
auto a_data = CreateR3Parameter<float>(batch_3d_4x5_, 0, "a", &builder, &a);
auto result = SVD(a, 100, 1e-8);
Add(result.d, ZerosLike(result.d));
ComputeAndCompareR2<float>(&builder, singular_values, {a_data.get()},
ErrorSpec(1e-3, 1e-3));
}
XLA_TEST_F(SVDTest,
DISABLED_ON_INTERPRETER(Various_Size_Random_Matrix_512x128)) {
XlaBuilder builder(TestName());
Array2D<float> a_val = GenerateRandomMatrix(512, 128);
XlaOp a;
auto a_data = CreateR2Parameter<float>(a_val, 0, "a", &builder, &a);
auto result = SVD(a, 100, 1e-4);
GetAverageAbsoluteError(ComputeMatmulUDVT(result, &builder), a, &builder);
ComputeAndCompareR0<float>(&builder, 1e-3, {a_data.get()},
ErrorSpec(1e-3, 1e-3));
}
XLA_TEST_F(SVDTest, Various_Size_Random_Matrix_128x256) {
XlaBuilder builder(TestName());
Array2D<float> a_val = GenerateRandomMatrix(128, 256);
XlaOp a;
auto a_data = CreateR2Parameter<float>(a_val, 0, "a", &builder, &a);
auto result = SVD(a, 100, 1e-4);
GetAverageAbsoluteError(ComputeMatmulUDVT(result, &builder), a, &builder);
ComputeAndCompareR0<float>(&builder, 1e-3, {a_data.get()},
ErrorSpec(1e-3, 1e-3));
}
XLA_TEST_F(SVDTest, Various_Size_Random_Matrix_256x128) {
XlaBuilder builder(TestName());
Array2D<float> a_val = GenerateRandomMatrix(256, 128);
XlaOp a;
auto a_data = CreateR2Parameter<float>(a_val, 0, "a", &builder, &a);
auto result = SVD(a, 100, 1e-4);
GetAverageAbsoluteError(ComputeMatmulUDVT(result, &builder), a, &builder);
ComputeAndCompareR0<float>(&builder, 1e-3, {a_data.get()},
ErrorSpec(1e-3, 1e-3));
}
XLA_TEST_F(SVDTest,
DISABLED_ON_INTERPRETER(Various_Size_Random_Matrix_128x512)) {
XlaBuilder builder(TestName());
Array2D<float> a_val = GenerateRandomMatrix(128, 512);
XlaOp a;
auto a_data = CreateR2Parameter<float>(a_val, 0, "a", &builder, &a);
auto result = SVD(a, 100, 1e-4);
GetAverageAbsoluteError(ComputeMatmulUDVT(result, &builder), a, &builder);
ComputeAndCompareR0<float>(&builder, 1e-3, {a_data.get()},
ErrorSpec(1e-3, 1e-3));
}
XLA_TEST_F(SVDTest, DISABLED_ON_CPU(DISABLED_ON_INTERPRETER(
Various_Size_Random_Matrix_512x256))) {
XlaBuilder builder(TestName());
Array2D<float> a_val = GenerateRandomMatrix(512, 256);
XlaOp a;
auto a_data = CreateR2Parameter<float>(a_val, 0, "a", &builder, &a);
auto result = SVD(a, 100, 1e-4);
GetAverageAbsoluteError(ComputeMatmulUDVT(result, &builder), a, &builder);
ComputeAndCompareR0<float>(&builder, 1e-3, {a_data.get()},
ErrorSpec(1e-3, 1e-3));
}
XLA_TEST_F(SVDTest, DISABLED_ON_GPU(DISABLED_ON_CPU(DISABLED_ON_INTERPRETER(
Various_Size_Random_Matrix_512x512)))) {
XlaBuilder builder(TestName());
Array2D<float> a_val = GenerateRandomMatrix(512, 512);
XlaOp a;
auto a_data = CreateR2Parameter<float>(a_val, 0, "a", &builder, &a);
auto result = SVD(a, 100, 1e-4);
GetAverageAbsoluteError(ComputeMatmulUDVT(result, &builder), a, &builder);
ComputeAndCompareR0<float>(&builder, 1e-3, {a_data.get()},
ErrorSpec(1e-3, 1e-3));
}
} | 2,228 |
#ifndef XLA_CLIENT_LIB_SORTING_H_
#define XLA_CLIENT_LIB_SORTING_H_
#include "xla/client/xla_builder.h"
#include "xla/types.h"
#include "xla/xla_data.pb.h"
namespace xla {
XlaOp TopK(XlaOp input, int64_t k,
PrimitiveType index_type = PrimitiveType::S32);
XlaOp TopKWithPartitions(XlaOp input, int64_t k, int64_t num_partitions = 1,
PrimitiveType index_type = PrimitiveType::S32);
}
#endif
#include "xla/client/lib/sorting.h"
#include <vector>
#include "xla/client/lib/comparators.h"
#include "xla/client/lib/constants.h"
#include "xla/client/lib/loops.h"
#include "xla/client/lib/slicing.h"
#include "xla/client/xla_builder.h"
#include "xla/shape_util.h"
#include "xla/util.h"
#include "xla/xla_data.pb.h"
namespace xla {
XlaOp TopK(XlaOp input, int64_t k, PrimitiveType index_type) {
XlaBuilder* const builder = input.builder();
return builder->ReportErrorOrReturn([&]() -> absl::StatusOr<XlaOp> {
TF_ASSIGN_OR_RETURN(Shape input_shape, builder->GetShape(input));
int last_dim = input_shape.dimensions_size() - 1;
int64_t last_dim_size = input_shape.dimensions(last_dim);
const int64_t kPerPartitionSize = 8192;
const int64_t kLastDimSizeThreshold = 524288;
const int64_t kMinNumPartitions = 8;
const int64_t kMinimalK = 1000;
if ((k >= kMinimalK) && (k < kPerPartitionSize) &&
(kPerPartitionSize / k > 2) && last_dim_size >= kLastDimSizeThreshold) {
int64_t num_partitions =
CeilOfRatio(last_dim_size - k, kPerPartitionSize - k);
if (num_partitions >= kMinNumPartitions) {
return TopKWithPartitions(input, k, num_partitions, index_type);
}
}
Shape iota_shape =
ShapeUtil::MakeShape(index_type, input_shape.dimensions());
XlaOp iota = Iota(builder, iota_shape, last_dim);
for (int64_t i = 0; i < input_shape.rank(); ++i) {
if (input_shape.is_dynamic_dimension(i)) {
iota = SetDimensionSize(iota, GetDimensionSize(input, i), i);
}
}
auto input_dims = input_shape.dimensions();
constexpr int32_t kLow16BitsLimit = int32_t{1} << 16;
constexpr int32_t kLow16BitsMask = kLow16BitsLimit - 1;
constexpr int32_t kHigh16BitsMask = ~kLow16BitsMask;
constexpr int kMaxLastDimSizeForSmallBatches = 1500;
constexpr int kSmallBatchSizeThreshold = 8;
const bool use_packed_bf16_sort =
(input_shape.element_type() == BF16 &&
last_dim_size < kLow16BitsLimit &&
(last_dim_size < kMaxLastDimSizeForSmallBatches ||
(input_shape.rank() == 2 &&
input_shape.dimensions(0) >= kSmallBatchSizeThreshold)));
std::vector<int64_t> start_indices(input_shape.dimensions_size(), 0);
std::vector<int64_t> limit_indices(input_dims.begin(), input_dims.end());
limit_indices[last_dim] = k;
std::vector<int64_t> strides(input_shape.dimensions_size(), 1);
XlaOp values;
XlaOp indices;
if (use_packed_bf16_sort) {
auto sign_magnitude_to_from_ones_complement = [builder](const XlaOp in) {
constexpr int32_t kAllNonSignBits = 0x7fffffff;
XlaOp in_s32 = BitcastConvertType(in, S32);
return Xor(
And(in_s32, ConstantR0<int32_t>(builder, kAllNonSignBits)),
ShiftRightArithmetic(in_s32, ConstantR0<int32_t>(builder, 31)));
};
XlaOp input_f32_trimmed =
Or(sign_magnitude_to_from_ones_complement(
BitcastConvertType(ConvertElementType(input, F32), S32)),
ConstantR0<int32_t>(builder, kLow16BitsMask));
XlaOp input_and_iota = Xor(input_f32_trimmed, iota);
XlaOp sort_result_raw =
Sort({input_and_iota},
CreateScalarGtComputation({index_type}, builder), last_dim,
false);
sort_result_raw =
Slice(sort_result_raw, start_indices, limit_indices, strides);
sort_result_raw = RemoveDynamicDimension(sort_result_raw, last_dim);
values = ConvertElementType(
BitcastConvertType(
And(sign_magnitude_to_from_ones_complement(sort_result_raw),
ConstantR0<int32_t>(builder, kHigh16BitsMask)),
F32),
BF16);
indices = And(
Xor(sort_result_raw, ConstantR0<int32_t>(builder, kLow16BitsMask)),
ConstantR0<int32_t>(builder, kLow16BitsMask));
} else {
XlaOp sort_result =
Sort({input, iota},
CreateScalarGtComputation(
{input_shape.element_type(), index_type}, iota.builder()),
last_dim, true);
values = Slice(GetTupleElement(sort_result, 0), start_indices,
limit_indices, strides);
values = RemoveDynamicDimension(values, last_dim);
indices = Slice(GetTupleElement(sort_result, 1), start_indices,
limit_indices, strides);
indices = RemoveDynamicDimension(indices, last_dim);
}
return Tuple(builder, {values, indices});
});
}
XlaOp TopKWithPartitions(XlaOp input, int64_t k, int64_t num_partitions,
PrimitiveType index_type) {
XlaBuilder* const builder = input.builder();
return builder->ReportErrorOrReturn([&]() -> absl::StatusOr<XlaOp> {
TF_ASSIGN_OR_RETURN(Shape input_shape, builder->GetShape(input));
int last_dim = input_shape.dimensions_size() - 1;
auto input_dims = input_shape.dimensions();
int64_t last_dim_size = input_shape.dimensions(last_dim);
const int64_t per_partition_size =
CeilOfRatio(last_dim_size, num_partitions);
if (k >= per_partition_size) {
return TopK(input, k, index_type);
}
Shape iota_shape =
ShapeUtil::MakeShape(index_type, input_shape.dimensions());
XlaOp iota = Iota(builder, iota_shape, last_dim);
for (int64_t i = 0; i < input_shape.rank(); ++i) {
if (input_shape.is_dynamic_dimension(i)) {
iota = SetDimensionSize(iota, GetDimensionSize(input, i), i);
}
}
auto topk_body_fn =
[&](XlaOp partition, absl::Span<const XlaOp> values_and_indices,
XlaBuilder* builder) -> absl::StatusOr<std::vector<XlaOp>> {
auto values = values_and_indices[0];
auto indices = values_and_indices[1];
auto input = values_and_indices[2];
auto iota = values_and_indices[3];
XlaOp start =
Mul(Add(partition, One(builder, index_type)),
ConstantR0WithType(builder, index_type, per_partition_size));
XlaOp sliced_input =
DynamicSliceInMinorDims(input, {start}, {per_partition_size});
XlaOp sliced_indices =
DynamicSliceInMinorDims(iota, {start}, {per_partition_size});
sliced_input = ConcatInDim(builder, {values, sliced_input}, last_dim);
sliced_indices =
ConcatInDim(builder, {indices, sliced_indices}, last_dim);
XlaOp sort_result = Sort(
{sliced_input, sliced_indices},
CreateScalarGtComputation({input_shape.element_type(), index_type},
sliced_indices.builder()),
last_dim, true);
std::vector<int64_t> start_indices(input_shape.dimensions_size(), 0);
std::vector<int64_t> limit_indices(input_dims.begin(), input_dims.end());
std::vector<int64_t> strides(input_shape.dimensions_size(), 1);
start_indices[last_dim] = 0;
limit_indices[last_dim] = k;
values = Slice(GetTupleElement(sort_result, 0), start_indices,
limit_indices, strides);
indices = Slice(GetTupleElement(sort_result, 1), start_indices,
limit_indices, strides);
return std::vector<XlaOp>{values, indices, input, iota};
};
std::vector<int64_t> start_indices(input_shape.dimensions_size(), 0);
std::vector<int64_t> limit_indices(input_dims.begin(), input_dims.end());
std::vector<int64_t> strides(input_shape.dimensions_size(), 1);
start_indices[last_dim] = 0;
limit_indices[last_dim] = per_partition_size;
XlaOp sliced_input = Slice(input, start_indices, limit_indices, strides);
XlaOp sliced_indices = Slice(iota, start_indices, limit_indices, strides);
XlaOp sort_result =
Sort({sliced_input, sliced_indices},
CreateScalarGtComputation({input_shape.element_type(), index_type},
sliced_indices.builder()),
last_dim, true);
start_indices[last_dim] = 0;
limit_indices[last_dim] = k;
XlaOp values = Slice(GetTupleElement(sort_result, 0), start_indices,
limit_indices, strides);
XlaOp indices = Slice(GetTupleElement(sort_result, 1), start_indices,
limit_indices, strides);
TF_ASSIGN_OR_RETURN(
auto values_and_indices,
ForEachIndex(num_partitions - 1, index_type, topk_body_fn,
{values, indices, input, iota}, "topk_with_partition",
builder));
return Tuple(builder, {values_and_indices[0], values_and_indices[1]});
});
}
} | #include "xla/client/lib/sorting.h"
#include <algorithm>
#include <functional>
#include <limits>
#include <random>
#include <vector>
#include "xla/client/xla_builder.h"
#include "xla/test.h"
#include "xla/tests/client_library_test_base.h"
#include "xla/tests/test_macros.h"
#include "xla/types.h"
namespace xla {
namespace {
using SortingTest = ClientLibraryTestBase;
XLA_TEST_F(SortingTest, TopK3From8Values) {
XlaBuilder builder(TestName());
auto x =
ConstantR1<float>(&builder, {0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0});
xla::GetTupleElement(xla::TopK(x, 3), 0);
ComputeAndCompareR1<float>(&builder, {7.0, 6.0, 5.0}, {});
}
XLA_TEST_F(SortingTest, TopK3From8Indices) {
XlaBuilder builder(TestName());
auto x_rev =
ConstantR1<float>(&builder, {7.0, 6.0, 5.0, 4.0, 3.0, 2.0, 1.0, 0.0});
xla::GetTupleElement(xla::TopK(x_rev, 3), 1);
ComputeAndCompareR1<int>(&builder, {0, 1, 2}, {});
}
XLA_TEST_F(SortingTest, TopK3From8Int16Indices) {
XlaBuilder builder(TestName());
auto x =
ConstantR1<float>(&builder, {0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0});
xla::GetTupleElement(xla::TopK(x, 3, PrimitiveType::S16), 1);
ComputeAndCompareR1<int16_t>(&builder, {7, 6, 5}, {});
}
XLA_TEST_F(SortingTest, TopKFullSortMinInt) {
XlaBuilder builder(TestName());
auto x_rev = ConstantR1<int>(&builder, {std::numeric_limits<int>::min(),
std::numeric_limits<int>::min() + 1,
std::numeric_limits<int>::max()});
xla::GetTupleElement(xla::TopK(x_rev, 3), 1);
ComputeAndCompareR1<int>(&builder, {2, 1, 0}, {});
}
XLA_TEST_F(SortingTest, TopKFullSort) {
XlaBuilder builder(TestName());
const int kSize = 16;
std::mt19937 eng;
std::uniform_real_distribution<float> u_dist(0.0, 100.0);
auto gen = std::bind(u_dist, eng);
std::vector<float> inputs(kSize);
std::generate(inputs.begin(), inputs.end(), gen);
auto x = ConstantR1<float>(&builder, inputs);
xla::GetTupleElement(xla::TopK(x, kSize), 0);
absl::c_sort(inputs, std::greater<float>());
ComputeAndCompareR1<float>(&builder, inputs, {});
}
XLA_TEST_F(SortingTest, TopKFullSortWithDuplicates) {
XlaBuilder builder(TestName());
XlaOp a;
auto a_data = CreateR1Parameter<int>({1, 1, 2, 2, 1}, 0, "a", &builder, &a);
xla::GetTupleElement(xla::TopK(a, 5), 1);
ComputeAndCompareR1<int>(&builder, {2, 3, 0, 1, 4}, {a_data.get()});
}
XLA_TEST_F(SortingTest, TopK3From8Values2Partitions) {
XlaBuilder builder(TestName());
auto x =
ConstantR1<float>(&builder, {0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0});
xla::GetTupleElement(xla::TopKWithPartitions(x, 3, 2), 0);
ComputeAndCompareR1<float>(&builder, {7.0, 6.0, 5.0}, {});
}
XLA_TEST_F(SortingTest, TopK3From8Indices2Partitions) {
XlaBuilder builder(TestName());
auto x_rev =
ConstantR1<float>(&builder, {7.0, 6.0, 5.0, 4.0, 3.0, 2.0, 1.0, 0.0});
xla::GetTupleElement(xla::TopKWithPartitions(x_rev, 3, 2),
1);
ComputeAndCompareR1<int>(&builder, {0, 1, 2}, {});
}
XLA_TEST_F(SortingTest, TopK3From8Values3Partitions) {
XlaBuilder builder(TestName());
auto x =
ConstantR1<float>(&builder, {0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0});
xla::GetTupleElement(xla::TopKWithPartitions(x, 3, 3), 0);
ComputeAndCompareR1<float>(&builder, {7.0, 6.0, 5.0}, {});
}
XLA_TEST_F(SortingTest, TopK3From8Indices3Partitions) {
XlaBuilder builder(TestName());
auto x_rev =
ConstantR1<float>(&builder, {7.0, 6.0, 5.0, 4.0, 3.0, 2.0, 1.0, 0.0});
xla::GetTupleElement(xla::TopKWithPartitions(x_rev, 3, 3),
1);
ComputeAndCompareR1<int>(&builder, {0, 1, 2}, {});
}
XLA_TEST_F(SortingTest, TopK3From8Values5Partitions) {
XlaBuilder builder(TestName());
auto x =
ConstantR1<float>(&builder, {0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0});
xla::GetTupleElement(xla::TopKWithPartitions(x, 3, 5), 0);
ComputeAndCompareR1<float>(&builder, {7.0, 6.0, 5.0}, {});
}
XLA_TEST_F(SortingTest, DISABLED_TopKLargeInput) {
XlaBuilder builder(TestName());
Array<float> input({2, 1000000});
input.FillRandom(1.0f, 2.0f);
auto x =
CreateConstantFromLiteral(LiteralUtil::CreateFromArray(input), &builder);
Array2D<float> expected_array(2, 1000);
expected_array.Fill(2.0f);
xla::GetTupleElement(xla::TopK(x, 1000), 0);
ErrorSpec error_spec(10.0f, 10.0f);
ComputeAndCompareR2<float>(&builder, expected_array, {}, error_spec);
}
XLA_TEST_F(SortingTest, TopK3From8Indices5Partitions) {
XlaBuilder builder(TestName());
auto x_rev =
ConstantR1<float>(&builder, {7.0, 6.0, 5.0, 4.0, 3.0, 2.0, 1.0, 0.0});
xla::GetTupleElement(xla::TopKWithPartitions(x_rev, 3, 5),
1);
ComputeAndCompareR1<int>(&builder, {0, 1, 2}, {});
}
XLA_TEST_F(SortingTest, TopK3From8Int16Indices5Partitions) {
XlaBuilder builder(TestName());
auto x_rev =
ConstantR1<float>(&builder, {7.0, 6.0, 5.0, 4.0, 3.0, 2.0, 1.0, 0.0});
xla::GetTupleElement(xla::TopKWithPartitions(x_rev, 3, 5,
PrimitiveType::S16),
1);
ComputeAndCompareR1<int16_t>(&builder, {0, 1, 2}, {});
}
XLA_TEST_F(SortingTest, TopKFullSortWithDuplicates2Partitions) {
XlaBuilder builder(TestName());
XlaOp a;
auto a_data = CreateR1Parameter<int>({1, 1, 2, 2, 1}, 0, "a", &builder, &a);
xla::GetTupleElement(xla::TopKWithPartitions(a, 3, 2), 1);
ComputeAndCompareR1<int>(&builder, {2, 3, 0}, {a_data.get()});
}
}
} | 2,229 |
#ifndef XLA_CLIENT_LIB_SELF_ADJOINT_EIG_H_
#define XLA_CLIENT_LIB_SELF_ADJOINT_EIG_H_
#include "xla/client/xla_builder.h"
#include "xla/xla_data.pb.h"
namespace xla {
struct SelfAdjointEigResult {
XlaOp v;
XlaOp w;
};
SelfAdjointEigResult SelfAdjointEig(XlaOp a, bool lower = true,
int64_t max_iter = 15, float tol = 1e-5,
bool sort_eigenvalues = true);
}
#endif
#include "xla/client/lib/self_adjoint_eig.h"
#include <memory>
#include <string>
#include <vector>
#include "absl/status/statusor.h"
#include "xla/client/lib/arithmetic.h"
#include "xla/client/lib/comparators.h"
#include "xla/client/lib/constants.h"
#include "xla/client/lib/loops.h"
#include "xla/client/lib/math.h"
#include "xla/client/lib/matrix.h"
#include "xla/client/lib/slicing.h"
#include "xla/client/xla_builder.h"
#include "xla/literal_util.h"
#include "xla/primitive_util.h"
#include "xla/shape_util.h"
#include "xla/status_macros.h"
#include "xla/util.h"
#include "tsl/platform/errors.h"
namespace xla {
SelfAdjointEigResult SelfAdjointEig(XlaOp a, bool lower, int64_t max_iter,
float tol, bool sort_eigenvalues) {
XlaBuilder* builder = a.builder();
XlaOp result = builder->ReportErrorOrReturn([&]() -> absl::StatusOr<XlaOp> {
TF_ASSIGN_OR_RETURN(Shape a_shape, builder->GetShape(a));
const int64_t num_dims = a_shape.rank();
if (num_dims < 2) {
return InvalidArgument(
"Arguments to Eigen decomposition must have rank >= 2: got shape %s.",
a_shape.ToString());
}
PrimitiveType type = a_shape.element_type();
if (!primitive_util::IsFloatingPointType(type) &&
!primitive_util::IsComplexType(type)) {
return InvalidArgument(
"Type of the input matrix must be floating point "
"or complex: got %s.",
a_shape.ToString());
}
const int64_t m = ShapeUtil::GetDimension(a_shape, -2);
const int64_t n = ShapeUtil::GetDimension(a_shape, -1);
if (m != n) {
return InvalidArgument(
"Arguments to symmetric eigendecomposition must be square matrices: "
"got shape (%d, %d).",
m, n);
}
const int num_batch_dims = a_shape.dimensions().size() - 2;
const std::vector<int64_t> batch_dims(
a_shape.dimensions().begin(),
a_shape.dimensions().begin() + num_batch_dims);
PrimitiveType eigvals_type =
primitive_util::IsComplexType(type)
? primitive_util::ComplexComponentType(type)
: type;
std::vector<int64_t> eigvals_dims = batch_dims;
eigvals_dims.push_back(m);
Shape eigh_shape = ShapeUtil::MakeTupleShape(
{a_shape, ShapeUtil::MakeShape(eigvals_type, eigvals_dims)});
std::string opaque =
absl::StrFormat("%d,%d,%d,%f", lower, sort_eigenvalues, max_iter, tol);
return CustomCall(a.builder(), "Eigh", {a}, eigh_shape, opaque);
});
return SelfAdjointEigResult{GetTupleElement(result, 0),
GetTupleElement(result, 1)};
}
} | #include "xla/client/lib/self_adjoint_eig.h"
#include <algorithm>
#include <numeric>
#include <vector>
#include "absl/status/statusor.h"
#include "xla/array.h"
#include "xla/array2d.h"
#include "xla/array3d.h"
#include "xla/client/lib/arithmetic.h"
#include "xla/client/lib/constants.h"
#include "xla/client/lib/math.h"
#include "xla/client/lib/matrix.h"
#include "xla/client/xla_builder.h"
#include "xla/literal.h"
#include "xla/test.h"
#include "xla/tests/client_library_test_base.h"
#include "xla/tests/literal_test_util.h"
#include "xla/tests/test_macros.h"
#include "xla/xla_data.pb.h"
#include "tsl/lib/core/status_test_util.h"
namespace xla {
class SelfAdjointEigTest : public ClientLibraryTestBase {
protected:
void SetUp() override {
ClientLibraryTestBase::SetUp();
batch_3d_4x4_ = Array3D<float>{
{
{4, 6, 8, 10},
{6, 45, 54, 63},
{8, 54, 146, 166},
{10, 63, 166, 310},
},
{
{16, 24, 8, 12},
{24, 61, 82, 48},
{8, 82, 100, 6},
{12, 48, 6, 62},
},
};
matrix2d_8x8_ = Array2D<float>{
{14., 123., 49., 112., 115., 173., 182., 125.},
{123., 14., 60., 118., 150., 130., 91., 72.},
{49., 60., 138., 111., 106., 101., 115., 142.},
{112., 118., 111., 142., 91., 130., 25., 61.},
{115., 150., 106., 91., 116., 121., 128., 85.},
{173., 130., 101., 130., 121., 70., 151., 132.},
{182., 91., 115., 25., 128., 151., 66., 92.},
{125., 72., 142., 61., 85., 132., 92., 156.},
};
low_rank_4x4_ = Array2D<float>{
{2, 1, 4, 3},
{1, 5, 5, 9},
{4, 5, 10, 11},
{3, 9, 11, 17},
};
}
void TearDown() override { ClientLibraryTestBase::TearDown(); }
Array3D<float> GetUnitMatrix3D(const Array3D<float>& matrix) {
Array3D<float> result(matrix.n1(), matrix.n2(), matrix.n3(), 0.0);
for (int i = 0; i < matrix.n1(); ++i) {
for (int j = 0; j < matrix.n2(); ++j) {
result({i, j, j}) = 1.0;
}
}
return result;
}
Array3D<float> ExtractTriangularMatrix(const Array3D<float>& matrix,
bool lower) {
Array3D<float> result(matrix);
for (int i = 0; i < result.n1(); ++i) {
for (int j = 0; j < result.n2(); ++j) {
if (lower) {
for (int k = j + 1; k < result.n3(); ++k) {
result({i, j, k}) = 0.0;
}
} else {
for (int k = 0; k < j; ++k) {
result({i, j, k}) = 0.0;
}
}
}
}
return result;
}
Array3D<float> batch_3d_4x4_;
Array2D<float> matrix2d_8x8_;
Array2D<float> low_rank_4x4_;
Array2D<int> wrong_type_4x4_;
};
XlaOp GetAverageAbsoluteError(XlaOp m1, XlaOp m2, XlaBuilder* builder) {
Shape shape = builder->GetShape(m1).value();
int64_t size = ShapeUtil::ElementsIn(shape);
return ReduceAll(Abs(m1 - m2), ConstantR0WithType(builder, F32, 0),
CreateScalarAddComputation(F32, builder)) /
ConstantR0WithType(builder, F32, std::max<int64_t>(1, size));
}
XlaOp ComputeMatmulVWVt(SelfAdjointEigResult result, XlaBuilder* builder) {
Shape shape = builder->GetShape(result.v).value();
absl::Span<const int64_t> out_dims = shape.dimensions();
std::vector<int64_t> broadcast_dims(shape.rank() - 1);
std::iota(broadcast_dims.begin(), broadcast_dims.end(), 0);
broadcast_dims[shape.rank() - 2] = shape.rank() - 1;
auto vw =
Mul(result.v,
BroadcastInDim(ConvertElementType(result.w, shape.element_type()),
out_dims, broadcast_dims));
return BatchDot(vw, MaybeConjugate(TransposeInMinorDims(result.v), true),
PrecisionConfig::HIGHEST);
}
XLA_TEST_F(SelfAdjointEigTest, Test_VWVt_EQ_A_2x4x4) {
for (bool sort_eigenvalues : {false, true}) {
XlaBuilder builder(TestName());
XlaOp a;
auto a_data = CreateR3Parameter<float>(batch_3d_4x4_, 0, "a", &builder, &a);
auto result = SelfAdjointEig(a, true, 15,
1e-5, sort_eigenvalues);
ComputeMatmulVWVt(result, &builder);
ComputeAndCompareR3<float>(&builder, batch_3d_4x4_, {a_data.get()},
ErrorSpec(1e-3, 1e-3));
}
}
XLA_TEST_F(SelfAdjointEigTest, Test_VWVt_EQ_A_3x3_Complex) {
XlaBuilder builder(TestName());
Array<complex64> input = {
{1, complex64{2, -7}, complex64{4, -8}},
{complex64{2, 7}, 3, complex64{5, -9}},
{complex64{4, 8}, complex64{5, 9}, 6},
};
XlaOp a;
auto a_data = CreateParameter<complex64>(input, 0, "a", &builder, &a);
auto result = SelfAdjointEig(a);
ComputeMatmulVWVt(result, &builder);
ComputeAndCompare<complex64>(&builder, input, {a_data.get()},
ErrorSpec(1e-3, 1e-3));
}
XLA_TEST_F(SelfAdjointEigTest, Test_VWVt_EQ_A_Lower_2x4x4) {
XlaBuilder builder(TestName());
XlaOp a;
auto a_data = CreateR3Parameter<float>(
ExtractTriangularMatrix(batch_3d_4x4_, true), 0, "a", &builder, &a);
auto result = SelfAdjointEig(a);
ComputeMatmulVWVt(result, &builder);
ComputeAndCompareR3<float>(&builder, batch_3d_4x4_, {a_data.get()},
ErrorSpec(1e-3, 1e-3));
}
XLA_TEST_F(SelfAdjointEigTest, Test_VWVt_EQ_A_Upper_2x4x4) {
XlaBuilder builder(TestName());
XlaOp a;
auto a_data = CreateR3Parameter<float>(
ExtractTriangularMatrix(batch_3d_4x4_, false), 0, "a", &builder, &a);
auto result = SelfAdjointEig(a, false);
ComputeMatmulVWVt(result, &builder);
ComputeAndCompareR3<float>(&builder, batch_3d_4x4_, {a_data.get()},
ErrorSpec(1e-3, 1e-3));
}
XLA_TEST_F(SelfAdjointEigTest, Test_Orthogonality_2x4x4) {
XlaBuilder builder(TestName());
XlaOp a;
auto a_data = CreateR3Parameter<float>(batch_3d_4x4_, 0, "a", &builder, &a);
auto result = SelfAdjointEig(a);
BatchDot(result.v, TransposeInMinorDims(result.v), PrecisionConfig::HIGHEST);
ComputeAndCompareR3<float>(&builder, GetUnitMatrix3D(batch_3d_4x4_),
{a_data.get()}, ErrorSpec(1e-3, 1e-3));
}
XLA_TEST_F(SelfAdjointEigTest, Test_VtWV_EQ_A_Rank_Deficient_4x4) {
XlaBuilder builder(TestName());
XlaOp a;
auto a_data = CreateR2Parameter<float>(low_rank_4x4_, 0, "a", &builder, &a);
auto result = SelfAdjointEig(a);
ComputeMatmulVWVt(result, &builder);
ComputeAndCompareR2<float>(&builder, low_rank_4x4_, {a_data.get()},
ErrorSpec(1e-3, 1e-3));
}
XLA_TEST_F(SelfAdjointEigTest, Test_Eigen_8x8) {
XlaBuilder builder(TestName());
std::vector<float> expected{-182.69205, -116.86245, -105.74489, -9.545369,
37.81711, 104.732285, 120.29153, 868.00385};
XlaOp a;
auto a_data = CreateR2Parameter<float>(matrix2d_8x8_, 0, "a", &builder, &a);
auto result = SelfAdjointEig(a);
Add(result.w, ZerosLike(result.w));
ComputeAndCompareR1<float>(&builder, expected, {a_data.get()},
ErrorSpec(1e-3, 1e-3));
}
XLA_TEST_F(SelfAdjointEigTest, Test_Orthogonality_8x8) {
XlaBuilder builder(TestName());
float expected_vals = 1e-3;
XlaOp a;
auto a_data = CreateR2Parameter<float>(matrix2d_8x8_, 0, "a", &builder, &a);
auto result = SelfAdjointEig(a);
GetAverageAbsoluteError(IdentityMatrix(&builder, F32, 8, 8),
BatchDot(TransposeInMinorDims(result.v), result.v),
&builder);
ComputeAndCompareR0<float>(&builder, expected_vals, {a_data.get()},
ErrorSpec(1e-3, 1e-3));
}
XLA_TEST_F(SelfAdjointEigTest, Wrong_Type_Int) {
XlaBuilder builder(TestName());
XlaOp a;
auto a_data = CreateR2Parameter<int>(wrong_type_4x4_, 0, "a", &builder, &a);
auto result = SelfAdjointEig(a);
EXPECT_FALSE(result.v.valid());
EXPECT_FALSE(result.w.valid());
}
Array2D<float> GenerateRandomSymmetricMatrix(int size) {
Array2D<float> result{size, size, 0.0};
result.FillRandom(10 , 2 , 12346 );
for (int i = 0; i < size; ++i) {
for (int j = 0; j < i; ++j) {
result({j, i}) = result({i, j});
}
}
return result;
}
using EighTestCase = int64_t;
class RandomEighTest : public ClientLibraryTestBase,
public ::testing::WithParamInterface<EighTestCase> {};
XLA_TEST_P(RandomEighTest, Random) {
XlaBuilder builder(TestName());
int64_t size = GetParam();
Array2D<float> a_val = GenerateRandomSymmetricMatrix(size);
XlaOp a;
auto a_data = CreateR2Parameter<float>(a_val, 0, "a", &builder, &a);
auto result = SelfAdjointEig(a);
GetAverageAbsoluteError(ComputeMatmulVWVt(result, &builder), a, &builder);
double kExpected = 0.00300000003;
ComputeAndCompareR0<float>(&builder, kExpected, {a_data.get()},
ErrorSpec(kExpected, 0));
}
#ifndef XLA_TEST_BACKEND_CPU
INSTANTIATE_TEST_SUITE_P(
RandomEighTestInstantiation, RandomEighTest,
::testing::Values(0, 1, 2, 3, 8, 16, 32, 77, 129, 203, 256, 257, 493, 511,
512,
513, 1000),
[](const ::testing::TestParamInfo<EighTestCase>& info) {
const int64_t size = info.param;
return absl::StrCat(size);
});
#else
INSTANTIATE_TEST_SUITE_P(
RandomEighTestInstantiation, RandomEighTest,
::testing::Values(0, 1, 2, 3, 8, 16, 32, 77, 129, 203, 256, 257, 493, 511,
512),
[](const ::testing::TestParamInfo<EighTestCase>& info) {
const int64_t size = info.param;
return absl::StrCat(size);
});
#endif
} | 2,230 |
#ifndef XLA_MLIR_TOOLS_MLIR_INTERPRETER_DIALECTS_COMPARATORS_H_
#define XLA_MLIR_TOOLS_MLIR_INTERPRETER_DIALECTS_COMPARATORS_H_
#include <complex>
#include <cstdint>
#include <type_traits>
#include "llvm/Support/ErrorHandling.h"
#include "xla/mlir/tools/mlir_interpreter/framework/interpreter_value_util.h"
namespace mlir {
namespace interpreter {
template <int64_t v, bool r, bool nan_result>
struct FloatCompare : CwiseAll {
template <typename T>
static bool Apply(T a, T b) {
if (isnan(a) || isnan(b)) return nan_result;
if constexpr (v == 0) {
return (a == b) == r;
} else if constexpr (std::is_floating_point_v<T> || std::is_integral_v<T>) {
auto cmp = a > b ? 1 : (a < b ? -1 : 0);
return (cmp == v) == r;
} else {
llvm_unreachable("operation not supported for this type");
}
}
template <typename T>
static bool isnan(T a) {
return std::isnan(a);
}
template <typename T>
static bool isnan(std::complex<T> a) {
return std::isnan(std::real(a)) || std::isnan(std::imag(a));
}
};
using Foeq = FloatCompare<0, true, false>;
using Foge = FloatCompare<-1, false, false>;
using Fogt = FloatCompare<1, true, false>;
using Fole = FloatCompare<1, false, false>;
using Folt = FloatCompare<-1, true, false>;
using Fone = FloatCompare<0, false, false>;
using Ford = FloatCompare<99, false, false>;
using Fueq = FloatCompare<0, true, true>;
using Fuge = FloatCompare<-1, false, true>;
using Fugt = FloatCompare<1, true, true>;
using Fule = FloatCompare<1, false, true>;
using Fult = FloatCompare<-1, true, true>;
using Fune = FloatCompare<0, false, true>;
using Funo = FloatCompare<99, true, true>;
template <int64_t v, bool r>
struct UnsignedCompare : CwiseInt {
template <typename T>
static bool Apply(T a, T b) {
using U = std::make_unsigned_t<T>;
auto a_u = static_cast<U>(a);
auto b_u = static_cast<U>(b);
auto cmp = a_u > b_u ? 1 : (a_u < b_u ? -1 : 0);
return (cmp == v) == r;
}
};
using Iuge = UnsignedCompare<-1, false>;
using Iule = UnsignedCompare<1, false>;
using Iugt = UnsignedCompare<1, true>;
using Iult = UnsignedCompare<-1, true>;
struct Iumax {
template <typename T>
static T apply(T a, T b) {
return Iuge::Apply(a, b) ? a : b;
}
};
struct Iumin {
template <typename T>
static T apply(T a, T b) {
return Iule::Apply(a, b) ? a : b;
}
};
}
}
#endif
#include "xla/client/lib/comparators.h"
#include <limits>
#include <optional>
#include <string>
#include <vector>
#include "absl/log/check.h"
#include "absl/strings/str_cat.h"
#include "absl/types/span.h"
#include "xla/client/lib/constants.h"
#include "xla/client/xla_builder.h"
#include "xla/client/xla_computation.h"
#include "xla/primitive_util.h"
#include "xla/shape_util.h"
#include "xla/types.h"
#include "xla/util.h"
#include "xla/xla_data.pb.h"
namespace xla {
namespace {
using XlaCompareOp = XlaOp (*)(XlaOp, XlaOp, absl::Span<const int64_t>);
XlaComputation CreateScalarComparisonComputation(
const std::string& name, const std::vector<PrimitiveType>& operand_types,
XlaBuilder* builder, XlaCompareOp generator) {
CHECK_NE(operand_types.size(), 0);
std::vector<std::optional<XlaCompareOp>> generators(operand_types.size());
generators[0] = generator;
return CreateScalarComparisonComputation(name, operand_types, generators,
builder);
}
}
XlaComputation CreateScalarComparisonComputation(
const std::string& name, const std::vector<PrimitiveType>& operand_types,
const std::vector<std::optional<XlaCompareOp>>& generators,
XlaBuilder* builder) {
auto b = builder->CreateSubBuilder(name);
if (operand_types.empty()) {
b->ReportError(InvalidArgument("operand_types should not be empty"));
return b->BuildAndNoteError();
}
CHECK_EQ(operand_types.size(), generators.size());
int parameter_count = 0;
int last_generator_index = 0;
std::vector<XlaOp> lhs_params;
std::vector<XlaOp> rhs_params;
for (auto operand_type : operand_types) {
auto scalar_shape = ShapeUtil::MakeShape(operand_type, {});
auto lhs_param = Parameter(b.get(), parameter_count * 2, scalar_shape,
absl::StrCat("p.", parameter_count, ".lhs"));
auto rhs_param = Parameter(b.get(), parameter_count * 2 + 1, scalar_shape,
absl::StrCat("p.", parameter_count, ".rhs"));
lhs_params.emplace_back(lhs_param);
rhs_params.emplace_back(rhs_param);
if (generators[parameter_count].has_value()) {
last_generator_index = parameter_count;
}
parameter_count++;
}
CHECK_NE(parameter_count, 0);
XlaOp result;
XlaOp prev_equal;
for (int i = 0; i < parameter_count; i++) {
if (generators[i].has_value()) {
XlaOp cmp_op = generators[i].value()(lhs_params[i], rhs_params[i], {});
result = prev_equal.valid() ? Select(prev_equal, cmp_op, result) : cmp_op;
if (i != last_generator_index) {
XlaOp eq_op = EqTotalOrder(lhs_params[i], rhs_params[i]);
prev_equal = prev_equal.valid() ? And(prev_equal, eq_op) : eq_op;
}
}
}
CHECK(result.valid());
return b->BuildAndNoteError();
}
XlaComputation CreateScalarLtComputation(
const std::vector<PrimitiveType>& operand_types, XlaBuilder* builder) {
return CreateScalarComparisonComputation("compare-less-than", operand_types,
builder, LtTotalOrder);
}
XlaComputation CreateScalarGtComputation(
const std::vector<PrimitiveType>& operand_types, XlaBuilder* builder) {
return CreateScalarComparisonComputation(
"compare-greater-than", operand_types, builder, GtTotalOrder);
}
} | #include "xla/client/lib/comparators.h"
#include <cmath>
#include <limits>
#include <vector>
#include "absl/container/inlined_vector.h"
#include "absl/strings/string_view.h"
#include "xla/client/lib/constants.h"
#include "xla/client/xla_builder.h"
#include "xla/client/xla_computation.h"
#include "xla/hlo/ir/hlo_opcode.h"
#include "xla/primitive_util.h"
#include "xla/service/hlo.pb.h"
#include "xla/test.h"
#include "xla/tests/client_library_test_base.h"
#include "xla/tests/test_macros.h"
#include "xla/xla_data.pb.h"
#include "tsl/platform/protobuf.h"
namespace xla {
namespace {
class ComparatorsTest : public ClientLibraryTestBase {
public:
ComparatorsTest() : builder_(TestName()) {}
XlaBuilder* builder() { return &builder_; }
private:
XlaBuilder builder_;
};
template <
PrimitiveType type,
typename T = typename primitive_util::PrimitiveTypeToNative<type>::type>
void BuildComparatorAndComparisons(ComparatorsTest* test,
bool compare_less_than,
absl::InlinedVector<bool, 10>* expected) {
auto compare = compare_less_than
? CreateScalarLtComputation({type}, test->builder())
: CreateScalarGtComputation({type}, test->builder());
auto negative_nan = ConstantR0<T>(
test->builder(), -T(std::numeric_limits<float>::quiet_NaN()));
auto positive_nan = ConstantR0<T>(test->builder(),
T(std::numeric_limits<float>::quiet_NaN()));
auto negative_zero = ConstantR0<T>(test->builder(), T(-0.));
auto positive_zero = ConstantR0<T>(test->builder(), T(0.));
auto negative_infinity = MinValue(test->builder(), type);
auto positive_infinity = MaxValue(test->builder(), type);
std::vector<XlaOp> all_constants{negative_nan, negative_infinity,
negative_zero, positive_zero,
positive_infinity, positive_nan};
std::vector<XlaOp> all_comparisons;
all_comparisons.reserve(std::pow(all_constants.size(), 2));
for (const XlaOp& lhs_constant : all_constants) {
for (const XlaOp& rhs_constant : all_constants) {
all_comparisons.push_back(Broadcast(
Call(test->builder(), compare, {lhs_constant, rhs_constant}), {1}));
}
}
ConcatInDim(test->builder(), all_comparisons, 0);
expected->clear();
for (int i = 0; i < all_constants.size(); ++i) {
for (int j = 0; j < all_constants.size(); ++j) {
expected->push_back(compare_less_than ? i < j : i > j);
}
}
}
XLA_TEST_F(ComparatorsTest, CompareLtBF16) {
absl::InlinedVector<bool, 10> expected;
BuildComparatorAndComparisons<BF16>(this, true,
&expected);
ComputeAndCompareR1<bool>(builder(), expected, {});
}
XLA_TEST_F(ComparatorsTest, CompareGtBF16) {
absl::InlinedVector<bool, 10> expected;
BuildComparatorAndComparisons<BF16>(this, false,
&expected);
ComputeAndCompareR1<bool>(builder(), expected, {});
}
XLA_TEST_F(ComparatorsTest, CompareLtF16) {
absl::InlinedVector<bool, 10> expected;
BuildComparatorAndComparisons<F16>(this, true,
&expected);
ComputeAndCompareR1<bool>(builder(), expected, {});
}
XLA_TEST_F(ComparatorsTest, CompareGtF16) {
absl::InlinedVector<bool, 10> expected;
BuildComparatorAndComparisons<F16>(this, false,
&expected);
ComputeAndCompareR1<bool>(builder(), expected, {});
}
XLA_TEST_F(ComparatorsTest, CompareLtF32) {
absl::InlinedVector<bool, 10> expected;
BuildComparatorAndComparisons<F32>(this, true,
&expected);
ComputeAndCompareR1<bool>(builder(), expected, {});
}
XLA_TEST_F(ComparatorsTest, CompareGtF32) {
absl::InlinedVector<bool, 10> expected;
BuildComparatorAndComparisons<F32>(this, false,
&expected);
ComputeAndCompareR1<bool>(builder(), expected, {});
}
XLA_TEST_F(ComparatorsTest, CompareLtF64) {
absl::InlinedVector<bool, 10> expected;
BuildComparatorAndComparisons<F64>(this, true,
&expected);
ComputeAndCompareR1<bool>(builder(), expected, {});
}
XLA_TEST_F(ComparatorsTest, CompareGtF64) {
absl::InlinedVector<bool, 10> expected;
BuildComparatorAndComparisons<F64>(this, false,
&expected);
ComputeAndCompareR1<bool>(builder(), expected, {});
}
const auto kCompareStr = HloOpcodeString(xla::HloOpcode::kCompare);
const auto kParameterStr = HloOpcodeString(xla::HloOpcode::kParameter);
const auto kSelectStr = HloOpcodeString(xla::HloOpcode::kSelect);
void ExpectCompareOp(
const xla::HloInstructionProto op, xla::PrimitiveType type,
absl::string_view direction, int parameter0_number, int parameter1_number,
const tsl::protobuf::RepeatedPtrField<xla::HloInstructionProto>& all_ops) {
EXPECT_EQ(op.opcode(), kCompareStr);
const auto& operand0 = all_ops.at(op.operand_ids(0) - 1);
EXPECT_EQ(operand0.opcode(), kParameterStr);
EXPECT_EQ(operand0.parameter_number(), parameter0_number);
EXPECT_EQ(operand0.shape().element_type(), type);
const auto& operand1 = all_ops.at(op.operand_ids(1) - 1);
EXPECT_EQ(operand1.opcode(), kParameterStr);
EXPECT_EQ(operand1.parameter_number(), parameter1_number);
EXPECT_EQ(operand1.shape().element_type(), type);
}
TEST(VariadicComparatorTest, OneOperandOneComparison) {
XlaBuilder builder("test");
XlaComputation comp = CreateScalarComparisonComputation(
"computation", {U16}, {LtTotalOrder}, &builder);
EXPECT_EQ(comp.proto().computations_size(), 1);
EXPECT_EQ(comp.proto().computations(0).program_shape().parameters_size(), 2);
const auto& instr = comp.proto().computations(0).instructions();
const auto& root = instr.at(comp.proto().computations(0).root_id() - 1);
ExpectCompareOp(root, U16, "LT", 0, 1, instr);
}
TEST(VariadicComparatorTest, TwoOperandsOneComparison) {
XlaBuilder builder("test");
XlaComputation comp = CreateScalarComparisonComputation(
"computation", {U16, U32}, {LtTotalOrder, {}}, &builder);
EXPECT_EQ(comp.proto().computations_size(), 1);
EXPECT_EQ(comp.proto().computations(0).program_shape().parameters_size(), 4);
const auto& instr = comp.proto().computations(0).instructions();
const auto& root = instr.at(comp.proto().computations(0).root_id() - 1);
ExpectCompareOp(root, U16, "LT", 0, 1, instr);
}
TEST(VariadicComparatorTest, TwoOperandsTwoComparisons) {
XlaBuilder builder("test");
XlaComputation comp = CreateScalarComparisonComputation(
"computation", {U16, U32}, {LtTotalOrder, LtTotalOrder}, &builder);
EXPECT_EQ(comp.proto().computations_size(), 1);
EXPECT_EQ(comp.proto().computations(0).program_shape().parameters_size(), 4);
const auto& instr = comp.proto().computations(0).instructions();
const auto& root = instr.at(comp.proto().computations(0).root_id() - 1);
EXPECT_EQ(root.opcode(), HloOpcodeString(xla::HloOpcode::kSelect));
ExpectCompareOp(instr.at(root.operand_ids(0) - 1), U16, "EQ", 0, 1, instr);
ExpectCompareOp(instr.at(root.operand_ids(1) - 1), U32, "LT", 2, 3, instr);
ExpectCompareOp(instr.at(root.operand_ids(2) - 1), U16, "LT", 0, 1, instr);
}
}
} | 2,231 |
#ifndef XLA_CLIENT_LIB_PRNG_H_
#define XLA_CLIENT_LIB_PRNG_H_
#include <array>
#include <functional>
#include <utility>
#include "xla/client/xla_builder.h"
#include "xla/xla_data.pb.h"
namespace xla {
struct RngOutput {
XlaOp value;
XlaOp state;
};
using BitGeneratorTy = std::function<RngOutput(XlaOp key, XlaOp initial_state,
const xla::Shape& shape)>;
RngOutput ThreeFryBitGenerator(XlaOp key, XlaOp initial_state,
const xla::Shape& shape);
RngOutput PhiloxBitGenerator(XlaOp key, XlaOp initial_state,
const Shape& shape);
std::pair<XlaOp, XlaOp> ScramblePhiloxKey(XlaOp key);
RngOutput UniformFloatingPointDistribution(XlaOp key, XlaOp initial_state,
BitGeneratorTy bit_generator,
XlaOp minval, XlaOp maxval,
const xla::Shape& shape);
RngOutput UniformIntDistribution(XlaOp key, XlaOp initial_state,
BitGeneratorTy bit_generator, XlaOp minval,
XlaOp maxval, const xla::Shape& shape);
RngOutput NormalFloatingPointDistribution(XlaOp key, XlaOp initial_state,
BitGeneratorTy bit_generator,
const xla::Shape& shape);
xla::XlaOp ConcatScalars(xla::XlaBuilder* builder,
absl::Span<const xla::XlaOp> scalars);
xla::XlaOp PhiloxIncreaseCounter(xla::XlaOp counter, xla::XlaOp delta);
}
#endif
#include "xla/client/lib/prng.h"
#include <array>
#include <cmath>
#include <cstdint>
#include <iterator>
#include <tuple>
#include <utility>
#include <vector>
#include "absl/status/statusor.h"
#include "xla/client/lib/constants.h"
#include "xla/client/xla_builder.h"
#include "xla/primitive_util.h"
#include "xla/util.h"
namespace xla {
xla::XlaOp ConcatScalars(xla::XlaBuilder* builder,
absl::Span<const xla::XlaOp> scalars) {
std::vector<xla::XlaOp> vectors;
absl::c_transform(scalars, std::back_inserter(vectors),
[](xla::XlaOp x) { return xla::Reshape(x, {1}); });
return ConcatInDim(builder, vectors, 0);
}
namespace {
XlaOp RotateLeftU32(XlaOp v, int distance) {
return (v << ConstantR0<uint32_t>(v.builder(), distance)) |
ShiftRightLogical(v, ConstantR0<uint32_t>(v.builder(), 32 - distance));
}
using ThreeFry2x32State = std::array<XlaOp, 2>;
ThreeFry2x32State ThreeFry2x32(ThreeFry2x32State input, ThreeFry2x32State key) {
XlaBuilder* builder = input[0].builder();
key[0] = BitcastConvertType(key[0], U32);
key[1] = BitcastConvertType(key[1], U32);
constexpr std::array<int, 8> rotations = {13, 15, 26, 6, 17, 29, 16, 24};
ThreeFry2x32State x;
std::array<XlaOp, 3> ks;
ks[2] = ConstantR0<uint32_t>(builder, 0x1BD11BDA);
for (int i = 0; i < 2; ++i) {
ks[i] = key[i];
x[i] = input[i];
ks[2] = ks[2] ^ key[i];
}
x[0] = x[0] + ks[0];
x[1] = x[1] + ks[1];
auto round = [](ThreeFry2x32State v, int rotation) {
v[0] = v[0] + v[1];
v[1] = RotateLeftU32(v[1], rotation);
v[1] = v[0] ^ v[1];
return v;
};
x = round(x, rotations[0]);
x = round(x, rotations[1]);
x = round(x, rotations[2]);
x = round(x, rotations[3]);
x[0] = x[0] + ks[1];
x[1] = x[1] + ks[2] + ConstantR0<uint32_t>(builder, 1);
x = round(x, rotations[4]);
x = round(x, rotations[5]);
x = round(x, rotations[6]);
x = round(x, rotations[7]);
x[0] = x[0] + ks[2];
x[1] = x[1] + ks[0] + ConstantR0<uint32_t>(builder, 2);
x = round(x, rotations[0]);
x = round(x, rotations[1]);
x = round(x, rotations[2]);
x = round(x, rotations[3]);
x[0] = x[0] + ks[0];
x[1] = x[1] + ks[1] + ConstantR0<uint32_t>(builder, 3);
x = round(x, rotations[4]);
x = round(x, rotations[5]);
x = round(x, rotations[6]);
x = round(x, rotations[7]);
x[0] = x[0] + ks[1];
x[1] = x[1] + ks[2] + ConstantR0<uint32_t>(builder, 4);
x = round(x, rotations[0]);
x = round(x, rotations[1]);
x = round(x, rotations[2]);
x = round(x, rotations[3]);
x[0] = x[0] + ks[2];
x[1] = x[1] + ks[0] + ConstantR0<uint32_t>(builder, 5);
return x;
}
std::array<XlaOp, 2> Uint64ToUint32s(XlaOp u64) {
XlaBuilder* builder = u64.builder();
XlaOp const32 = ConstantR0WithType(builder, U64, 32);
XlaOp fst = ConvertElementType(u64, U32);
XlaOp snd = ConvertElementType(ShiftRightLogical(u64, const32), U32);
return {fst, snd};
}
XlaOp Uint32sToUint64(std::array<XlaOp, 2> u32s) {
XlaBuilder* builder = u32s[0].builder();
return ConvertElementType(u32s[0], U64) |
ShiftLeft(ConvertElementType(u32s[1], U64),
ConstantR0WithType(builder, U64, 32));
}
std::pair<ThreeFry2x32State, XlaOp> GetThreeFryInputsAndUpdatedState(
XlaOp initial_state, const Shape& shape) {
XlaBuilder* builder = initial_state.builder();
auto u64_shape = ShapeUtil::MakeShape(U64, shape.dimensions());
auto input_u64 = Broadcast(Reshape(initial_state, {}), shape.dimensions());
int64_t trailing_dims_product = 1;
for (int64_t i = shape.rank() - 1; i >= 0; --i) {
if (shape.dimensions(i) < 2) {
continue;
}
input_u64 =
input_u64 + (Iota(builder, u64_shape, i) *
ConstantR0<uint64_t>(builder, trailing_dims_product));
trailing_dims_product *= shape.dimensions(i);
}
XlaOp new_state = initial_state +
ConstantR0<uint64_t>(builder, ShapeUtil::ElementsIn(shape));
return std::make_pair(Uint64ToUint32s(input_u64), new_state);
}
struct SplitShapePair {
Shape half_shape;
Shape concat_shape;
int64_t split_dim;
int64_t new_concat_dim;
};
SplitShapePair SplitShapeIntoHalves(const Shape& shape) {
SplitShapePair pair;
if (shape.rank() == 0) {
pair.half_shape = ShapeUtil::MakeShape(shape.element_type(), {1});
pair.concat_shape = ShapeUtil::MakeShape(shape.element_type(), {2});
pair.split_dim = 0;
pair.new_concat_dim = 0;
return pair;
}
pair.split_dim = -1;
for (int64_t i = 0; i < shape.rank(); ++i) {
if (shape.dimensions(i) % 2 == 0) {
pair.split_dim = i;
break;
}
}
if (pair.split_dim == -1) {
for (int64_t i = 0; i < shape.rank(); ++i) {
if (pair.split_dim == -1 ||
shape.dimensions(i) > shape.dimensions(pair.split_dim)) {
pair.split_dim = i;
}
}
}
if (pair.split_dim < 0) {
LOG(ERROR) << "This point shouldn't have been reached.";
}
std::vector<int64_t> half_shape_dims;
std::vector<int64_t> concat_shape_dims;
const auto rank = shape.rank();
half_shape_dims.reserve(rank + 1);
concat_shape_dims.reserve(rank + 1);
for (int64_t i = 0; i < rank; ++i) {
if (i == pair.split_dim) {
half_shape_dims.push_back(CeilOfRatio<int64_t>(shape.dimensions(i), 2));
half_shape_dims.push_back(1);
concat_shape_dims.push_back(half_shape_dims[i]);
concat_shape_dims.push_back(2);
} else {
half_shape_dims.push_back(shape.dimensions(i));
concat_shape_dims.push_back(shape.dimensions(i));
}
}
pair.new_concat_dim = pair.split_dim + 1;
pair.half_shape = ShapeUtil::MakeShape(shape.element_type(), half_shape_dims);
pair.concat_shape =
ShapeUtil::MakeShape(shape.element_type(), concat_shape_dims);
return pair;
}
XlaOp CombineShapePair(absl::Span<const XlaOp> pair,
const SplitShapePair& shape_pair,
const Shape& original_shape) {
if (original_shape.rank() == 0) {
return Reshape(pair[0], {});
}
XlaBuilder* builder = pair[0].builder();
XlaOp result = ConcatInDim(builder, pair, shape_pair.new_concat_dim);
const int64_t pre_split_size =
original_shape.dimensions(shape_pair.split_dim);
std::vector<int64_t> reshape_dims(original_shape.dimensions().begin(),
original_shape.dimensions().end());
reshape_dims[shape_pair.split_dim] = RoundUpTo<int64_t>(pre_split_size, 2);
result = Reshape(result, reshape_dims);
if (reshape_dims[shape_pair.split_dim] != pre_split_size) {
result = Slice(result, std::vector<int64_t>(original_shape.rank(), 0),
original_shape.dimensions(),
std::vector<int64_t>(original_shape.rank(), 1));
}
return result;
}
RngOutput ThreeFryRngBit32(XlaOp key, XlaOp initial_state, const Shape& shape) {
auto shape_pair = SplitShapeIntoHalves(shape);
std::pair<ThreeFry2x32State, XlaOp> inputs_state =
GetThreeFryInputsAndUpdatedState(initial_state, shape_pair.half_shape);
ThreeFry2x32State inputs = inputs_state.first;
ThreeFry2x32State outputs = ThreeFry2x32(inputs, Uint64ToUint32s(key));
XlaOp result = CombineShapePair(outputs, shape_pair, shape);
return {result, inputs_state.second};
}
RngOutput ThreeFryRngBitNarrow(XlaOp op_key, XlaOp initial_state,
const Shape& shape) {
auto new_shape = shape;
new_shape.set_element_type(U32);
auto output = ThreeFryRngBit32(op_key, initial_state, new_shape);
output.value = ConvertElementType(
output.value, primitive_util::UnsignedIntegralTypeForBitWidth(
primitive_util::BitWidth(shape.element_type())));
return output;
}
RngOutput ThreeFryRngBit64(XlaOp key, XlaOp initial_state, const Shape& shape) {
std::pair<ThreeFry2x32State, XlaOp> inputs_state =
GetThreeFryInputsAndUpdatedState(initial_state, shape);
ThreeFry2x32State inputs = inputs_state.first;
ThreeFry2x32State outputs = ThreeFry2x32(inputs, Uint64ToUint32s(key));
XlaOp result = Uint32sToUint64(outputs);
return {result, inputs_state.second};
}
using Philox4x32Key = std::array<XlaOp, 2>;
using Philox4x32State = std::array<XlaOp, 4>;
Philox4x32State Philox4x32(Philox4x32State state, Philox4x32Key key) {
static const uint32_t kPhiloxW32A = 0x9E3779B9;
static const uint32_t kPhiloxW32B = 0xBB67AE85;
static const uint32_t kPhiloxM4x32A = 0xD2511F53;
static const uint32_t kPhiloxM4x32B = 0xCD9E8D57;
struct HighLowPair {
XlaOp high;
XlaOp low;
};
auto mul_hi_low = [](XlaOp x, uint32_t k) {
auto product =
ConvertElementType(x, U64) * ConstantR0<uint64_t>(x.builder(), k);
auto low = ConvertElementType(product, U32);
auto high = ConvertElementType(
product >> ConstantR0<uint64_t>(x.builder(), 32), U32);
return HighLowPair{high, low};
};
auto philox_round = [&](Philox4x32State x, Philox4x32Key key) {
auto product0 = mul_hi_low(x[0], kPhiloxM4x32A);
auto product1 = mul_hi_low(x[2], kPhiloxM4x32B);
return Philox4x32State{product1.high ^ x[1] ^ key[0], product1.low,
product0.high ^ x[3] ^ key[1], product0.low};
};
auto raise_key = [](Philox4x32Key key) {
XlaBuilder* builder = key[0].builder();
return Philox4x32Key{key[0] + ConstantR0<uint32_t>(builder, kPhiloxW32A),
key[1] + ConstantR0<uint32_t>(builder, kPhiloxW32B)};
};
static const int kNumRounds = 10;
for (int round = 0; round < kNumRounds; ++round, key = raise_key(key)) {
state = philox_round(state, key);
}
return state;
}
std::pair<Philox4x32State, Philox4x32Key> ScramblePhiloxKey(Philox4x32Key key) {
XlaBuilder* builder = key[0].builder();
XlaOp key0 = ConvertElementType(key[0], U64);
XlaOp key1 = ConvertElementType(key[1], U64);
Philox4x32State state = {
ConvertElementType(key0, U32),
ConvertElementType(key0 >> ScalarLike(key0, 32), U32),
ConvertElementType(key1, U32),
ConvertElementType(key1 >> ScalarLike(key1, 32), U32),
};
key = {ConstantR0<uint32_t>(builder, 0x3ec8f720),
ConstantR0<uint32_t>(builder, 0x02461e29)};
state = Philox4x32(state, key);
XlaOp zero = ConstantR0<uint32_t>(builder, 0);
return {Philox4x32State{zero, zero, state[2], state[3]},
Philox4x32Key{state[0], state[1]}};
}
std::array<XlaOp, 2> Uint128AddUint64(
const std::array<XlaOp, 2>& u128, XlaOp u64,
absl::Span<const int64_t> broadcast_sizes = {}) {
auto u128_low = u128[0];
auto u128_high = u128[1];
XlaOp new_u128_low = u128_low + u64;
XlaOp one = ConstantR0<uint64_t>(u128[0].builder(), 1);
XlaOp new_u128_high = Select(Lt(new_u128_low, u128_low),
Broadcast(u128_high + one, broadcast_sizes),
Broadcast(u128_high, broadcast_sizes));
return {new_u128_low, new_u128_high};
}
std::array<XlaOp, 2> Uint32sToUint128(const std::array<XlaOp, 4>& u32s) {
return {Uint32sToUint64({u32s[0], u32s[1]}),
Uint32sToUint64({u32s[2], u32s[3]})};
}
std::array<XlaOp, 4> Uint128ToUint32s(const std::array<XlaOp, 2>& u128) {
std::array<XlaOp, 2> u128_low_32s = Uint64ToUint32s(u128[0]);
std::array<XlaOp, 2> u128_high_32s = Uint64ToUint32s(u128[1]);
return {u128_low_32s[0], u128_low_32s[1], u128_high_32s[0], u128_high_32s[1]};
}
std::array<XlaOp, 2> Uint128FromOp(XlaOp op) {
auto u128_low = xla::Reshape(xla::Slice(op, {0}, {1}, {1}), {});
auto u128_high = xla::Reshape(xla::Slice(op, {1}, {2}, {1}), {});
return {u128_low, u128_high};
}
XlaOp Uint128ToOp(std::array<XlaOp, 2> u128) {
return ConcatScalars(u128[0].builder(), {u128[0], u128[1]});
}
std::pair<Philox4x32State, XlaOp> GetPhiloxInputsAndUpdatedState(
const Philox4x32State& state, int64_t n) {
XlaBuilder* builder = state[0].builder();
XlaOp iota = Iota(builder, U64, n);
auto state_u128 = Uint32sToUint128(state);
auto inputs = Uint128ToUint32s(Uint128AddUint64(state_u128, iota, {n}));
XlaOp new_state = Uint128ToOp(
Uint128AddUint64(state_u128, ConstantR0<uint64_t>(builder, n)));
return std::make_pair(inputs, new_state);
}
std::pair<Philox4x32State, XlaOp> GeneratePhiloxBits(int64_t num_elems,
XlaOp initial_state,
Philox4x32Key key) {
Philox4x32State state;
state = Uint128ToUint32s(Uint128FromOp(initial_state));
const int64_t num_vector4 = CeilOfRatio<int64_t>(num_elems, 4);
Philox4x32State inputs;
XlaOp new_state;
std::tie(inputs, new_state) =
GetPhiloxInputsAndUpdatedState(state, num_vector4);
auto outputs = Philox4x32(inputs, key);
return std::make_pair(outputs, new_state);
}
RngOutput PhiloxRngBit32(XlaOp op_key, XlaOp initial_state,
const Shape& shape) {
XlaBuilder* builder = op_key.builder();
const int64_t num_elems = ShapeUtil::ElementsIn(shape);
Philox4x32Key key = Uint64ToUint32s(op_key);
Philox4x32State bits;
XlaOp new_state;
std::tie(bits, new_state) = GeneratePhiloxBits(num_elems, initial_state, key);
int64_t bits_len = (num_elems + 3) / 4;
for (auto i = 0; i < 4; ++i) {
bits[i] = Reshape(bits[i], {bits_len, 1});
}
XlaOp numbers = ConcatInDim(builder, {bits[0], bits[1], bits[2], bits[3]},
1);
numbers = Reshape(numbers, {bits_len * 4});
numbers = Slice(numbers, {0},
{num_elems},
{1});
return {Reshape(numbers, shape.dimensions()), new_state};
}
RngOutput PhiloxRngBitNarrow(XlaOp op_key, XlaOp initial_state,
const Shape& shape) {
auto new_shape = shape;
new_shape.set_element_type(U32);
auto output = PhiloxRngBit32(op_key, initial_state, new_shape);
output.value = ConvertElementType(
output.value, primitive_util::UnsignedIntegralTypeForBitWidth(
primitive_util::BitWidth(shape.element_type())));
return output;
}
RngOutput PhiloxRngBit64(XlaOp op_key, XlaOp initial_state,
const Shape& shape) {
XlaBuilder* builder = op_key.builder();
const int64_t num_elems = ShapeUtil::ElementsIn(shape);
Philox4x32Key key = Uint64ToUint32s(op_key);
Philox4x32State bits32;
XlaOp new_state;
std::tie(bits32, new_state) =
GeneratePhiloxBits(num_elems * 2, initial_state, key);
std::array<XlaOp, 2> bits64;
bits64[0] = Uint32sToUint64({bits32[0], bits32[1]});
bits64[1] = Uint32sToUint64({bits32[2], bits32[3]});
int64_t bits64_len = (num_elems + 1) / 2;
for (auto i = 0; i < 2; ++i) {
bits64[i] = Reshape(bits64[i], {bits64_len, 1});
}
XlaOp numbers = ConcatInDim(builder, {bits64[0], bits64[1]},
1);
numbers = Reshape(numbers, {bits64_len * 2});
numbers = Slice(numbers, {0},
{num_elems},
{1});
return {Reshape(numbers, shape.dimensions()), new_state};
}
XlaOp ConvertRandomBitsToUniformFloatingPoint(XlaOp bits, XlaOp minval,
XlaOp maxval) {
XlaBuilder* builder = bits.builder();
return builder->ReportErrorOrReturn([&]() -> absl::StatusOr<XlaOp> {
TF_ASSIGN_OR_RETURN(const Shape* minval_shape,
builder->GetShapePtr(minval));
TF_ASSIGN_OR_RETURN(const Shape* bits_shape, builder->GetShapePtr(bits));
PrimitiveType value_type = minval_shape->element_type();
PrimitiveType bit_type = bits_shape->element_type();
if (!primitive_util::IsFloatingPointType(value_type) ||
!primitive_util::IsIntegralType(bit_type)) {
return InvalidArgument(
"In ConvertRandomBitsToUniformFloatingPoint, value_type and bit_type "
"can only be (floating_type, integer_type). Got combination: (%s, "
"%s).",
primitive_util::LowercasePrimitiveTypeName(value_type),
primitive_util::LowercasePrimitiveTypeName(bit_type));
}
if (value_type == F16 && bit_type == U16) {
auto mantissa = bits & ScalarLike(bits, 0x3ffu);
auto exponent = ScalarLike(bits, static_cast<uint16_t>(15) << 10);
auto u16_result = exponent | mantissa;
auto result = BitcastConvertType(u16_result, F16);
return result - ScalarLike(result, 1.0);
} else {
int num_bits = primitive_util::BitWidth(bit_type);
int num_mantissa_bits = primitive_util::SignificandWidth(value_type) - 1;
if (num_mantissa_bits > num_bits) {
return InvalidArgument(
"%s bit type argument must have enough bits to cover the number of "
"mantissa bits of the result type %s",
primitive_util::LowercasePrimitiveTypeName(bit_type),
primitive_util::LowercasePrimitiveTypeName(value_type));
}
bits = ShiftRightLogical(bits,
ScalarLike(bits, num_bits - num_mantissa_bits));
XlaOp values = ConvertElementType(bits, value_type);
values = values * ScalarLike(values, std::ldexp(1., -num_mantissa_bits));
return values * (maxval - minval) + minval;
}
});
}
XlaOp ConvertRandomBitsToUniformInt(XlaOp bits, XlaOp minval, XlaOp maxval,
PrimitiveType type,
PrimitiveType unsigned_type) {
XlaBuilder* builder = bits.builder();
XlaOp range = BitcastConvertType(maxval, unsigned_type) -
BitcastConvertType(minval, unsigned_type);
XlaOp dist = Rem(bits, range);
XlaOp dist_div_2 =
ShiftRightLogical(dist, ConstantR0WithType(builder, unsigned_type, 1));
return minval + BitcastConvertType(dist_div_2, type) +
BitcastConvertType(dist - dist_div_2, type);
}
std::pair<XlaOp, XlaOp> BoxMullerTransform(XlaOp x0, XlaOp x1) {
XlaOp u1 = Max(x0, ScalarLike(x0, 1.0e-7f));
XlaOp v1 = ScalarLike(x1, 2.0f * M_PI) * x1;
XlaOp u2 = Sqrt(ScalarLike(u1, -2.0f) * Log(u1));
return {Sin(v1) * u2, Cos(v1) * u2};
}
}
XlaOp PhiloxIncreaseCounter(XlaOp counter, XlaOp delta) {
return Uint128ToOp(Uint128AddUint64(Uint128FromOp(counter), delta));
}
RngOutput ThreeFryBitGenerator(XlaOp key, XlaOp initial_state,
const Shape& shape) {
PrimitiveType type = shape.element_type();
return primitive_util::PrimitiveTypeSwitch<RngOutput>(
[&](auto primitive_type_constant) -> RngOutput {
if constexpr (primitive_util::IsArrayType(primitive_type_constant) &&
!primitive_util::IsComplexType(primitive_type_constant) &&
primitive_type_constant != PRED) {
const int kBits = primitive_util::BitWidth(primitive_type_constant);
if (kBits < 32) {
return ThreeFryRngBitNarrow(key, initial_state, shape);
}
if (kBits == 32) {
return ThreeFryRngBit32(key, initial_state, shape);
}
if (kBits == 64) {
return ThreeFryRngBit64(key, initial_state, shape);
}
}
return {
key.builder()->ReportError(Unimplemented(
"Types other than F16, F32, F64, U16, S16, U32, S32, U64 and "
"S64 are not implemented by ThreeFryBitGenerator; got %s",
primitive_util::LowercasePrimitiveTypeName(type))),
initial_state};
},
type);
}
RngOutput PhiloxBitGenerator(XlaOp key, XlaOp initial_state,
const Shape& shape) {
PrimitiveType type = shape.element_type();
return primitive_util::PrimitiveTypeSwitch<RngOutput>(
[&](auto primitive_type_constant) -> RngOutput {
if constexpr (primitive_util::IsArrayType(primitive_type_constant) &&
!primitive_util::IsComplexType(primitive_type_constant) &&
primitive_type_constant != PRED) {
const int kBits = primitive_util::BitWidth(primitive_type_constant);
if (kBits < 32) {
return PhiloxRngBitNarrow(key, initial_state, shape);
}
if (kBits == 32) {
return PhiloxRngBit32(key, initial_state, shape);
}
if (kBits == 64) {
return PhiloxRngBit64(key, initial_state, shape);
}
}
return {
key.builder()->ReportError(Unimplemented(
"Types other than F16, F32, F64, U16, S16, U32, S32, U64 and "
"S64 are not implemented by PhiloxBitGenerator; got %s",
primitive_util::LowercasePrimitiveTypeName(type))),
initial_state};
},
type);
}
std::pair<XlaOp, XlaOp> ScramblePhiloxKey(XlaOp key) {
Philox4x32Key pkey = Uint64ToUint32s(key);
auto state_key = ScramblePhiloxKey(pkey);
return std::make_pair(Uint128ToOp(Uint32sToUint128(state_key.first)),
Uint32sToUint64(state_key.second));
}
RngOutput UniformFloatingPointDistribution(XlaOp key, XlaOp initial_state,
BitGeneratorTy bit_generator,
XlaOp minval, XlaOp maxval,
const Shape& shape) {
RngOutput bits_state = bit_generator(key, initial_state, shape);
XlaOp bits = bits_state.value;
XlaOp new_state = bits_state.state;
return {ConvertRandomBitsToUniformFloatingPoint(bits, minval, maxval),
new_state};
}
RngOutput UniformIntDistribution(XlaOp key, XlaOp initial_state,
BitGeneratorTy bit_generator, XlaOp minval,
XlaOp maxval, const Shape& shape) {
RngOutput bits_state = bit_generator(key, initial_state, shape);
XlaOp bits = bits_state.value;
XlaOp new_state = bits_state.state;
PrimitiveType type = shape.element_type();
PrimitiveType unsigned_type;
if (type == U32 || type == S32) {
unsigned_type = U32;
} else if (type == U64 || type == S64) {
unsigned_type = U64;
} else {
return {key.builder()->ReportError(Unimplemented(
"Types other than U32, S32, U64 and S64 "
"are not implemented by UniformIntDistribution; got %s",
primitive_util::Lowercase | #include "xla/client/lib/prng.h"
#include <cstdint>
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "xla/client/lib/constants.h"
#include "xla/client/xla_builder.h"
#include "xla/primitive_util.h"
#include "xla/shape.h"
#include "xla/test.h"
#include "xla/tests/client_library_test_base.h"
#include "xla/tests/test_macros.h"
#include "xla/xla_data.pb.h"
namespace xla {
namespace {
class PrngTest : public ClientLibraryTestBase {
public:
template <PrimitiveType value_type, PrimitiveType bit_type,
typename ValueT = typename primitive_util::PrimitiveTypeToNative<
value_type>::type,
typename BitT =
typename primitive_util::PrimitiveTypeToNative<bit_type>::type>
void TestConvertRandomBitsToUniformFloatingPoint(uint32_t bits, float minval,
float maxval) {
XlaBuilder builder("convert_random_bits_to_uniform_floating_point");
XlaOp bits_op = ConstantR0<BitT>(&builder, static_cast<BitT>(bits));
XlaOp minval_op = ConstantR0<ValueT>(&builder, static_cast<ValueT>(minval));
XlaOp maxval_op = ConstantR0<ValueT>(&builder, static_cast<ValueT>(maxval));
XlaOp seed = ConstantR0<uint64_t>(&builder, 42);
XlaOp initial_state = Zero(&builder, PrimitiveType::U64);
BitGeneratorTy bit_generator = [](XlaOp key, XlaOp state,
const Shape& shape) {
state = ConcatScalars(key.builder(), {key, state});
XlaOp result =
RngBitGenerator(RandomAlgorithm::RNG_DEFAULT, state, shape);
return RngOutput{GetTupleElement(result, 1),
GetTupleElement(result, 0)};
};
const Shape rng_shape = builder.GetShape(bits_op).value();
EXPECT_EQ(rng_shape.element_type(), bit_type);
RngOutput rng_output = UniformFloatingPointDistribution(
seed, initial_state, bit_generator, minval_op, maxval_op, rng_shape);
if (rng_output.value.valid()) {
XlaOp result = rng_output.value;
EXPECT_EQ(builder.GetShape(result).value().element_type(), value_type);
XlaOp result_ge_min = Ge(result, minval_op);
XlaOp result_lt_max = Lt(result, maxval_op);
And(result_ge_min, result_lt_max);
ComputeAndCompareR0<bool>(&builder, true, {});
} else {
EXPECT_EQ(builder.first_error().code(),
absl::StatusCode::kInvalidArgument);
}
}
};
XLA_TEST_F(PrngTest, RandomBitsToUniformFloatingPointInvalidArguments) {
TestConvertRandomBitsToUniformFloatingPoint<PrimitiveType::F32,
PrimitiveType::U16>(0x1234, 0.0f,
1.0f);
TestConvertRandomBitsToUniformFloatingPoint<PrimitiveType::F16,
PrimitiveType::U8>(0x12, 0.0f,
1.0f);
}
}
} | 2,232 |
#ifndef XLA_CLIENT_LIB_TRIDIAGONAL_H_
#define XLA_CLIENT_LIB_TRIDIAGONAL_H_
#include "xla/client/xla_builder.h"
#include "xla/xla_data.pb.h"
namespace xla {
namespace tridiagonal {
enum SolverAlgorithm { kThomas };
absl::StatusOr<XlaOp> TridiagonalSolver(SolverAlgorithm algo,
XlaOp lower_diagonal,
XlaOp main_diagonal,
XlaOp upper_diagonal, XlaOp rhs);
absl::StatusOr<XlaOp> TridiagonalSolver(SolverAlgorithm algo, XlaOp diagonals,
XlaOp rhs);
absl::StatusOr<XlaOp> TridiagonalMatMul(XlaOp upper_diagonal,
XlaOp main_diagonal,
XlaOp lower_diagonal, XlaOp rhs);
}
}
#endif
#include "xla/client/lib/tridiagonal.h"
#include <cstdint>
#include <numeric>
#include <string>
#include <string_view>
#include <vector>
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/types/span.h"
#include "xla/client/lib/constants.h"
#include "xla/client/lib/loops.h"
#include "xla/client/lib/slicing.h"
#include "xla/client/xla_builder.h"
#include "xla/shape_util.h"
#include "xla/status_macros.h"
namespace xla {
namespace tridiagonal {
namespace {
absl::Status CheckSecondToLastDimension(const Shape& op_shape, int64_t rank,
int64_t expected,
const std::string& op_name) {
const auto actual_num_dims = ShapeUtil::GetDimension(op_shape, rank - 2);
if (actual_num_dims != expected) {
return InvalidArgument(
"Second to last dimension of %s should be %d but is %d.", op_name,
expected, actual_num_dims);
}
return absl::OkStatus();
}
absl::StatusOr<int64_t> CheckSystemAndReturnNumEquations(XlaOp lower_diagonal,
XlaOp main_diagonal,
XlaOp upper_diagonal,
XlaOp rhs) {
XlaBuilder* builder = lower_diagonal.builder();
TF_ASSIGN_OR_RETURN(Shape lower_diagonal_shape,
builder->GetShape(lower_diagonal));
TF_ASSIGN_OR_RETURN(Shape main_diagonal_shape,
builder->GetShape(main_diagonal));
TF_ASSIGN_OR_RETURN(Shape upper_diagonal_shape,
builder->GetShape(upper_diagonal));
TF_ASSIGN_OR_RETURN(Shape rhs_shape, builder->GetShape(rhs));
const auto lower_diagonal_rank = lower_diagonal_shape.rank();
const auto main_diagonal_rank = main_diagonal_shape.rank();
const auto upper_diagonal_rank = upper_diagonal_shape.rank();
const auto rhs_rank = rhs_shape.rank();
if (!((lower_diagonal_rank == main_diagonal_rank) &&
(lower_diagonal_rank == upper_diagonal_rank) &&
(lower_diagonal_rank == rhs_rank))) {
return InvalidArgument(
"All inputs should have the same rank but got rank "
"%d for lower diagonal, %d for diagonal, %d for upper diagonal, "
"%d for rhs",
lower_diagonal_rank, main_diagonal_rank, upper_diagonal_rank, rhs_rank);
}
const auto rank = lower_diagonal_rank;
if (rank < 2) {
return InvalidArgument("Arguments must have rank >=2; got rank %d.", rank);
}
const auto lower_diagonal_num_eqs =
ShapeUtil::GetDimension(lower_diagonal_shape, rank - 1);
const auto main_diagonal_num_eqs =
ShapeUtil::GetDimension(main_diagonal_shape, rank - 1);
const auto upper_diagonal_num_eqs =
ShapeUtil::GetDimension(upper_diagonal_shape, rank - 1);
const auto rhs_num_eqs = ShapeUtil::GetDimension(rhs_shape, rank - 1);
if (!((lower_diagonal_num_eqs == main_diagonal_num_eqs) &&
(lower_diagonal_num_eqs == upper_diagonal_num_eqs) &&
(lower_diagonal_num_eqs == rhs_num_eqs))) {
return InvalidArgument(
"All inputs should have the same innermost dimension but got "
"%d for lower diagonal, %d for diagonal, %d for upper diagonal, "
"%d for rhs",
lower_diagonal_num_eqs, main_diagonal_num_eqs, upper_diagonal_num_eqs,
rhs_num_eqs);
}
const auto num_equations = lower_diagonal_num_eqs;
TF_RETURN_IF_ERROR(CheckSecondToLastDimension(lower_diagonal_shape, rank, 1,
"lower diagonal"));
TF_RETURN_IF_ERROR(
CheckSecondToLastDimension(main_diagonal_shape, rank, 1, "diagonal"));
TF_RETURN_IF_ERROR(CheckSecondToLastDimension(upper_diagonal_shape, rank, 1,
"upper diagonal"));
return num_equations;
}
struct TridiagonalMatMulShapeParams {
int64_t rank;
int64_t m;
int64_t n;
PrimitiveType element_type;
};
absl::Status ValidateTridiagonalMatMulDiagonal(
const Shape& diagonal_shape, const std::string_view diagonal_name,
const Shape& rhs_shape) {
const int64_t diagonal_rank = diagonal_shape.rank();
const int64_t rhs_rank = rhs_shape.rank();
if (diagonal_rank != rhs_rank) {
return InvalidArgument("%s must have same rank as rhs, but got %d and %d.",
diagonal_name, diagonal_rank, rhs_rank);
}
for (int64_t i = 0; i < rhs_rank - 2; i++) {
const int64_t diagonal_dimension =
ShapeUtil::GetDimension(diagonal_shape, i);
const int64_t rhs_dimension = ShapeUtil::GetDimension(rhs_shape, i);
if (diagonal_dimension != rhs_dimension) {
return InvalidArgument(
"%s must have same outer dimensions as rhs, but for index %d, got %d "
"and %d.",
diagonal_name, i, diagonal_dimension, rhs_dimension);
}
}
if (const int64_t digonal_second_last_dimension =
ShapeUtil::GetDimension(diagonal_shape, rhs_rank - 2);
digonal_second_last_dimension != 1) {
return InvalidArgument(
"%s's second-to-last dimension must be 1, but got %d.", diagonal_name,
digonal_second_last_dimension);
}
const int64_t digonal_last_dimension =
ShapeUtil::GetDimension(diagonal_shape, rhs_rank - 1);
const int64_t rhs_second_last_dimension =
ShapeUtil::GetDimension(rhs_shape, rhs_rank - 2);
if (digonal_last_dimension != rhs_second_last_dimension) {
return InvalidArgument(
"%s's last dimension size must be rhs's second-to-last dimension size, "
"but got %d and %d.",
diagonal_name, digonal_last_dimension, rhs_second_last_dimension);
}
return absl::OkStatus();
}
absl::StatusOr<TridiagonalMatMulShapeParams>
CheckMatMulSystemAndReturnShapeParams(XlaOp upper_diagonal, XlaOp main_diagonal,
XlaOp lower_diagonal, XlaOp rhs) {
XlaBuilder* builder = upper_diagonal.builder();
TF_ASSIGN_OR_RETURN(const Shape upper_diagonal_shape,
builder->GetShape(upper_diagonal));
TF_ASSIGN_OR_RETURN(const Shape main_diagonal_shape,
builder->GetShape(main_diagonal));
TF_ASSIGN_OR_RETURN(const Shape lower_diagonal_shape,
builder->GetShape(lower_diagonal));
TF_ASSIGN_OR_RETURN(const Shape rhs_shape, builder->GetShape(rhs));
const int64_t rank = rhs_shape.rank();
if (rank < 2) {
return InvalidArgument("Input must have rank >= 2, but got %d.", rank);
}
TF_RETURN_IF_ERROR(ValidateTridiagonalMatMulDiagonal(upper_diagonal_shape,
"superdiag", rhs_shape));
TF_RETURN_IF_ERROR(ValidateTridiagonalMatMulDiagonal(main_diagonal_shape,
"maindiag", rhs_shape));
TF_RETURN_IF_ERROR(ValidateTridiagonalMatMulDiagonal(lower_diagonal_shape,
"subdiag", rhs_shape));
const int64_t rhs_height = ShapeUtil::GetDimension(rhs_shape, rank - 2);
const int64_t rhs_width = ShapeUtil::GetDimension(rhs_shape, rank - 1);
TridiagonalMatMulShapeParams shape_params;
shape_params.rank = rank;
shape_params.m = rhs_height;
shape_params.n = rhs_width;
shape_params.element_type = rhs_shape.element_type();
return shape_params;
}
XlaOp Coefficient(XlaOp operand, int32_t i) {
return DynamicSliceInMinorDims(operand,
{ConstantR0(operand.builder(), i)},
{1});
}
XlaOp Coefficient(XlaOp operand, XlaOp i) {
return DynamicSliceInMinorDims(operand,
{i}, {1});
}
XlaOp UpdateEq(XlaOp updated, int32_t i, XlaOp update) {
return DynamicUpdateSliceInMinorDims(
updated, update, {ConstantR0(updated.builder(), i)});
}
XlaOp UpdateEq(XlaOp updated, XlaOp i, XlaOp update) {
return DynamicUpdateSliceInMinorDims(updated, update, {i});
}
template <SolverAlgorithm algo>
absl::StatusOr<XlaOp> TridiagonalSolverImpl(XlaOp lower_diagonal,
XlaOp main_diagonal,
XlaOp upper_diagonal, XlaOp rhs);
template <>
absl::StatusOr<XlaOp> TridiagonalSolverImpl<kThomas>(XlaOp lower_diagonal,
XlaOp main_diagonal,
XlaOp upper_diagonal,
XlaOp rhs) {
XlaBuilder* builder = lower_diagonal.builder();
TF_ASSIGN_OR_RETURN(int64_t num_eqs,
CheckSystemAndReturnNumEquations(
lower_diagonal, main_diagonal, upper_diagonal, rhs));
XlaOp main_diag_after_elimination = ZerosLike(main_diagonal);
XlaOp rhs_after_elimination = ZerosLike(rhs);
XlaOp upper_diagonal_coeffs = ZerosLike(upper_diagonal);
XlaOp x_coeffs = ZerosLike(rhs);
main_diag_after_elimination =
UpdateEq(main_diag_after_elimination, 0, Coefficient(main_diagonal, 0));
rhs_after_elimination =
UpdateEq(rhs_after_elimination, 0, Coefficient(rhs, 0));
auto preparation_body_fn =
[](XlaOp i, absl::Span<const XlaOp> values,
XlaBuilder* builder) -> absl::StatusOr<std::vector<XlaOp>> {
auto upper_diagonal_coeffs = values[0];
auto upper_diagonal = values[1];
upper_diagonal_coeffs =
UpdateEq(upper_diagonal_coeffs, i, Coefficient(upper_diagonal, i));
return std::vector<XlaOp>{upper_diagonal_coeffs, upper_diagonal};
};
TF_ASSIGN_OR_RETURN(auto values_after_preparation,
ForEachIndex(num_eqs - 1, S32, preparation_body_fn,
{upper_diagonal_coeffs, upper_diagonal},
"preparation", builder));
upper_diagonal_coeffs = values_after_preparation[0];
auto forward_transformation_fn =
[](XlaOp i_minus_one, absl::Span<const XlaOp> values,
XlaBuilder* builder) -> absl::StatusOr<std::vector<XlaOp>> {
auto lower_diagonal = values[0];
auto main_diagonal = values[1];
auto rhs = values[2];
auto main_diag_after_elimination = values[3];
auto upper_diagonal_coeffs = values[4];
auto rhs_after_elimination = values[5];
auto one = ScalarLike(i_minus_one, 1);
auto i = i_minus_one + one;
auto lower_diagonal_i = Coefficient(lower_diagonal, i);
auto main_diagonal_i = Coefficient(main_diagonal, i);
auto rhs_i = Coefficient(rhs, i);
auto w_i =
lower_diagonal_i / Coefficient(main_diag_after_elimination, i - one);
main_diag_after_elimination = UpdateEq(
main_diag_after_elimination, i,
main_diagonal_i - w_i * Coefficient(upper_diagonal_coeffs, i - one));
rhs_after_elimination =
UpdateEq(rhs_after_elimination, i,
rhs_i - w_i * Coefficient(rhs_after_elimination, i - one));
return std::vector<XlaOp>{lower_diagonal,
main_diagonal,
rhs,
main_diag_after_elimination,
upper_diagonal_coeffs,
rhs_after_elimination};
};
TF_ASSIGN_OR_RETURN(
auto values_after_fwd_transformation,
ForEachIndex(
num_eqs - 1, S32, forward_transformation_fn,
{lower_diagonal, main_diagonal, rhs, main_diag_after_elimination,
upper_diagonal_coeffs, rhs_after_elimination},
"forward_transformation", builder));
lower_diagonal = values_after_fwd_transformation[0];
main_diagonal = values_after_fwd_transformation[1];
rhs = values_after_fwd_transformation[2];
main_diag_after_elimination = values_after_fwd_transformation[3];
upper_diagonal_coeffs = values_after_fwd_transformation[4];
rhs_after_elimination = values_after_fwd_transformation[5];
x_coeffs =
UpdateEq(x_coeffs, num_eqs - 1,
Coefficient(rhs_after_elimination, num_eqs - 1) /
Coefficient(main_diag_after_elimination, num_eqs - 1));
auto bwd_reduction_fn =
[num_eqs](XlaOp j, absl::Span<const XlaOp> values,
XlaBuilder* builder) -> absl::StatusOr<std::vector<XlaOp>> {
auto x_coeffs = values[0];
auto rhs_after_elimination = values[1];
auto upper_diagonal_coeffs = values[2];
auto main_diag_after_elimination = values[3];
auto n = ScalarLike(j, num_eqs - 2);
auto one = ScalarLike(j, 1);
auto i = n - j;
x_coeffs = UpdateEq(x_coeffs, i,
(Coefficient(rhs_after_elimination, i) -
Coefficient(upper_diagonal_coeffs, i) *
Coefficient(x_coeffs, i + one)) /
Coefficient(main_diag_after_elimination, i));
return std::vector<XlaOp>{x_coeffs, rhs_after_elimination,
upper_diagonal_coeffs,
main_diag_after_elimination};
};
TF_ASSIGN_OR_RETURN(
auto values_after_bwd_reduction,
ForEachIndex(num_eqs - 1, S32, bwd_reduction_fn,
{x_coeffs, rhs_after_elimination, upper_diagonal_coeffs,
main_diag_after_elimination},
"backward_reduction", builder));
x_coeffs = values_after_bwd_reduction[0];
return x_coeffs;
}
}
absl::StatusOr<XlaOp> TridiagonalSolver(SolverAlgorithm algo,
XlaOp lower_diagonal,
XlaOp main_diagonal,
XlaOp upper_diagonal, XlaOp rhs) {
switch (algo) {
case kThomas:
return TridiagonalSolverImpl<kThomas>(lower_diagonal, main_diagonal,
upper_diagonal, rhs);
default:
return Unimplemented(
"Only algorithm kThomas (%d) is implemented, got: %d",
static_cast<int>(kThomas), algo);
}
}
absl::StatusOr<XlaOp> TridiagonalSolver(SolverAlgorithm algo, XlaOp diagonals,
XlaOp rhs) {
XlaBuilder* builder = diagonals.builder();
TF_ASSIGN_OR_RETURN(Shape diagonals_shape, builder->GetShape(diagonals));
const int64_t rank = diagonals_shape.rank();
auto upper_diagonal =
SliceInDim(diagonals, 0, 1,
1, rank - 2);
auto main_diagonal =
SliceInDim(diagonals, 1, 2,
1, rank - 2);
auto lower_diagonal =
SliceInDim(diagonals, 2, 3,
1, rank - 2);
std::vector<int64_t> transpose_order(rank);
std::iota(transpose_order.begin(), transpose_order.end(), 0);
transpose_order[rank - 2] = rank - 1;
transpose_order[rank - 1] = rank - 2;
rhs = Transpose(rhs, transpose_order);
switch (algo) {
case kThomas: {
TF_ASSIGN_OR_RETURN(
XlaOp x, TridiagonalSolverImpl<kThomas>(lower_diagonal, main_diagonal,
upper_diagonal, rhs));
return Transpose(x, transpose_order);
}
default:
return Unimplemented(
"Only algorithm kThomas (%d) is implemented, got: %d",
static_cast<int>(kThomas), algo);
}
}
absl::StatusOr<XlaOp> TridiagonalMatMul(XlaOp upper_diagonal,
XlaOp main_diagonal,
XlaOp lower_diagonal, XlaOp rhs) {
TF_ASSIGN_OR_RETURN(const TridiagonalMatMulShapeParams shape_params,
CheckMatMulSystemAndReturnShapeParams(
upper_diagonal, main_diagonal, lower_diagonal, rhs));
XlaBuilder* builder = main_diagonal.builder();
std::vector<int64_t> broadcasted_dims(shape_params.rank);
std::iota(broadcasted_dims.begin(), broadcasted_dims.end(), 0);
std::vector<int64_t> transpose_dims = broadcasted_dims;
std::swap(transpose_dims[shape_params.rank - 2],
transpose_dims[shape_params.rank - 1]);
main_diagonal = xla::Transpose(main_diagonal, transpose_dims);
XlaOp diag_part = xla::Mul(main_diagonal, rhs, broadcasted_dims);
upper_diagonal = SliceInMinorDims(upper_diagonal, {0},
{shape_params.m - 1});
upper_diagonal = xla::Transpose(upper_diagonal, transpose_dims);
XlaOp adjusted_upper_rhs = SliceInMinorDims(
rhs, {1, 0}, {shape_params.m, shape_params.n});
XlaOp upper_diag_part =
xla::Mul(upper_diagonal, adjusted_upper_rhs, broadcasted_dims);
upper_diag_part = xla::PadInDim(
upper_diag_part, xla::Zero(builder, shape_params.element_type),
shape_params.rank - 2, 0, 1);
lower_diagonal = SliceInMinorDims(lower_diagonal, {1},
{shape_params.m});
lower_diagonal = xla::Transpose(lower_diagonal, transpose_dims);
XlaOp adjusted_lower_rhs = SliceInMinorDims(
rhs, {0, 0}, {shape_params.m - 1, shape_params.n});
XlaOp lower_diag_part =
xla::Mul(lower_diagonal, adjusted_lower_rhs, broadcasted_dims);
lower_diag_part = xla::PadInDim(
lower_diag_part, xla::Zero(builder, shape_params.element_type),
shape_params.rank - 2, 1, 0);
return diag_part + upper_diag_part + lower_diag_part;
}
}
} | #include "xla/client/lib/tridiagonal.h"
#include <cstdint>
#include <tuple>
#include <vector>
#include "absl/status/status.h"
#include "xla/client/lib/slicing.h"
#include "xla/client/xla_builder.h"
#include "xla/literal.h"
#include "xla/shape_util.h"
#include "xla/test.h"
#include "xla/tests/client_library_test_base.h"
#include "xla/tests/test_macros.h"
namespace xla {
namespace tridiagonal {
namespace {
class TridiagonalTest
: public ClientLibraryTestBase,
public ::testing::WithParamInterface<std::tuple<int, int, int>> {};
XLA_TEST_P(TridiagonalTest, SimpleTridiagonalMatMulOk) {
xla::XlaBuilder builder(TestName());
Array3D<float> upper_diagonal{{{34, 35, 999}}};
Array3D<float> main_diagonal{{{21, 22, 23}}};
Array3D<float> lower_diagonal{{{999, 10, 100}}};
Array3D<float> rhs{{{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}}};
XlaOp upper_diagonal_xla;
XlaOp main_diagonal_xla;
XlaOp lower_diagonal_xla;
XlaOp rhs_xla;
auto upper_diagonal_data = CreateR3Parameter<float>(
upper_diagonal, 0, "upper_diagonal", &builder, &upper_diagonal_xla);
auto main_diagonal_data = CreateR3Parameter<float>(
main_diagonal, 1, "main_diagonal", &builder, &main_diagonal_xla);
auto lower_diagonal_data = CreateR3Parameter<float>(
lower_diagonal, 2, "lower_diagonal", &builder, &lower_diagonal_xla);
auto rhs_data = CreateR3Parameter<float>(rhs, 3, "rhs", &builder, &rhs_xla);
TF_ASSERT_OK_AND_ASSIGN(
XlaOp x, TridiagonalMatMul(upper_diagonal_xla, main_diagonal_xla,
lower_diagonal_xla, rhs_xla));
ASSERT_EQ(x.builder()->first_error(), absl::OkStatus());
ASSERT_TRUE(x.valid());
std::vector<int64_t> expected_shape{1, 3, 4};
std::vector<float> expected_values{191, 246, 301, 356, 435, 502,
569, 636, 707, 830, 953, 1076};
TF_ASSERT_OK_AND_ASSIGN(
auto result,
ComputeAndTransfer(x.builder(),
{upper_diagonal_data.get(), main_diagonal_data.get(),
lower_diagonal_data.get(), rhs_data.get()}));
EXPECT_EQ(result.shape().dimensions(), expected_shape);
EXPECT_EQ(result.data<float>({}), expected_values);
}
XLA_TEST_P(TridiagonalTest, TridiagonalMatMulWrongShape) {
xla::XlaBuilder builder(TestName());
Array<float> upper_diagonal = Array<float>({5, 3, 7}, 1);
Array<float> main_diagonal = Array<float>({5, 3, 7}, 1);
Array<float> lower_diagonal = Array<float>({5, 3, 7}, 1);
Array<float> rhs = Array<float>({5, 3, 7, 6}, 1);
XlaOp upper_diagonal_xla;
XlaOp main_diagonal_xla;
XlaOp lower_diagonal_xla;
XlaOp rhs_xla;
auto upper_diagonal_data = CreateParameter<float>(
upper_diagonal, 0, "upper_diagonal", &builder, &upper_diagonal_xla);
auto main_diagonal_data = CreateParameter<float>(
main_diagonal, 1, "main_diagonal", &builder, &main_diagonal_xla);
auto lower_diagonal_data = CreateParameter<float>(
lower_diagonal, 2, "lower_diagonal", &builder, &lower_diagonal_xla);
auto rhs_data = CreateParameter<float>(rhs, 3, "rhs", &builder, &rhs_xla);
auto result = TridiagonalMatMul(upper_diagonal_xla, main_diagonal_xla,
lower_diagonal_xla, rhs_xla);
ASSERT_EQ(result.status(),
InvalidArgument(
"superdiag must have same rank as rhs, but got 3 and 4."));
}
XLA_TEST_P(TridiagonalTest, Solves) {
const auto& spec = GetParam();
xla::XlaBuilder builder(TestName());
const int64_t batch_size = std::get<0>(spec);
const int64_t num_eqs = std::get<1>(spec);
const int64_t num_rhs = std::get<2>(spec);
Array3D<float> lower_diagonal(batch_size, 1, num_eqs);
Array3D<float> main_diagonal(batch_size, 1, num_eqs);
Array3D<float> upper_diagonal(batch_size, 1, num_eqs);
Array3D<float> rhs(batch_size, num_rhs, num_eqs);
lower_diagonal.FillRandom(1.0, 0.0, 0);
main_diagonal.FillRandom(0.05, 1.0,
batch_size * num_eqs);
upper_diagonal.FillRandom(1.0, 0.0,
2 * batch_size * num_eqs);
rhs.FillRandom(1.0, 0.0, 3 * batch_size * num_eqs);
XlaOp lower_diagonal_xla;
XlaOp main_diagonal_xla;
XlaOp upper_diagonal_xla;
XlaOp rhs_xla;
auto lower_diagonal_data = CreateR3Parameter<float>(
lower_diagonal, 0, "lower_diagonal", &builder, &lower_diagonal_xla);
auto main_diagonal_data = CreateR3Parameter<float>(
main_diagonal, 1, "main_diagonal", &builder, &main_diagonal_xla);
auto upper_diagonal_data = CreateR3Parameter<float>(
upper_diagonal, 2, "upper_diagonal", &builder, &upper_diagonal_xla);
auto rhs_data = CreateR3Parameter<float>(rhs, 3, "rhs", &builder, &rhs_xla);
TF_ASSERT_OK_AND_ASSIGN(
XlaOp x, TridiagonalSolver(kThomas, lower_diagonal_xla, main_diagonal_xla,
upper_diagonal_xla, rhs_xla));
auto Coefficient = [](auto operand, auto i) {
return SliceInMinorDims(operand, {i}, {i + 1});
};
std::vector<XlaOp> relative_errors(num_eqs);
for (int64_t i = 0; i < num_eqs; i++) {
auto a_i = Coefficient(lower_diagonal_xla, i);
auto b_i = Coefficient(main_diagonal_xla, i);
auto c_i = Coefficient(upper_diagonal_xla, i);
auto d_i = Coefficient(rhs_xla, i);
if (i == 0) {
relative_errors[i] =
(b_i * Coefficient(x, i) + c_i * Coefficient(x, i + 1) - d_i) / d_i;
} else if (i == num_eqs - 1) {
relative_errors[i] =
(a_i * Coefficient(x, i - 1) + b_i * Coefficient(x, i) - d_i) / d_i;
} else {
relative_errors[i] =
(a_i * Coefficient(x, i - 1) + b_i * Coefficient(x, i) +
c_i * Coefficient(x, i + 1) - d_i) /
d_i;
}
}
Abs(ConcatInDim(&builder, relative_errors, 2));
TF_ASSERT_OK_AND_ASSIGN(
auto result,
ComputeAndTransfer(&builder,
{lower_diagonal_data.get(), main_diagonal_data.get(),
upper_diagonal_data.get(), rhs_data.get()}));
auto result_data = result.data<float>({});
for (auto result_component : result_data) {
EXPECT_TRUE(result_component < 5e-3);
}
}
INSTANTIATE_TEST_CASE_P(TridiagonalTestInstantiation, TridiagonalTest,
::testing::Combine(::testing::Values(1, 12),
::testing::Values(4, 8),
::testing::Values(1, 12)));
}
}
} | 2,233 |
#ifndef XLA_TSL_DISTRIBUTED_RUNTIME_CALL_OPTIONS_H_
#define XLA_TSL_DISTRIBUTED_RUNTIME_CALL_OPTIONS_H_
#include <functional>
#include "tsl/platform/macros.h"
#include "tsl/platform/mutex.h"
#include "tsl/platform/thread_annotations.h"
#include "tsl/platform/types.h"
namespace tsl {
class CallOptions {
public:
CallOptions();
void StartCancel();
typedef std::function<void()> CancelFunction;
void SetCancelCallback(CancelFunction cancel_func);
void ClearCancelCallback();
int64_t GetTimeout();
void SetTimeout(int64_t ms);
private:
mutex mu_;
CancelFunction cancel_func_ TF_GUARDED_BY(mu_);
int64_t timeout_in_ms_ TF_GUARDED_BY(mu_) = 0;
CallOptions(const CallOptions&) = delete;
void operator=(const CallOptions&) = delete;
};
}
#endif
#include "xla/tsl/distributed_runtime/call_options.h"
#include <utility>
#include "tsl/platform/mutex.h"
namespace tsl {
CallOptions::CallOptions() = default;
void CallOptions::StartCancel() {
mutex_lock l(mu_);
if (cancel_func_ != nullptr) {
cancel_func_();
}
}
void CallOptions::SetCancelCallback(CancelFunction cancel_func) {
mutex_lock l(mu_);
cancel_func_ = std::move(cancel_func);
}
void CallOptions::ClearCancelCallback() {
mutex_lock l(mu_);
cancel_func_ = nullptr;
}
int64_t CallOptions::GetTimeout() {
mutex_lock l(mu_);
return timeout_in_ms_;
}
void CallOptions::SetTimeout(int64_t ms) {
mutex_lock l(mu_);
timeout_in_ms_ = ms;
}
} | #include "tensorflow/core/distributed_runtime/call_options.h"
#include "tensorflow/core/platform/test.h"
namespace tensorflow {
TEST(CallOptions, Cancel) {
int num_calls = 0;
CallOptions opts;
opts.StartCancel();
EXPECT_EQ(num_calls, 0);
opts.SetCancelCallback([&num_calls]() { num_calls++; });
EXPECT_EQ(num_calls, 0);
opts.StartCancel();
EXPECT_EQ(num_calls, 1);
opts.StartCancel();
EXPECT_EQ(num_calls, 2);
opts.ClearCancelCallback();
EXPECT_EQ(num_calls, 2);
opts.StartCancel();
EXPECT_EQ(num_calls, 2);
}
} | 2,234 |
#ifndef XLA_TSL_DISTRIBUTED_RUNTIME_PREEMPTION_PREEMPTION_SYNC_MANAGER_H_
#define XLA_TSL_DISTRIBUTED_RUNTIME_PREEMPTION_PREEMPTION_SYNC_MANAGER_H_
#include <memory>
#include <string>
#include "xla/tsl/distributed_runtime/coordination/coordination_service_agent.h"
#include "xla/tsl/distributed_runtime/preemption/preemption_notifier.h"
#include "tsl/platform/status.h"
namespace tsl {
class PreemptionSyncManager {
public:
virtual ~PreemptionSyncManager() = default;
virtual absl::Status Initialize(CoordinationServiceAgent* agent) = 0;
virtual absl::Status Initialize(
CoordinationServiceAgent* agent,
const std::string& preemption_notifier_type) = 0;
virtual absl::Status Initialize(
CoordinationServiceAgent* agent,
std::unique_ptr<PreemptionNotifier> notifier) = 0;
virtual bool ReachedSyncPoint(int step_counter) = 0;
};
std::unique_ptr<PreemptionSyncManager> CreatePreemptionSyncManager();
}
#endif
#include "xla/tsl/distributed_runtime/preemption/preemption_sync_manager.h"
#include <algorithm>
#include <functional>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "absl/strings/str_cat.h"
#include "absl/synchronization/notification.h"
#include "absl/time/time.h"
#include "xla/tsl/distributed_runtime/call_options.h"
#include "xla/tsl/distributed_runtime/coordination/coordination_service_agent.h"
#include "xla/tsl/distributed_runtime/preemption/preemption_notifier.h"
#include "tsl/lib/monitoring/gauge.h"
#include "tsl/platform/env.h"
#include "tsl/platform/mutex.h"
#include "tsl/platform/statusor.h"
#include "tsl/protobuf/coordination_service.pb.h"
namespace tsl {
namespace {
using tensorflow::CoordinatedTask;
using tensorflow::KeyValueEntry;
constexpr int64_t kPreemptionSyncUnsetCounter = -1;
constexpr char kPreemptionNoticeKey[] = "RECEIVED_PREEMPTION_NOTICE";
constexpr char kPreemptionCounterDirKey[] = "PREEMPTION_CURRENT_COUNTER/";
constexpr char kPreemptionBarrier[] = "PREEMPTION_SYNC_BARRIER";
constexpr absl::Duration kPreemptionBarrierTimeout = absl::Minutes(3);
auto* sync_usage_metric = monitoring::Gauge<bool, 0>::New(
"/coordination_service/preempt_manager/reached_sync_point_usage",
"Records if preempt sync manager's ReachSyncPoint() was called at least "
"once.");
auto* notified_metric = monitoring::Gauge<bool, 0>::New(
"/coordination_service/preempt_manager/notified",
"Records receipt of preemption notification.");
auto* set_sync_point_metric = monitoring::Gauge<bool, 0>::New(
"/coordination_service/preempt_manager/set_sync_point",
"Records that sync point is set.");
auto* reached_sync_point_metric = monitoring::Gauge<bool, 0>::New(
"/coordination_service/preempt_manager/reached_sync_point",
"Records that sync point is reached.");
constexpr absl::Duration kProtocolDuration = absl::Minutes(15);
class PreemptionSyncManagerImpl : public PreemptionSyncManager {
public:
PreemptionSyncManagerImpl() = default;
~PreemptionSyncManagerImpl() override {
shutdown_.Notify();
}
absl::Status Initialize(CoordinationServiceAgent* agent) override;
absl::Status Initialize(CoordinationServiceAgent* agent,
const std::string& preemption_notifier_type) override;
absl::Status Initialize(
CoordinationServiceAgent* agent,
std::unique_ptr<PreemptionNotifier> notifier) override;
bool ReachedSyncPoint(int step_counter) override;
private:
void ComputeSyncCallCounter(absl::Time death_time);
void CancelPreemptionBarrier();
mutex mu_;
int64_t call_counter_ TF_GUARDED_BY(mu_) = 0;
int64_t preemption_sync_counter_ TF_GUARDED_BY(mu_) =
kPreemptionSyncUnsetCounter;
std::string current_call_counter_key_;
Env* env_;
CoordinationServiceAgent* agent_;
absl::Notification shutdown_;
std::unique_ptr<Thread> sync_protocol_thread_;
std::unique_ptr<PreemptionNotifier> preemption_notifier_;
std::shared_ptr<CallOptions> call_opts_;
};
absl::Status PreemptionSyncManagerImpl::Initialize(
CoordinationServiceAgent* agent) {
return Initialize(agent, "sigterm");
}
absl::Status PreemptionSyncManagerImpl::Initialize(
CoordinationServiceAgent* agent,
const std::string& preemption_notifier_type) {
TF_ASSIGN_OR_RETURN(Env * env, agent->GetEnv());
return Initialize(agent, PreemptionNotifier::CreatePreemptionNotifier(
preemption_notifier_type, env));
}
absl::Status PreemptionSyncManagerImpl::Initialize(
CoordinationServiceAgent* agent,
std::unique_ptr<PreemptionNotifier> notifier) {
TF_ASSIGN_OR_RETURN(Env * env, agent->GetEnv());
env_ = env;
agent_ = agent;
preemption_notifier_ = std::move(notifier);
TF_ASSIGN_OR_RETURN(CoordinatedTask own_task, agent->GetOwnTask());
const std::string task_name =
absl::StrCat("/job:", own_task.job_name(), "/task:", own_task.task_id());
current_call_counter_key_ = absl::StrCat(kPreemptionCounterDirKey, task_name);
preemption_notifier_->WillBePreemptedAtAsync(
[agent = agent_, task_name](absl::StatusOr<absl::Time> death_time) {
if (!death_time.ok()) {
if (errors::IsCancelled(death_time.status())) {
LOG(INFO) << "Preemption sync protocol cancelled by notifier: "
<< death_time.status()
<< ". This is expected during program shutdown.";
} else {
LOG(ERROR) << "Error from preemption notifier: "
<< death_time.status();
}
return;
}
notified_metric->GetCell()->Set(true);
const absl::Status s = agent->InsertKeyValue(
kPreemptionNoticeKey, absl::FormatTime(*death_time));
LOG(INFO) << "Notified coordination service that this task will "
"be preempted at "
<< *death_time << ". absl::Status: " << s;
});
call_opts_ = agent_->GetKeyValueAsync(
kPreemptionNoticeKey,
[this, agent = agent_](absl::StatusOr<std::string> status_or_death_time) {
if (errors::IsCancelled(status_or_death_time.status())) {
LOG(INFO) << "Cancelled call to retrieve preemption notice. This is "
"expected upon program shutdown.";
return;
} else if (!status_or_death_time.ok()) {
LOG(WARNING)
<< "Failed to retrieve preemption notice from "
"coordination service: "
<< status_or_death_time.status()
<< ". This is only expected if one of the tasks is unhealthy."
" Check the logs for the actual root cause.";
agent->CancelBarrierAsync(
kPreemptionBarrier, [](const absl::Status& status) {
if (!status.ok()) {
LOG(ERROR)
<< "Failed to cancel preemption barrier: " << status;
}
});
return;
}
std::string err;
absl::Time death_time;
if (absl::ParseTime(absl::RFC3339_full, *status_or_death_time,
&death_time, &err)) {
LOG(INFO) << "Received preemption notice with death_time "
<< death_time;
} else {
LOG(ERROR) << "Unable to parse preemption notice's death time: "
<< err;
CancelPreemptionBarrier();
return;
}
sync_protocol_thread_ = absl::WrapUnique(env_->StartThread(
{}, "PreemptionSyncManager_SyncProtocol",
std::bind(&PreemptionSyncManagerImpl::ComputeSyncCallCounter, this,
death_time)));
});
return absl::OkStatus();
}
void PreemptionSyncManagerImpl::ComputeSyncCallCounter(absl::Time death_time) {
const absl::Duration remaining_time = death_time - absl::Now();
if (remaining_time > kProtocolDuration) {
LOG(INFO) << "Will begin preemption sync protocol in " << remaining_time;
const absl::Duration sleep_time = remaining_time - kProtocolDuration;
if (shutdown_.WaitForNotificationWithTimeout(sleep_time)) {
LOG(WARNING)
<< "Shutdown is triggered before preemption sync protocol has begun.";
CancelPreemptionBarrier();
return;
}
}
mutex_lock l(mu_);
const absl::Status notified_status = agent_->InsertKeyValue(
current_call_counter_key_, std::to_string(call_counter_));
if (!notified_status.ok()) {
LOG(ERROR) << "Preemption sync failed - could not inform service of "
"current call counter: "
<< notified_status;
CancelPreemptionBarrier();
return;
}
const absl::Status barrier_status =
agent_->WaitAtBarrier(kPreemptionBarrier, kPreemptionBarrierTimeout, {});
if (!barrier_status.ok()) {
LOG(ERROR) << "Preemption sync barrier failed: " << barrier_status;
return;
}
absl::StatusOr<std::vector<KeyValueEntry>> all_counters =
agent_->GetKeyValueDir(kPreemptionCounterDirKey);
if (!all_counters.ok()) {
LOG(ERROR) << "Preemption sync failed - unable to retrieve call counters: "
<< all_counters.status();
return;
}
int64_t max_counter = kPreemptionSyncUnsetCounter;
for (const auto& kv : *all_counters) {
int64_t call_counter;
if (!absl::SimpleAtoi(kv.value(), &call_counter)) {
LOG(ERROR) << "Preemption sync failed - failed to parse preemption call "
"counter: "
<< kv.DebugString();
return;
}
max_counter = std::max(max_counter, call_counter);
}
if (max_counter == kPreemptionSyncUnsetCounter) {
LOG(ERROR) << "Preemption sync failed - no call counters found.";
return;
}
preemption_sync_counter_ = max_counter + 1;
LOG(INFO) << "Preemption sync counter is set: " << preemption_sync_counter_;
set_sync_point_metric->GetCell()->Set(true);
}
void PreemptionSyncManagerImpl::CancelPreemptionBarrier() {
agent_->CancelBarrierAsync(
kPreemptionBarrier, [](const absl::Status& status) {
if (!status.ok()) {
LOG(ERROR) << "Failed to cancel preemption barrier: " << status;
}
});
}
bool PreemptionSyncManagerImpl::ReachedSyncPoint(int step_counter) {
sync_usage_metric->GetCell()->Set(true);
mutex_lock l(mu_);
call_counter_ = step_counter;
VLOG(3) << "Current call counter: " << call_counter_
<< ", Preemption sync point: " << preemption_sync_counter_;
const bool reached_sync_point = preemption_sync_counter_ == call_counter_;
if (reached_sync_point) {
reached_sync_point_metric->GetCell()->Set(true);
}
return reached_sync_point;
}
}
std::unique_ptr<PreemptionSyncManager> CreatePreemptionSyncManager() {
return std::make_unique<PreemptionSyncManagerImpl>();
}
} | #include "xla/tsl/distributed_runtime/preemption/preemption_sync_manager.h"
#include <memory>
#include <string>
#include <utility>
#include "grpcpp/server.h"
#include "grpcpp/server_builder.h"
#include "grpcpp/support/channel_arguments.h"
#include "absl/memory/memory.h"
#include "absl/time/clock.h"
#include "absl/time/time.h"
#include "xla/tsl/distributed_runtime/coordination/coordination_client.h"
#include "xla/tsl/distributed_runtime/coordination/coordination_service.h"
#include "xla/tsl/distributed_runtime/coordination/coordination_service_agent.h"
#include "xla/tsl/distributed_runtime/preemption/preemption_notifier.h"
#include "xla/tsl/distributed_runtime/rpc/async_service_interface.h"
#include "xla/tsl/distributed_runtime/rpc/coordination/grpc_coordination_client.h"
#include "xla/tsl/distributed_runtime/rpc/coordination/grpc_coordination_service_impl.h"
#include "tsl/platform/env.h"
#include "tsl/platform/errors.h"
#include "tsl/platform/status.h"
#include "tsl/platform/test.h"
#include "tsl/platform/threadpool.h"
#include "tsl/protobuf/coordination_config.pb.h"
namespace tsl {
namespace {
using tensorflow::CoordinatedJob;
using tensorflow::CoordinatedTask;
using tensorflow::CoordinationServiceConfig;
constexpr char kJobName[] = "test_worker";
class FakePreemptionNotifier : public PreemptionNotifier {
public:
FakePreemptionNotifier() : PreemptionNotifier(nullptr) {}
~FakePreemptionNotifier() override {
NotifyRegisteredListeners(
errors::Cancelled("~FakePreemptionNotifier() was called."));
}
void AnnounceDeath(absl::Time death_time) {
LOG(WARNING) << "Received preemption notice with death time: "
<< death_time;
NotifyRegisteredListeners(death_time);
}
};
class PreemptionSyncManagerTest : public ::testing::Test {
protected:
PreemptionSyncManagerTest() {
StartCoordinationService();
InitializeAndConnectCoordinationAgents();
auto preempt_notifier = std::make_unique<FakePreemptionNotifier>();
preempt_notifier_ = preempt_notifier.get();
TF_CHECK_OK(preempt_sync_mgr_->Initialize(coord_agent_.get(),
std::move(preempt_notifier)));
auto preempt_notifier2 = std::make_unique<FakePreemptionNotifier>();
preempt_notifier2_ = preempt_notifier2.get();
TF_CHECK_OK(preempt_sync_mgr2_->Initialize(coord_agent2_.get(),
std::move(preempt_notifier2)));
}
~PreemptionSyncManagerTest() override {
preempt_sync_mgr_ = nullptr;
preempt_sync_mgr2_ = nullptr;
coord_agent_ = nullptr;
coord_agent2_ = nullptr;
coord_service_ = nullptr;
static_cast<tsl::GrpcCoordinationServiceImpl*>(coord_rpc_service_.get())
->SetCoordinationServiceInstance(nullptr);
grpc_server_->Shutdown();
coord_rpc_service_->Shutdown();
}
void SendPreemptionNotice(absl::Time death_time = absl::Now(),
bool to_task1 = true) {
if (to_task1) {
preempt_notifier_->AnnounceDeath(death_time);
} else {
preempt_notifier2_->AnnounceDeath(death_time);
}
Env::Default()->SleepForMicroseconds(
absl::ToInt64Microseconds(absl::Seconds(1)));
}
void SimulateUnhealthyTaskTwo() {
CoordinatedTask task2;
task2.set_job_name(kJobName);
task2.set_task_id(1);
TF_CHECK_OK(
coord_service_->ReportTaskError(task2, errors::Internal("test_error")));
}
std::unique_ptr<PreemptionSyncManager> preempt_sync_mgr_ =
CreatePreemptionSyncManager();
std::unique_ptr<PreemptionSyncManager> preempt_sync_mgr2_ =
CreatePreemptionSyncManager();
protected:
void StartCoordinationService() {
::grpc::ServerBuilder builder;
coord_service_ = EnableCoordinationService();
coord_compute_pool_ = std::make_unique<thread::ThreadPool>(
Env::Default(), "CoordinationServiceRpcHandler",
1);
coord_rpc_service_ = std::make_unique<GrpcCoordinationServiceImpl>(
coord_compute_pool_.get(), &builder);
auto* grpc_coord_service =
static_cast<GrpcCoordinationServiceImpl*>(coord_rpc_service_.get());
grpc_coord_service->SetCoordinationServiceInstance(coord_service_.get());
grpc_server_ = builder.BuildAndStart();
coord_rpc_thread_ = absl::WrapUnique(Env::Default()->StartThread(
{}, "CoordinationServiceHandleRPCsLoop",
[service = coord_rpc_service_.get()]() { service->HandleRPCsLoop(); }));
}
std::unique_ptr<CoordinationServiceInterface> EnableCoordinationService() {
CoordinationServiceConfig config;
config.set_service_type("standalone");
CoordinatedJob* job = config.mutable_coordinated_job_list()->Add();
job->set_name(kJobName);
job->set_num_tasks(2);
return CoordinationServiceInterface::EnableCoordinationService(
Env::Default(), config, nullptr);
}
void InitializeAndConnectCoordinationAgents() {
std::unique_ptr<CoordinationClient> coord_client =
absl::WrapUnique(NewGrpcCoordinationClient(
grpc_server_->InProcessChannel(::grpc::ChannelArguments())));
std::unique_ptr<CoordinationClient> coord_client2 =
absl::WrapUnique(NewGrpcCoordinationClient(
grpc_server_->InProcessChannel(::grpc::ChannelArguments())));
auto error_fn = [](const absl::Status& status) {
LOG(ERROR) << "Coordination service agent in error status: " << status;
};
CoordinationServiceConfig coord_config;
coord_config.set_service_leader("test_leader");
TF_CHECK_OK(coord_agent_->Initialize(Env::Default(), kJobName,
0, coord_config,
std::move(coord_client), error_fn));
TF_CHECK_OK(coord_agent2_->Initialize(Env::Default(), kJobName,
1, coord_config,
std::move(coord_client2), error_fn));
TF_CHECK_OK(coord_agent_->Connect());
TF_CHECK_OK(coord_agent2_->Connect());
}
std::unique_ptr<CoordinationServiceInterface> coord_service_;
std::unique_ptr<::grpc::Server> grpc_server_;
std::unique_ptr<thread::ThreadPool> coord_compute_pool_;
std::unique_ptr<AsyncServiceInterface> coord_rpc_service_;
std::unique_ptr<Thread> coord_rpc_thread_;
std::unique_ptr<CoordinationServiceAgent> coord_agent_ =
CreateCoordinationServiceAgent();
FakePreemptionNotifier* preempt_notifier_;
std::unique_ptr<CoordinationServiceAgent> coord_agent2_ =
CreateCoordinationServiceAgent();
FakePreemptionNotifier* preempt_notifier2_;
};
TEST_F(PreemptionSyncManagerTest, NoPreemption_NoSyncPoint) {
int step_counter = 0;
EXPECT_FALSE(preempt_sync_mgr_->ReachedSyncPoint(step_counter++));
EXPECT_FALSE(preempt_sync_mgr_->ReachedSyncPoint(step_counter++));
EXPECT_FALSE(preempt_sync_mgr_->ReachedSyncPoint(step_counter++));
}
TEST_F(PreemptionSyncManagerTest, Preemption_SingleSyncPoint) {
int step_counter = 0;
EXPECT_FALSE(preempt_sync_mgr_->ReachedSyncPoint(step_counter++));
EXPECT_FALSE(preempt_sync_mgr_->ReachedSyncPoint(step_counter++));
SendPreemptionNotice();
EXPECT_TRUE(preempt_sync_mgr_->ReachedSyncPoint(step_counter++));
EXPECT_FALSE(preempt_sync_mgr_->ReachedSyncPoint(step_counter++));
}
TEST_F(PreemptionSyncManagerTest, DelayedPreemption_NoSyncPointYet) {
int step_counter = 0;
EXPECT_FALSE(preempt_sync_mgr_->ReachedSyncPoint(step_counter++));
EXPECT_FALSE(preempt_sync_mgr_->ReachedSyncPoint(step_counter++));
SendPreemptionNotice(absl::Now() + absl::Hours(1));
EXPECT_FALSE(preempt_sync_mgr_->ReachedSyncPoint(step_counter++));
}
TEST_F(PreemptionSyncManagerTest, UnhealthyTask_NoSyncPoint) {
int step_counter = 0;
EXPECT_FALSE(preempt_sync_mgr_->ReachedSyncPoint(step_counter++));
EXPECT_FALSE(preempt_sync_mgr_->ReachedSyncPoint(step_counter++));
SimulateUnhealthyTaskTwo();
SendPreemptionNotice();
EXPECT_FALSE(preempt_sync_mgr_->ReachedSyncPoint(step_counter++));
}
TEST_F(PreemptionSyncManagerTest, ShutdownTasksWithoutPreemption) {
int step_counter = 0;
EXPECT_FALSE(preempt_sync_mgr_->ReachedSyncPoint(step_counter++));
EXPECT_FALSE(preempt_sync_mgr_->ReachedSyncPoint(step_counter++));
TF_CHECK_OK(coord_agent_->Shutdown());
TF_CHECK_OK(coord_agent2_->Shutdown());
EXPECT_FALSE(preempt_sync_mgr_->ReachedSyncPoint(step_counter++));
}
TEST_F(PreemptionSyncManagerTest, PreemptSlowTask) {
int step_counter0 = 0;
int step_counter2 = 0;
EXPECT_FALSE(preempt_sync_mgr_->ReachedSyncPoint(step_counter0++));
EXPECT_FALSE(preempt_sync_mgr2_->ReachedSyncPoint(step_counter2++));
EXPECT_FALSE(preempt_sync_mgr2_->ReachedSyncPoint(step_counter2++));
EXPECT_FALSE(preempt_sync_mgr2_->ReachedSyncPoint(step_counter2++));
SendPreemptionNotice();
EXPECT_FALSE(preempt_sync_mgr_->ReachedSyncPoint(step_counter0++));
EXPECT_FALSE(preempt_sync_mgr_->ReachedSyncPoint(step_counter0++));
EXPECT_TRUE(preempt_sync_mgr_->ReachedSyncPoint(step_counter0++));
EXPECT_TRUE(preempt_sync_mgr2_->ReachedSyncPoint(step_counter2++));
}
TEST_F(PreemptionSyncManagerTest, PreemptFastTask) {
int step_counter0 = 0;
int step_counter2 = 0;
EXPECT_FALSE(preempt_sync_mgr_->ReachedSyncPoint(step_counter0++));
EXPECT_FALSE(preempt_sync_mgr2_->ReachedSyncPoint(step_counter2++));
EXPECT_FALSE(preempt_sync_mgr2_->ReachedSyncPoint(step_counter2++));
EXPECT_FALSE(preempt_sync_mgr2_->ReachedSyncPoint(step_counter2++));
SendPreemptionNotice(absl::Now(), false);
EXPECT_FALSE(preempt_sync_mgr_->ReachedSyncPoint(step_counter0++));
EXPECT_FALSE(preempt_sync_mgr_->ReachedSyncPoint(step_counter0++));
EXPECT_TRUE(preempt_sync_mgr_->ReachedSyncPoint(step_counter0++));
EXPECT_TRUE(preempt_sync_mgr2_->ReachedSyncPoint(step_counter2++));
}
}
} | 2,235 |
#ifndef XLA_TSL_DISTRIBUTED_RUNTIME_PREEMPTION_PREEMPTION_NOTIFIER_H_
#define XLA_TSL_DISTRIBUTED_RUNTIME_PREEMPTION_PREEMPTION_NOTIFIER_H_
#include <functional>
#include <memory>
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>
#include "absl/strings/str_join.h"
#include "absl/time/time.h"
#include "tsl/platform/env.h"
#include "tsl/platform/mutex.h"
#include "tsl/platform/statusor.h"
namespace tsl {
#define REGISTER_PREEMPTION_NOTIFIER(notifier_type_name, factory_fn) \
REGISTER_PREEMPTION_NOTIFIER_UNIQ_HELPER(__COUNTER__, notifier_type_name, \
factory_fn)
#define REGISTER_PREEMPTION_NOTIFIER_UNIQ_HELPER(counter, notifier_type_name, \
factory_fn) \
static bool static_preemption_notifier_##counter TF_ATTRIBUTE_UNUSED = \
[]() { \
::tsl::PreemptionNotifier::RegisterPreemptionNotifier( \
notifier_type_name, factory_fn); \
return true; \
}()
class PreemptionNotifier {
public:
typedef std::function<void(absl::StatusOr<absl::Time>)> PreemptTimeCallback;
using PreemptionNotifierFactory =
std::function<std::unique_ptr<PreemptionNotifier>(Env* env)>;
explicit PreemptionNotifier(Env* env) : env_(env) {}
virtual ~PreemptionNotifier() = default;
static void RegisterPreemptionNotifier(const std::string& notifier_type_name,
PreemptionNotifierFactory factory_fn) {
GetPreemptionNotifierFactories()->emplace(notifier_type_name,
std::move(factory_fn));
}
static std::unique_ptr<PreemptionNotifier> CreatePreemptionNotifier(
const std::string& notifier_type, Env* env) {
const auto* factories = GetPreemptionNotifierFactories();
auto it = factories->find(notifier_type);
if (it == factories->end()) {
std::vector<std::string> registered_types;
registered_types.reserve(factories->size());
for (auto& kv : *factories) {
registered_types.push_back(kv.first);
}
LOG(ERROR) << "No preemption notifier factory found for notifier type "
<< notifier_type
<< ". All registered preemption notifier types are: "
<< absl::StrJoin(registered_types, ", ")
<< ". Make sure the library is loaded to the program.";
return nullptr;
}
return it->second(env);
}
absl::StatusOr<absl::Time> WillBePreemptedAt();
void WillBePreemptedAtAsync(PreemptTimeCallback callback);
protected:
Env* GetEnv() { return env_; }
void NotifyRegisteredListeners(absl::StatusOr<absl::Time> death_time);
private:
static std::unordered_map<std::string, PreemptionNotifierFactory>*
GetPreemptionNotifierFactories() {
static auto* preemption_notifier_factories =
new std::unordered_map<std::string, PreemptionNotifierFactory>();
return preemption_notifier_factories;
}
Env* env_;
mutex mu_;
absl::Time death_time_ TF_GUARDED_BY(mu_) = absl::InfinitePast();
std::vector<PreemptTimeCallback> callbacks_ TF_GUARDED_BY(mu_);
};
}
#endif
#include "xla/tsl/distributed_runtime/preemption/preemption_notifier.h"
#include <atomic>
#include <csignal>
#include <functional>
#include <memory>
#include <utility>
#include "absl/synchronization/notification.h"
#include "absl/time/clock.h"
#include "absl/time/time.h"
#include "tsl/platform/env.h"
#include "tsl/platform/errors.h"
#include "tsl/platform/mutex.h"
#include "tsl/platform/statusor.h"
#if defined(PLATFORM_GOOGLE)
#include "thread/executor.h"
#include "thread/signal.h"
#endif
namespace tsl {
namespace {
constexpr absl::Duration kListenInterval = absl::Seconds(1);
constexpr absl::Time kUnsetDeathTime = absl::InfinitePast();
static std::atomic_bool sigterm_received(false);
class SigtermNotifier : public PreemptionNotifier {
public:
explicit SigtermNotifier(Env* env);
~SigtermNotifier() override {
shutdown_notification_.Notify();
}
private:
void StartListenerThread();
absl::Notification shutdown_notification_;
std::unique_ptr<Thread> preempt_listener_thread_;
};
SigtermNotifier::SigtermNotifier(Env* env) : PreemptionNotifier(env) {
sigterm_received.store(false);
StartListenerThread();
#if defined(PLATFORM_GOOGLE)
thread::signal::Token unused_token;
thread::signal::AddHandler(
SIGTERM, thread::Executor::DefaultExecutor(),
[]() { sigterm_received.store(true); },
0,
&unused_token);
#else
std::signal(SIGTERM, [](int signal) { sigterm_received.store(true); });
#endif
}
void SigtermNotifier::StartListenerThread() {
preempt_listener_thread_.reset(
GetEnv()->StartThread({}, "PreemptionNotifier_Listen", [this]() {
while (!sigterm_received.load()) {
if (shutdown_notification_.WaitForNotificationWithTimeout(
kListenInterval)) {
NotifyRegisteredListeners(
errors::Cancelled("Preemption notifier is being deleted."));
return;
}
}
const absl::Time death_time = absl::Now();
LOG(WARNING) << "SIGTERM caught at " << death_time;
NotifyRegisteredListeners(death_time);
}));
}
}
absl::StatusOr<absl::Time> PreemptionNotifier::WillBePreemptedAt() {
absl::Notification n;
absl::StatusOr<absl::Time> result;
WillBePreemptedAtAsync(
[&n, &result](absl::StatusOr<absl::Time> async_result) {
result = async_result;
n.Notify();
});
n.WaitForNotification();
return result;
}
void PreemptionNotifier::WillBePreemptedAtAsync(PreemptTimeCallback callback) {
mutex_lock l(mu_);
if (death_time_ == kUnsetDeathTime) {
callbacks_.push_back(std::move(callback));
} else {
callback(death_time_);
}
}
void PreemptionNotifier::NotifyRegisteredListeners(
absl::StatusOr<absl::Time> death_time) {
mutex_lock l(mu_);
if (death_time.ok()) {
death_time_ = death_time.value();
}
for (const auto& callback : callbacks_) {
callback(death_time);
}
callbacks_.clear();
}
REGISTER_PREEMPTION_NOTIFIER(
"sigterm", [](Env* env) -> std::unique_ptr<PreemptionNotifier> {
return std::make_unique<SigtermNotifier>(env);
});
} | #include "xla/tsl/distributed_runtime/preemption/preemption_notifier.h"
#include <csignal>
#include <functional>
#include <memory>
#include <utility>
#include "absl/synchronization/notification.h"
#include "absl/time/clock.h"
#include "absl/time/time.h"
#include "tsl/platform/env.h"
#include "tsl/platform/errors.h"
#include "tsl/platform/status.h"
#include "tsl/platform/statusor.h"
#include "tsl/platform/test.h"
#if defined(PLATFORM_GOOGLE)
#include "thread/executor.h"
#include "thread/signal.h"
#endif
namespace tsl {
namespace {
class PreemptNotifierTest : public ::testing::Test {
public:
PreemptNotifierTest() {
#if defined(PLATFORM_GOOGLE)
thread::signal::Token unused_token;
thread::signal::AddHandler(
SIGTERM, thread::Executor::DefaultExecutor(), []() {},
thread::signal::kOverrideDefault, &unused_token);
#endif
}
};
TEST_F(PreemptNotifierTest, WillBePreemptedAt) {
auto env = Env::Default();
std::unique_ptr<PreemptionNotifier> preempt_notifier =
PreemptionNotifier::CreatePreemptionNotifier("sigterm", env);
absl::Time start_time = absl::Now();
env->SchedClosureAfter(absl::ToInt64Microseconds(absl::Seconds(1)),
[]() { std::raise(SIGTERM); });
absl::StatusOr<absl::Time> result = preempt_notifier->WillBePreemptedAt();
TF_CHECK_OK(result.status());
absl::Time preempt_time = result.value();
absl::Duration time_diff = preempt_time - start_time;
EXPECT_GT(time_diff, absl::Seconds(1.0));
EXPECT_LT(time_diff, absl::Seconds(3));
}
TEST_F(PreemptNotifierTest,
WillBePreemptedAt_AlreadyPreempted_ReturnsImmediately) {
auto env = Env::Default();
std::unique_ptr<PreemptionNotifier> preempt_notifier =
PreemptionNotifier::CreatePreemptionNotifier("sigterm", env);
absl::Time start_time = absl::Now();
std::raise(SIGTERM);
env->SleepForMicroseconds(absl::ToInt64Microseconds(absl::Seconds(2)));
absl::StatusOr<absl::Time> result = preempt_notifier->WillBePreemptedAt();
TF_CHECK_OK(result.status());
absl::Time preempt_time = result.value();
absl::Duration time_diff = preempt_time - start_time;
EXPECT_GT(time_diff, absl::ZeroDuration());
EXPECT_LT(time_diff, absl::Seconds(2));
}
TEST_F(PreemptNotifierTest, WillBePreemptedAtAsync_SameResultForAllCallbacks) {
auto env = Env::Default();
std::unique_ptr<PreemptionNotifier> preempt_notifier =
PreemptionNotifier::CreatePreemptionNotifier("sigterm", env);
env->SchedClosureAfter(absl::ToInt64Microseconds(absl::Seconds(1)),
[]() { std::raise(SIGTERM); });
absl::StatusOr<absl::Time> preempt_time;
absl::StatusOr<absl::Time> preempt_time_2;
absl::Notification n;
absl::Notification n_2;
preempt_notifier->WillBePreemptedAtAsync(
[&preempt_time, &n](absl::StatusOr<absl::Time> result) {
preempt_time = result;
n.Notify();
});
preempt_notifier->WillBePreemptedAtAsync(
[&preempt_time_2, &n_2](absl::StatusOr<absl::Time> result) {
preempt_time_2 = result;
n_2.Notify();
});
n.WaitForNotification();
n_2.WaitForNotification();
TF_CHECK_OK(preempt_time.status());
TF_CHECK_OK(preempt_time_2.status());
EXPECT_EQ(preempt_time.value(), preempt_time_2.value());
}
TEST_F(PreemptNotifierTest, Reset_TwoDifferentPreemptTimesRecorded) {
auto env = Env::Default();
std::unique_ptr<PreemptionNotifier> preempt_notifier =
PreemptionNotifier::CreatePreemptionNotifier("sigterm", env);
std::raise(SIGTERM);
absl::StatusOr<absl::Time> result = preempt_notifier->WillBePreemptedAt();
TF_CHECK_OK(result.status());
absl::Time preempt_time = result.value();
preempt_notifier =
PreemptionNotifier::CreatePreemptionNotifier("sigterm", env);
std::raise(SIGTERM);
absl::Time preempt_time_2 = preempt_notifier->WillBePreemptedAt().value();
EXPECT_NE(preempt_time, preempt_time_2);
}
TEST_F(PreemptNotifierTest, DestructorCancelsPendingCalls) {
auto env = Env::Default();
std::unique_ptr<PreemptionNotifier> preempt_notifier =
PreemptionNotifier::CreatePreemptionNotifier("sigterm", env);
absl::StatusOr<absl::Time> result;
absl::Notification n;
preempt_notifier->WillBePreemptedAtAsync(
[&result, &n](absl::StatusOr<absl::Time> status_or_time) {
result = status_or_time;
n.Notify();
});
preempt_notifier = nullptr;
n.WaitForNotification();
EXPECT_TRUE(errors::IsCancelled(result.status()));
}
}
} | 2,236 |
#ifndef XLA_TSL_DISTRIBUTED_RUNTIME_RPC_GRPC_CHANNEL_H_
#define XLA_TSL_DISTRIBUTED_RUNTIME_RPC_GRPC_CHANNEL_H_
#include <map>
#include <memory>
#include <set>
#include <string>
#include <vector>
#include "grpcpp/grpcpp.h"
#include "xla/tsl/distributed_runtime/rpc/grpc_util.h"
#include "tsl/protobuf/rpc_options.pb.h"
namespace tsl {
using tensorflow::RPCOptions;
class GrpcChannelSpec {
public:
struct HostPortsJob {
HostPortsJob(const string& job_id, const std::map<int, string>& host_ports)
: job_id(job_id), host_ports(host_ports) {}
const string job_id;
const std::map<int, string> host_ports;
};
absl::Status AddHostPortsJob(const string& job_id,
const std::map<int, string>& host_ports);
const std::vector<HostPortsJob>& host_ports_jobs() const {
return host_ports_jobs_;
}
private:
std::vector<HostPortsJob> host_ports_jobs_;
std::set<string> job_ids_;
};
class GrpcChannelCache {
public:
virtual ~GrpcChannelCache() {}
virtual void ListWorkers(std::vector<string>* workers) = 0;
virtual void ListWorkersInJob(const string& job_name,
std::vector<string>* workers) = 0;
virtual SharedGrpcChannelPtr FindWorkerChannel(const string& target) = 0;
virtual string TranslateTask(const string& task) = 0;
};
typedef std::function<SharedGrpcChannelPtr(string)> ChannelCreationFunction;
GrpcChannelCache* NewGrpcChannelCache(
const GrpcChannelSpec& channel_spec, ChannelCreationFunction channel_func,
const RPCOptions& rpc_options = RPCOptions());
::grpc::ChannelArguments GetChannelArguments(const RPCOptions* rpc_options);
ChannelCreationFunction ConvertToChannelCreationFunction(
const std::function<absl::Status(string, const RPCOptions*,
SharedGrpcChannelPtr*)>&
new_channel_func_ptr);
absl::Status NewHostPortGrpcChannel(const string& target,
const RPCOptions* rpc_options,
SharedGrpcChannelPtr* channel_pointer);
}
#endif
#include "xla/tsl/distributed_runtime/rpc/grpc_channel.h"
#include <cstdlib>
#include <limits>
#include <map>
#include <string>
#include <unordered_map>
#include "grpcpp/create_channel.h"
#include "absl/strings/escaping.h"
#include "absl/strings/match.h"
#include "absl/strings/str_split.h"
#include "xla/tsl/distributed_runtime/rpc/grpc_channel_common.h"
#include "xla/tsl/util/device_name_utils.h"
#include "tsl/lib/gtl/map_util.h"
#include "tsl/platform/errors.h"
#include "tsl/platform/logging.h"
#include "tsl/platform/macros.h"
#include "tsl/platform/mutex.h"
#include "tsl/platform/numbers.h"
#include "tsl/platform/status.h"
#include "tsl/platform/str_util.h"
#include "tsl/platform/strcat.h"
#include "tsl/platform/thread_annotations.h"
#include "tsl/platform/types.h"
#include "tsl/protobuf/rpc_options.pb.h"
namespace tsl {
namespace {
string MakeAddress(const string& job, int replica, int task) {
return strings::StrCat("/job:", job, "/replica:", replica, "/task:", task);
}
absl::Status ValidateHostPortPair(const string& host_port) {
string bns_prefix = "/bns/";
if (host_port.substr(0, bns_prefix.length()) == bns_prefix) {
return absl::OkStatus();
}
uint32 port;
auto colon_index = host_port.find_last_of(':');
if (!strings::safe_strtou32(host_port.substr(colon_index + 1), &port) ||
host_port.substr(0, colon_index).find('/') != string::npos) {
return errors::InvalidArgument("Could not interpret \"", host_port,
"\" as a host-port pair.");
}
return absl::OkStatus();
}
::grpc::ChannelArguments* CreateDefaultChannelArguments() {
::grpc::ChannelArguments* args = new ::grpc::ChannelArguments();
const char* env = std::getenv("TF_GRPC_DEFAULT_OPTIONS");
if (env != nullptr) {
for (auto& grpc_option : absl::StrSplit(env, ',')) {
std::vector<string> name_value = absl::StrSplit(grpc_option, '=');
if (name_value.size() != 2) {
LOG(ERROR) << "Invalid GRPC options format: " << grpc_option;
continue;
}
VLOG(3) << "Setting GRPC default for '" << name_value[0] << "' to '"
<< name_value[1] << "'";
if (name_value[1].size() >= 2 && name_value[1][0] == '"') {
string ue_value = name_value[1].substr(1, name_value[1].size() - 2);
string value;
string error;
if (!absl::CUnescape(ue_value, &value, &error)) {
LOG(ERROR) << "Failed to parse escaped string for " << grpc_option
<< ": " << error;
} else {
args->SetString(name_value[0], value);
}
} else {
int64_t value;
if (strings::safe_strto64(name_value[1], &value)) {
args->SetInt(name_value[0], value);
} else {
LOG(ERROR) << "Invalid integer value: " << grpc_option;
}
}
}
}
return args;
}
const ::grpc::ChannelArguments* GetDefaultChannelArguments() {
static const ::grpc::ChannelArguments* args = CreateDefaultChannelArguments();
return args;
}
}
::grpc::ChannelArguments GetChannelArguments(const RPCOptions* rpc_options) {
::grpc::ChannelArguments args = *GetDefaultChannelArguments();
args.SetInt(GRPC_ARG_MAX_MESSAGE_LENGTH, std::numeric_limits<int32>::max());
args.SetInt(GRPC_ARG_MAX_RECONNECT_BACKOFF_MS, 1000);
if (rpc_options != nullptr) {
if (rpc_options->compression_algorithm() == "deflate") {
args.SetCompressionAlgorithm(GRPC_COMPRESS_DEFLATE);
args.SetInt(GRPC_COMPRESSION_CHANNEL_DEFAULT_LEVEL,
rpc_options->compression_level());
VLOG(5) << "Setting GRPC compression : algo='"
<< rpc_options->compression_algorithm()
<< "' level=" << rpc_options->compression_level();
} else if (rpc_options->compression_algorithm() == "gzip") {
args.SetCompressionAlgorithm(GRPC_COMPRESS_GZIP);
args.SetInt(GRPC_COMPRESSION_CHANNEL_DEFAULT_LEVEL,
rpc_options->compression_level());
VLOG(5) << "Setting GRPC compression : algo='"
<< rpc_options->compression_algorithm()
<< "' level=" << rpc_options->compression_level();
} else if (!rpc_options->compression_algorithm().empty()) {
LOG(ERROR) << "Invalid compression algorithm: "
<< rpc_options->compression_algorithm();
}
if (rpc_options->disable_session_connection_sharing()) {
VLOG(5) << "Disabling TCP connection sharing";
args.SetInt(GRPC_ARG_USE_LOCAL_SUBCHANNEL_POOL, true);
}
}
return args;
}
absl::Status NewHostPortGrpcChannel(const string& target,
const RPCOptions* rpc_options,
SharedGrpcChannelPtr* channel_pointer) {
TF_RETURN_IF_ERROR(ValidateHostPortPair(target));
::grpc::ChannelArguments args = GetChannelArguments(rpc_options);
*channel_pointer = ::grpc::CreateCustomChannel(
"dns:
return absl::OkStatus();
}
ChannelCreationFunction ConvertToChannelCreationFunction(
const std::function<absl::Status(string, const RPCOptions*,
SharedGrpcChannelPtr*)>&
new_channel_func_ptr) {
return [new_channel_func_ptr](const string& target) -> SharedGrpcChannelPtr {
SharedGrpcChannelPtr channel_ptr;
if (new_channel_func_ptr(target, nullptr, &channel_ptr)
.ok()) {
return channel_ptr;
} else {
return nullptr;
}
};
}
absl::Status GrpcChannelSpec::AddHostPortsJob(
const string& job_id, const std::map<int, string>& host_ports) {
if (!job_ids_.insert(job_id).second) {
return errors::InvalidArgument(
"Duplicate job ID in cluster specification: ", job_id);
}
for (const auto& id_host_port : host_ports) {
TF_RETURN_IF_ERROR(ValidateHostPortPair(id_host_port.second));
}
host_ports_jobs_.emplace_back(job_id, host_ports);
return absl::OkStatus();
}
namespace {
using CachingGrpcChannelCache = GenericCachingChannelCache<GrpcChannelCache>;
class MultiGrpcChannelCache : public CachingGrpcChannelCache {
public:
explicit MultiGrpcChannelCache(const std::vector<GrpcChannelCache*>& caches,
int num_channels_per_target)
: CachingGrpcChannelCache(num_channels_per_target), caches_(caches) {}
~MultiGrpcChannelCache() override {
for (GrpcChannelCache* cache : caches_) {
delete cache;
}
}
void ListWorkers(std::vector<string>* workers) override {
for (GrpcChannelCache* cache : caches_) {
cache->ListWorkers(workers);
}
}
void ListWorkersInJob(const string& job_name,
std::vector<string>* workers) override {
for (GrpcChannelCache* cache : caches_) {
cache->ListWorkersInJob(job_name, workers);
}
}
string TranslateTask(const string& target) override {
mutex_lock l(mu_);
GrpcChannelCache* cache = gtl::FindPtrOrNull(target_caches_, target);
if (cache == nullptr) {
for (GrpcChannelCache* c : caches_) {
string r = c->TranslateTask(target);
if (!r.empty()) {
target_caches_.insert({target, c});
cache = c;
break;
}
}
}
CHECK(cache) << "Could not find GrpcChannelCache holding channel for "
<< target;
return cache->TranslateTask(target);
}
protected:
SharedGrpcChannelPtr FindChannelOnce(const string& target) override {
for (GrpcChannelCache* cache : caches_) {
SharedGrpcChannelPtr ch(cache->FindWorkerChannel(target));
if (ch) {
mutex_lock l(mu_);
target_caches_.insert({target, cache});
return ch;
}
}
return nullptr;
}
private:
const std::vector<GrpcChannelCache*> caches_;
mutex mu_;
std::unordered_map<string, GrpcChannelCache*> target_caches_
TF_GUARDED_BY(mu_);
};
class SparseGrpcChannelCache : public CachingGrpcChannelCache {
public:
SparseGrpcChannelCache(const string& job_id,
const std::map<int, string>& host_ports,
ChannelCreationFunction channel_func,
int num_channels_per_target)
: CachingGrpcChannelCache(num_channels_per_target),
job_id_(job_id),
host_ports_(host_ports),
channel_func_(std::move(channel_func)) {
VLOG(2) << "Initialize GrpcChannelCache for job " << ToString();
}
~SparseGrpcChannelCache() override {}
void ListWorkers(std::vector<string>* workers) override {
workers->reserve(workers->size() + host_ports_.size());
for (const auto& id_host_port : host_ports_) {
std::vector<std::string> replicas =
absl::StrSplit(id_host_port.second, ',', absl::SkipEmpty());
for (int replica = 0; replica < replicas.size(); ++replica) {
workers->emplace_back(
MakeAddress(job_id_, replica, id_host_port.first));
}
}
}
void ListWorkersInJob(const string& job_name,
std::vector<string>* workers) override {
if (job_name == job_id_) {
ListWorkers(workers);
}
}
string TranslateTask(const string& target) override {
DeviceNameUtils::ParsedName parsed;
if (!DeviceNameUtils::ParseFullName(target, &parsed)) {
LOG(WARNING) << "Invalid target: " << target;
return "";
}
if (!parsed.has_job || parsed.job != job_id_) {
return "";
}
int32_t task = parsed.has_task ? parsed.task : -1;
auto iter = host_ports_.find(task);
if (iter == host_ports_.end()) {
LOG(WARNING) << "Task " << task << " was not defined in sparse job "
<< job_id_ << ": " << target;
return "";
}
std::vector<std::string> host_ports =
absl::StrSplit(iter->second, ',', absl::SkipEmpty());
if (host_ports.size() > parsed.replica) {
return host_ports[parsed.replica];
}
LOG(WARNING) << "Requested out-of-range replica, defaulting to 0: "
<< target;
return host_ports[0];
}
protected:
SharedGrpcChannelPtr FindChannelOnce(const string& target) override {
const string host_port = TranslateTask(target);
if (host_port.empty()) {
return nullptr;
}
auto chan_ptr = channel_func_(host_port);
VLOG(5) << "Channel created for: job: " << job_id_
<< " host_port: " << host_port << " target : " << target
<< " Ptr: " << chan_ptr.get();
return chan_ptr;
}
private:
string ToString() {
std::vector<string> task_strings;
task_strings.reserve(host_ports_.size());
for (const auto& id_host_port : host_ports_) {
task_strings.emplace_back(
strings::StrCat(id_host_port.first, " -> ", id_host_port.second));
}
return strings::StrCat(job_id_, " -> {", absl::StrJoin(task_strings, ", "),
"}");
}
const string job_id_;
const std::map<int, string> host_ports_;
const ChannelCreationFunction channel_func_;
SparseGrpcChannelCache(const SparseGrpcChannelCache&) = delete;
void operator=(const SparseGrpcChannelCache&) = delete;
};
}
GrpcChannelCache* NewGrpcChannelCache(const GrpcChannelSpec& spec,
ChannelCreationFunction channel_func,
const RPCOptions& options) {
const int num_jobs = spec.host_ports_jobs().size();
if (!num_jobs) {
LOG(ERROR) << "Empty channel spec.";
return nullptr;
}
std::vector<GrpcChannelCache*> caches;
caches.reserve(num_jobs);
for (auto& job : spec.host_ports_jobs()) {
VLOG(2) << "Creating Grpc Channel Cache for: " << job.job_id;
caches.push_back(
new SparseGrpcChannelCache(job.job_id, job.host_ports, channel_func,
options.num_channels_per_target()));
}
return caches.size() == 1 ? caches[0]
: new MultiGrpcChannelCache(
caches, options.num_channels_per_target());
}
} | #include "xla/tsl/distributed_runtime/rpc/grpc_channel.h"
#include <string>
#include <vector>
#include "xla/tsl/util/device_name_utils.h"
#include "tsl/lib/core/status_test_util.h"
#include "tsl/platform/strcat.h"
#include "tsl/platform/test.h"
#include "tsl/protobuf/rpc_options.pb.h"
namespace tsl {
#define IsSameAddrSp DeviceNameUtils::IsSameAddressSpace
TEST(GrpcChannelTest, IsSameAddressSpace) {
EXPECT_TRUE(IsSameAddrSp("/job:mnist/replica:10/task:10/cpu:0",
"/job:mnist/replica:10/task:10/cpu:1"));
EXPECT_TRUE(IsSameAddrSp("/job:mnist/replica:10/task:10/cpu:0",
"/job:mnist/replica:10/task:10/device:GPU:2"));
EXPECT_TRUE(IsSameAddrSp("/job:mnist/replica:10/task:10",
"/job:mnist/replica:10/task:10/device:GPU:2"));
EXPECT_TRUE(IsSameAddrSp("/job:mnist/replica:10/task:10/cpu:1",
"/job:mnist/replica:10/task:10"));
EXPECT_FALSE(IsSameAddrSp("/job:mnist/replica:10/task:9/cpu:0",
"/job:mnist/replica:10/task:10/cpu:0"));
EXPECT_FALSE(IsSameAddrSp("/job:mnist/replica:9/task:10/cpu:0",
"/job:mnist/replica:10/task:10/cpu:0"));
EXPECT_FALSE(IsSameAddrSp("/job:MNIST/replica:10/task:10/cpu:0",
"/job:mnist/replica:10/task:10/cpu:0"));
EXPECT_FALSE(IsSameAddrSp("random_invalid_target", "random_invalid_target"));
EXPECT_FALSE(IsSameAddrSp("/job:/replica:10/task:10/cpu:0",
"/job:/replica:10/task:10/cpu:1"));
EXPECT_FALSE(IsSameAddrSp("/job:mnist/replica:xx/task:10/cpu:0",
"/job:mnist/replica:xx/task:10/cpu:1"));
EXPECT_FALSE(IsSameAddrSp("/job:mnist/replica:10/task:yy/cpu:0",
"/job:mnist/replica:10/task:yy/cpu:1"));
}
TEST(GrpcChannelTest, HostPorts) {
GrpcChannelSpec spec;
TF_ASSERT_OK(spec.AddHostPortsJob("mnist", {{0, "a:1"},
{1, "b:2"},
{2, "c:3"},
{3, "d:4"},
{4, "e:5"},
{5, "f:6"}}));
ChannelCreationFunction channel_func =
ConvertToChannelCreationFunction(NewHostPortGrpcChannel);
std::unique_ptr<GrpcChannelCache> cc(
NewGrpcChannelCache(spec, channel_func, tensorflow::RPCOptions()));
EXPECT_EQ(nullptr, cc->FindWorkerChannel("invalid_target"));
EXPECT_EQ(nullptr, cc->FindWorkerChannel("/job:other/replica:0/task:0"));
EXPECT_EQ(nullptr, cc->FindWorkerChannel("/job:mnist/replica:0/task:6"));
{
auto a_1_1 = cc->FindWorkerChannel("/job:mnist/replica:0/task:0");
auto a_1_2 = cc->FindWorkerChannel("/job:mnist/replica:0/task:0");
auto d_4_1 = cc->FindWorkerChannel("/job:mnist/replica:0/task:3");
auto d_4_2 = cc->FindWorkerChannel("/job:mnist/replica:0/task:3");
auto e_5_1 = cc->FindWorkerChannel("/job:mnist/replica:0/task:4");
auto e_5_2 = cc->FindWorkerChannel("/job:mnist/replica:0/task:4");
EXPECT_EQ(a_1_1.get(), a_1_2.get());
EXPECT_EQ(d_4_1.get(), d_4_2.get());
EXPECT_EQ(e_5_1.get(), e_5_2.get());
EXPECT_NE(a_1_1.get(), d_4_2.get());
EXPECT_NE(a_1_1.get(), e_5_2.get());
EXPECT_NE(d_4_1.get(), e_5_2.get());
}
{
std::vector<string> workers;
cc->ListWorkers(&workers);
EXPECT_EQ(
std::vector<string>(
{"/job:mnist/replica:0/task:0", "/job:mnist/replica:0/task:1",
"/job:mnist/replica:0/task:2", "/job:mnist/replica:0/task:3",
"/job:mnist/replica:0/task:4", "/job:mnist/replica:0/task:5"}),
workers);
}
{
std::vector<string> workers;
cc->ListWorkersInJob("mnist", &workers);
EXPECT_EQ(
std::vector<string>(
{"/job:mnist/replica:0/task:0", "/job:mnist/replica:0/task:1",
"/job:mnist/replica:0/task:2", "/job:mnist/replica:0/task:3",
"/job:mnist/replica:0/task:4", "/job:mnist/replica:0/task:5"}),
workers);
}
{
std::vector<string> workers;
cc->ListWorkersInJob("other", &workers);
EXPECT_TRUE(workers.empty());
}
}
TEST(GrpcChannelTest, HostPortsMultiChannelPerTarget) {
GrpcChannelSpec spec;
TF_EXPECT_OK(
spec.AddHostPortsJob("mnist", {{0, "a:1"}, {1, "b:2"}, {2, "c:3"}}));
ChannelCreationFunction channel_func =
ConvertToChannelCreationFunction(NewHostPortGrpcChannel);
tensorflow::RPCOptions rpc_options;
rpc_options.set_num_channels_per_target(4);
std::unique_ptr<GrpcChannelCache> cc(
NewGrpcChannelCache(spec, channel_func, rpc_options));
EXPECT_EQ(nullptr, cc->FindWorkerChannel("invalid_target"));
EXPECT_EQ(nullptr, cc->FindWorkerChannel("/job:other/replica:0/task:0"));
EXPECT_EQ(nullptr, cc->FindWorkerChannel("/job:mnist/replica:0/task:3"));
{
std::vector<SharedGrpcChannelPtr> a_1_channels, b_2_channels, c_3_channels;
for (int i = 0; i < 10; i++) {
a_1_channels.push_back(
cc->FindWorkerChannel("/job:mnist/replica:0/task:0"));
b_2_channels.push_back(
cc->FindWorkerChannel("/job:mnist/replica:0/task:1"));
c_3_channels.push_back(
cc->FindWorkerChannel("/job:mnist/replica:0/task:2"));
}
for (int i = 0; i < 6; i++) {
EXPECT_EQ(a_1_channels[i].get(), a_1_channels[i + 4].get());
EXPECT_EQ(b_2_channels[i].get(), b_2_channels[i + 4].get());
EXPECT_EQ(c_3_channels[i].get(), c_3_channels[i + 4].get());
}
for (int i = 0; i < 6; i++) {
for (int j = 1; j < 4; j++) {
EXPECT_NE(a_1_channels[i].get(), a_1_channels[i + j].get());
EXPECT_NE(b_2_channels[i].get(), b_2_channels[i + j].get());
EXPECT_NE(c_3_channels[i].get(), c_3_channels[i + j].get());
}
}
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 6; j++) {
EXPECT_NE(a_1_channels[i].get(), b_2_channels[j].get());
EXPECT_NE(a_1_channels[i].get(), c_3_channels[j].get());
EXPECT_NE(b_2_channels[i].get(), c_3_channels[j].get());
}
}
}
{
std::vector<string> workers;
cc->ListWorkers(&workers);
EXPECT_EQ(std::vector<string>({"/job:mnist/replica:0/task:0",
"/job:mnist/replica:0/task:1",
"/job:mnist/replica:0/task:2"}),
workers);
}
{
std::vector<string> workers;
cc->ListWorkersInJob("mnist", &workers);
EXPECT_EQ(std::vector<string>({"/job:mnist/replica:0/task:0",
"/job:mnist/replica:0/task:1",
"/job:mnist/replica:0/task:2"}),
workers);
}
{
std::vector<string> workers;
cc->ListWorkersInJob("other", &workers);
EXPECT_TRUE(workers.empty());
}
}
TEST(GrpcChannelTest, HostPortsMultiGrpcMultiChannelPerTarget) {
GrpcChannelSpec spec;
TF_EXPECT_OK(
spec.AddHostPortsJob("mnist", {{0, "a:1"}, {1, "b:2"}, {2, "c:3"}}));
TF_EXPECT_OK(
spec.AddHostPortsJob("mnist2", {{0, "a:1"}, {1, "b:2"}, {2, "c:3"}}));
ChannelCreationFunction channel_func =
ConvertToChannelCreationFunction(NewHostPortGrpcChannel);
tensorflow::RPCOptions rpc_options;
rpc_options.set_num_channels_per_target(4);
std::unique_ptr<GrpcChannelCache> cc(
NewGrpcChannelCache(spec, channel_func, rpc_options));
EXPECT_EQ(nullptr, cc->FindWorkerChannel("invalid_target"));
EXPECT_EQ(nullptr, cc->FindWorkerChannel("/job:other/replica:0/task:0"));
EXPECT_EQ(nullptr, cc->FindWorkerChannel("/job:mnist/replica:0/task:3"));
EXPECT_NE(nullptr, cc->FindWorkerChannel("/job:mnist2/replica:0/task:0"));
{
std::vector<SharedGrpcChannelPtr> a_1_channels, b_2_channels, c_3_channels;
for (int i = 0; i < 10; i++) {
a_1_channels.push_back(
cc->FindWorkerChannel("/job:mnist/replica:0/task:0"));
b_2_channels.push_back(
cc->FindWorkerChannel("/job:mnist/replica:0/task:1"));
c_3_channels.push_back(
cc->FindWorkerChannel("/job:mnist2/replica:0/task:0"));
}
for (int i = 0; i < 6; i++) {
EXPECT_EQ(a_1_channels[i].get(), a_1_channels[i + 4].get());
EXPECT_EQ(b_2_channels[i].get(), b_2_channels[i + 4].get());
EXPECT_EQ(c_3_channels[i].get(), c_3_channels[i + 4].get());
}
for (int i = 0; i < 6; i++) {
for (int j = 1; j < 4; j++) {
EXPECT_NE(a_1_channels[i].get(), a_1_channels[i + j].get());
EXPECT_NE(b_2_channels[i].get(), b_2_channels[i + j].get());
EXPECT_NE(c_3_channels[i].get(), c_3_channels[i + j].get());
}
}
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 6; j++) {
EXPECT_NE(a_1_channels[i].get(), b_2_channels[j].get());
EXPECT_NE(a_1_channels[i].get(), c_3_channels[j].get());
EXPECT_NE(b_2_channels[i].get(), c_3_channels[j].get());
}
}
}
{
std::vector<string> workers;
cc->ListWorkers(&workers);
EXPECT_EQ(
std::vector<string>(
{"/job:mnist/replica:0/task:0", "/job:mnist/replica:0/task:1",
"/job:mnist/replica:0/task:2", "/job:mnist2/replica:0/task:0",
"/job:mnist2/replica:0/task:1", "/job:mnist2/replica:0/task:2"}),
workers);
}
{
std::vector<string> workers, workers2;
cc->ListWorkersInJob("mnist", &workers);
EXPECT_EQ(std::vector<string>({"/job:mnist/replica:0/task:0",
"/job:mnist/replica:0/task:1",
"/job:mnist/replica:0/task:2"}),
workers);
cc->ListWorkersInJob("mnist2", &workers2);
EXPECT_EQ(std::vector<string>({"/job:mnist2/replica:0/task:0",
"/job:mnist2/replica:0/task:1",
"/job:mnist2/replica:0/task:2"}),
workers2);
}
{
std::vector<string> workers;
cc->ListWorkersInJob("other", &workers);
EXPECT_TRUE(workers.empty());
}
}
TEST(GrpcChannelTest, SparseHostPorts) {
GrpcChannelSpec spec;
TF_EXPECT_OK(
spec.AddHostPortsJob("mnist", {{0, "a:1"}, {3, "d:4"}, {4, "e:5"}}));
ChannelCreationFunction channel_func =
ConvertToChannelCreationFunction(NewHostPortGrpcChannel);
std::unique_ptr<GrpcChannelCache> cc(
NewGrpcChannelCache(spec, channel_func, tensorflow::RPCOptions()));
EXPECT_EQ(nullptr, cc->FindWorkerChannel("invalid_target"));
EXPECT_EQ(nullptr, cc->FindWorkerChannel("/job:other/replica:0/task:0"));
EXPECT_EQ(nullptr, cc->FindWorkerChannel("/job:mnist/replica:0/task:1"));
EXPECT_EQ(nullptr, cc->FindWorkerChannel("/job:mnist/replica:0/task:2"));
EXPECT_EQ(nullptr, cc->FindWorkerChannel("/job:mnist/replica:0/task:5"));
{
auto a_1_1 = cc->FindWorkerChannel("/job:mnist/replica:0/task:0");
auto a_1_2 = cc->FindWorkerChannel("/job:mnist/replica:0/task:0");
LOG(WARNING) << " Getting task 3";
auto d_4_1 = cc->FindWorkerChannel("/job:mnist/replica:0/task:3");
auto d_4_2 = cc->FindWorkerChannel("/job:mnist/replica:0/task:3");
LOG(WARNING) << " Getting task 4";
auto e_5_1 = cc->FindWorkerChannel("/job:mnist/replica:0/task:4");
auto e_5_2 = cc->FindWorkerChannel("/job:mnist/replica:0/task:4");
EXPECT_EQ(a_1_1.get(), a_1_2.get());
EXPECT_EQ(d_4_1.get(), d_4_2.get());
EXPECT_EQ(e_5_1.get(), e_5_2.get());
EXPECT_NE(a_1_1.get(), d_4_2.get());
EXPECT_NE(a_1_1.get(), e_5_2.get());
EXPECT_NE(d_4_1.get(), e_5_2.get());
}
{
std::vector<string> workers;
cc->ListWorkers(&workers);
std::sort(workers.begin(), workers.end());
EXPECT_EQ(std::vector<string>({"/job:mnist/replica:0/task:0",
"/job:mnist/replica:0/task:3",
"/job:mnist/replica:0/task:4"}),
workers);
}
{
std::vector<string> workers;
cc->ListWorkersInJob("mnist", &workers);
EXPECT_EQ(std::vector<string>({"/job:mnist/replica:0/task:0",
"/job:mnist/replica:0/task:3",
"/job:mnist/replica:0/task:4"}),
workers);
}
{
std::vector<string> workers;
cc->ListWorkersInJob("other", &workers);
EXPECT_TRUE(workers.empty());
}
}
TEST(GrpcChannelTest, NewHostPortGrpcChannelValidation) {
SharedGrpcChannelPtr mock_ptr;
EXPECT_TRUE(NewHostPortGrpcChannel("127.0.0.1:2222", nullptr,
&mock_ptr)
.ok());
EXPECT_TRUE(NewHostPortGrpcChannel("example.com:2222",
nullptr, &mock_ptr)
.ok());
EXPECT_TRUE(NewHostPortGrpcChannel("fqdn.example.com.:2222",
nullptr, &mock_ptr)
.ok());
EXPECT_TRUE(NewHostPortGrpcChannel("[2002:a9c:258e::]:2222",
nullptr, &mock_ptr)
.ok());
EXPECT_TRUE(
NewHostPortGrpcChannel("[::]:2222", nullptr, &mock_ptr)
.ok());
EXPECT_FALSE(NewHostPortGrpcChannel("example.com/abc:2222",
nullptr, &mock_ptr)
.ok());
EXPECT_FALSE(NewHostPortGrpcChannel("127.0.0.1:2222/",
nullptr, &mock_ptr)
.ok());
EXPECT_FALSE(NewHostPortGrpcChannel(
"example.com/abc:", nullptr, &mock_ptr)
.ok());
EXPECT_FALSE(
NewHostPortGrpcChannel("[::]/:2222", nullptr, &mock_ptr)
.ok());
EXPECT_FALSE(
NewHostPortGrpcChannel("[::]:2222/", nullptr, &mock_ptr)
.ok());
EXPECT_FALSE(
NewHostPortGrpcChannel("[::]:", nullptr, &mock_ptr).ok());
EXPECT_TRUE(
NewHostPortGrpcChannel("/bns/example", nullptr, &mock_ptr)
.ok());
}
} | 2,237 |
#ifndef XLA_TSL_DISTRIBUTED_RUNTIME_COORDINATION_COORDINATION_SERVICE_AGENT_H_
#define XLA_TSL_DISTRIBUTED_RUNTIME_COORDINATION_COORDINATION_SERVICE_AGENT_H_
#include <functional>
#include <map>
#include <memory>
#include <string>
#include <string_view>
#include <vector>
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/time/time.h"
#include "xla/tsl/distributed_runtime/call_options.h"
#include "xla/tsl/distributed_runtime/coordination/coordination_client.h"
#include "tsl/platform/status.h"
#include "tsl/protobuf/coordination_service.pb.h"
namespace tensorflow {
class CoordinationServiceConfig;
};
namespace tsl {
class Env;
class CoordinationServiceAgent {
public:
using StatusOrValueCallback =
std::function<void(const absl::StatusOr<std::string>&)>;
using StatusOrValueDirCallback = std::function<void(
const absl::StatusOr<std::vector<tensorflow::KeyValueEntry>>&)>;
using ChangedKeyValuesCallback =
std::function<void(const std::map<std::string, std::string>&)>;
virtual ~CoordinationServiceAgent() = default;
virtual absl::Status Initialize(
tsl::Env* env, std::string_view job_name, int task_id,
const tensorflow::CoordinationServiceConfig& configs,
std::unique_ptr<CoordinationClient> leader_client,
StatusCallback error_fn) = 0;
virtual absl::Status Initialize(
tsl::Env* env, const tensorflow::CoordinatedTask& task,
const tensorflow::CoordinationServiceConfig& configs,
std::unique_ptr<CoordinationClient> leader_client,
StatusCallback error_fn) = 0;
virtual bool IsInitialized() = 0;
virtual bool IsConnected() = 0;
virtual bool IsError() = 0;
virtual absl::Status Connect() = 0;
virtual absl::Status WaitForAllTasks(
const tensorflow::DeviceInfo& local_devices) = 0;
virtual const tensorflow::DeviceInfo& GetClusterDeviceInfo() = 0;
virtual absl::StatusOr<tensorflow::CoordinatedTask> GetOwnTask() = 0;
virtual absl::StatusOr<std::vector<tensorflow::CoordinatedTaskStateInfo>>
GetTaskState(const std::vector<tensorflow::CoordinatedTask>& task) = 0;
virtual absl::Status ReportError(const absl::Status& error) = 0;
virtual absl::Status Shutdown() = 0;
virtual absl::Status Reset() = 0;
virtual absl::StatusOr<std::string> GetKeyValue(std::string_view key) = 0;
virtual absl::StatusOr<std::string> GetKeyValue(std::string_view key,
absl::Duration timeout) = 0;
virtual std::shared_ptr<CallOptions> GetKeyValueAsync(
std::string_view, StatusOrValueCallback done) = 0;
virtual absl::StatusOr<std::string> TryGetKeyValue(std::string_view key) = 0;
virtual absl::StatusOr<std::vector<tensorflow::KeyValueEntry>> GetKeyValueDir(
std::string_view key) = 0;
virtual void GetKeyValueDirAsync(std::string_view key,
StatusOrValueDirCallback done) = 0;
virtual absl::Status InsertKeyValue(std::string_view key,
std::string_view value) = 0;
virtual absl::Status InsertKeyValue(std::string_view key,
std::string_view value,
bool allow_overwrite) = 0;
virtual absl::Status DeleteKeyValue(std::string_view key) = 0;
virtual absl::Status UpdateKeyValue(std::string_view key,
std::string_view value) = 0;
virtual absl::Status StartWatchKey(std::string_view key,
ChangedKeyValuesCallback on_change) = 0;
virtual absl::Status StopWatchKey(std::string_view key) = 0;
virtual absl::Status WaitAtBarrier(
std::string_view barrier_id, absl::Duration timeout,
const std::vector<tensorflow::CoordinatedTask>& tasks) = 0;
virtual void WaitAtBarrierAsync(
std::string_view barrier_id, absl::Duration timeout,
const std::vector<tensorflow::CoordinatedTask>& tasks,
StatusCallback done) = 0;
virtual absl::Status CancelBarrier(std::string_view barrier_id) = 0;
virtual void CancelBarrierAsync(std::string_view barrier_id,
StatusCallback done) = 0;
virtual absl::StatusOr<tsl::Env*> GetEnv() = 0;
protected:
virtual void SetError(const absl::Status& error) = 0;
virtual absl::Status ActivateWatch(
std::string_view, const std::map<std::string, std::string>&) = 0;
private:
friend class CoordinationServiceRpcHandler;
};
std::unique_ptr<CoordinationServiceAgent> CreateCoordinationServiceAgent();
}
#endif
#include "xla/tsl/distributed_runtime/coordination/coordination_service_agent.h"
#include <algorithm>
#include <cassert>
#include <cstdint>
#include <iterator>
#include <map>
#include <memory>
#include <optional>
#include <random>
#include <string>
#include <string_view>
#include <utility>
#include <vector>
#include "absl/container/flat_hash_set.h"
#include "absl/log/log.h"
#include "absl/status/status.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/substitute.h"
#include "absl/synchronization/mutex.h"
#include "absl/synchronization/notification.h"
#include "absl/time/clock.h"
#include "absl/time/time.h"
#include "xla/tsl/distributed_runtime/call_options.h"
#include "xla/tsl/distributed_runtime/coordination/coordination_client.h"
#include "xla/tsl/distributed_runtime/coordination/coordination_service_error_util.h"
#include "xla/tsl/framework/cancellation.h"
#include "tsl/lib/monitoring/gauge.h"
#include "tsl/platform/env.h"
#include "tsl/platform/random.h"
#include "tsl/platform/status.h"
#include "tsl/platform/thread_annotations.h"
#include "tsl/protobuf/coordination_config.pb.h"
#include "tsl/protobuf/coordination_service.pb.h"
namespace tsl {
using tensorflow::CoordinatedTask;
using tensorflow::CoordinatedTaskState;
using tensorflow::CoordinatedTaskStateInfo;
using tensorflow::CoordinationServiceConfig;
using tensorflow::DeviceInfo;
using tensorflow::KeyValueEntry;
namespace {
auto* enabled_usage_metric =
monitoring::Gauge<bool, 0>::New("/coordination_service/agent/enabled",
"Tracks usage of coordination service.");
constexpr absl::Duration kDefaultClusterRegisterTimeout = absl::Hours(1);
constexpr absl::Duration kDefaultHeartbeatTimeout = absl::Seconds(10);
constexpr absl::Duration kDefaultShutdownTimeout = absl::Seconds(10);
constexpr char kHeartbeatThread[] = "CoordinationServiceHeartbeatLoop";
class CoordinationServiceAgentImpl : public CoordinationServiceAgent {
public:
CoordinationServiceAgentImpl() = default;
~CoordinationServiceAgentImpl() override {
absl::Status s = ShutdownInternal();
VLOG(3) << "Coordination agent dtor failed with status: " << s;
}
absl::Status Initialize(Env* env, std::string_view job_name, int task_id,
const CoordinationServiceConfig& configs,
std::unique_ptr<CoordinationClient> leader_client,
StatusCallback error_fn) override;
absl::Status Initialize(Env* env, const CoordinatedTask& task,
const CoordinationServiceConfig& configs,
std::unique_ptr<CoordinationClient> leader_client,
StatusCallback error_fn) override;
bool IsInitialized() override;
bool IsConnected() override;
bool IsError() override;
absl::Status Connect() override;
absl::Status WaitForAllTasks(const DeviceInfo& local_devices) override;
const DeviceInfo& GetClusterDeviceInfo() override;
absl::StatusOr<CoordinatedTask> GetOwnTask() override;
absl::StatusOr<std::vector<CoordinatedTaskStateInfo>> GetTaskState(
const std::vector<CoordinatedTask>& task) override;
absl::Status ReportError(const absl::Status& error) override;
absl::Status Shutdown() override;
absl::Status Reset() override;
absl::StatusOr<std::string> GetKeyValue(std::string_view key) override;
absl::StatusOr<std::string> GetKeyValue(std::string_view key,
absl::Duration timeout) override;
std::shared_ptr<CallOptions> GetKeyValueAsync(
std::string_view key, StatusOrValueCallback done) override;
absl::StatusOr<std::string> TryGetKeyValue(std::string_view key) override;
absl::StatusOr<std::vector<KeyValueEntry>> GetKeyValueDir(
std::string_view key) override;
void GetKeyValueDirAsync(std::string_view key,
StatusOrValueDirCallback done) override;
absl::Status InsertKeyValue(std::string_view key,
std::string_view value) override;
absl::Status InsertKeyValue(std::string_view key, std::string_view value,
bool allow_overwrite) override;
absl::Status DeleteKeyValue(std::string_view key) override;
absl::Status UpdateKeyValue(std::string_view key,
std::string_view value) override;
absl::Status StartWatchKey(std::string_view key,
ChangedKeyValuesCallback on_change) override;
absl::Status StopWatchKey(std::string_view key) override;
absl::Status WaitAtBarrier(
std::string_view barrier_id, absl::Duration timeout,
const std::vector<CoordinatedTask>& tasks) override;
void WaitAtBarrierAsync(std::string_view barrier_id, absl::Duration timeout,
const std::vector<CoordinatedTask>& tasks,
StatusCallback done) override;
absl::Status CancelBarrier(std::string_view barrier_id) override;
void CancelBarrierAsync(std::string_view barrier_id,
StatusCallback done) override;
absl::StatusOr<Env*> GetEnv() override;
protected:
void SetError(const absl::Status& error) override;
absl::Status ActivateWatch(
std::string_view key, const std::map<std::string, std::string>&) override;
absl::Status ValidateRunningAgent(bool allow_disconnected = false);
void StopHeartbeat();
private:
absl::Status ShutdownInternal();
Env* env_ = nullptr;
const uint64_t incarnation_id_ = random::New64();
CoordinatedTask task_;
CoordinationServiceConfig configs_;
StatusCallback error_fn_;
mutable absl::Mutex state_mu_;
CoordinatedTaskState state_ TF_GUARDED_BY(state_mu_) =
CoordinatedTaskState::TASKSTATE_UNINITIALIZED;
absl::Status status_ TF_GUARDED_BY(state_mu_) = absl::OkStatus();
absl::flat_hash_set<std::string> used_barrier_ids_ TF_GUARDED_BY(state_mu_);
uint64_t leader_incarnation_ = 0;
DeviceInfo cluster_devices_;
absl::Mutex heartbeat_thread_shutdown_mu_;
absl::CondVar heartbeat_thread_cv_;
bool shutting_down_ TF_GUARDED_BY(heartbeat_thread_shutdown_mu_) = false;
std::unique_ptr<Thread> heartbeat_thread_;
CancellationManager cancellation_manager_;
std::unique_ptr<CoordinationClient> leader_client_;
CoordinationServiceAgentImpl(const CoordinationServiceAgentImpl&) = delete;
void operator=(const CoordinationServiceAgentImpl&) = delete;
};
absl::Status CoordinationServiceAgentImpl::Initialize(
Env* env, std::string_view job_name, int task_id,
const CoordinationServiceConfig& configs,
std::unique_ptr<CoordinationClient> leader_client,
StatusCallback error_fn) {
CoordinatedTask task;
task.set_job_name(std::string(job_name));
task.set_task_id(task_id);
return Initialize(env, task, configs, std::move(leader_client), error_fn);
}
absl::Status CoordinationServiceAgentImpl::Initialize(
Env* env, const CoordinatedTask& task,
const CoordinationServiceConfig& configs,
std::unique_ptr<CoordinationClient> leader_client,
StatusCallback error_fn) {
enabled_usage_metric->GetCell()->Set(true);
absl::MutexLock l(&state_mu_);
if (state_ != CoordinatedTaskState::TASKSTATE_UNINITIALIZED) {
return MakeCoordinationError(absl::FailedPreconditionError(
"Coordination service agent has already been initialized."));
}
env_ = env;
task_ = task;
configs_ = configs;
if (configs_.service_leader().empty()) {
return MakeCoordinationError(absl::InvalidArgumentError(
"CoordinationServiceAgent must be initialized with a valid leader."));
}
leader_client_ = std::move(leader_client);
if (leader_client_ == nullptr) {
return MakeCoordinationError(absl::InvalidArgumentError(
"CoordinationServiceAgent must have a valid leader client."));
}
error_fn_ = error_fn;
state_ = CoordinatedTaskState::TASKSTATE_DISCONNECTED;
return absl::OkStatus();
}
bool CoordinationServiceAgentImpl::IsInitialized() {
absl::MutexLock l(&state_mu_);
return state_ != CoordinatedTaskState::TASKSTATE_UNINITIALIZED;
}
bool CoordinationServiceAgentImpl::IsConnected() {
absl::MutexLock l(&state_mu_);
return state_ == CoordinatedTaskState::TASKSTATE_CONNECTED;
}
bool CoordinationServiceAgentImpl::IsError() {
absl::MutexLock l(&state_mu_);
return state_ == CoordinatedTaskState::TASKSTATE_ERROR;
}
void CoordinationServiceAgentImpl::StopHeartbeat() {
{
absl::MutexLock l(&heartbeat_thread_shutdown_mu_);
shutting_down_ = true;
heartbeat_thread_cv_.SignalAll();
}
heartbeat_thread_ = nullptr;
}
absl::Status CoordinationServiceAgentImpl::Connect() {
VLOG(3) << "Agent has started trying to Connect().";
{
absl::MutexLock l(&state_mu_);
if (state_ != CoordinatedTaskState::TASKSTATE_DISCONNECTED) {
return MakeCoordinationError(absl::FailedPreconditionError(
"Coordination service agent is not in DISCONNECTED state."));
}
}
absl::Status connect_status =
absl::UnknownError("Connection not attempted yet.");
RegisterTaskRequest request;
*request.mutable_source_task() = task_;
request.set_incarnation(incarnation_id_);
RegisterTaskResponse response;
const int64_t register_timeout =
configs_.cluster_register_timeout_in_ms() > 0
? configs_.cluster_register_timeout_in_ms()
: absl::ToInt64Milliseconds(kDefaultClusterRegisterTimeout);
const absl::Time deadline =
absl::Now() + absl::Milliseconds(register_timeout);
int attempt = 0;
std::default_random_engine generator;
std::uniform_real_distribution<double> distribution(0.0, 1.0);
do {
++attempt;
CallOptions call_opts;
call_opts.SetTimeout(absl::ToInt64Milliseconds(deadline - absl::Now()));
absl::Notification n;
leader_client_->RegisterTaskAsync(
&call_opts, &request, &response, [&](absl::Status s) {
if (s.ok()) {
leader_incarnation_ = response.leader_incarnation();
{
absl::MutexLock l(&state_mu_);
state_ = CoordinatedTaskState::TASKSTATE_CONNECTED;
}
}
connect_status = s;
n.Notify();
});
n.WaitForNotification();
if (!connect_status.ok()) {
const int backoff = 1 << std::min(14, attempt);
absl::SleepFor(absl::Milliseconds(backoff * distribution(generator)));
}
} while (!connect_status.ok() && absl::Now() < deadline &&
(connect_status.GetPayload(CoordinationErrorPayloadKey()) ==
std::nullopt ||
absl::IsAborted(connect_status) ||
absl::IsInternal(connect_status)));
if (!connect_status.ok()) {
SetError(connect_status);
return connect_status;
}
LOG(INFO) << "Coordination agent has successfully connected.";
heartbeat_thread_.reset(
env_->StartThread(ThreadOptions(), kHeartbeatThread, [this]() -> void {
HeartbeatRequest request;
*request.mutable_source_task() = task_;
request.set_incarnation(incarnation_id_);
HeartbeatResponse response;
const int64_t heartbeat_interval_ms =
configs_.heartbeat_timeout_in_ms() > 0
? configs_.heartbeat_timeout_in_ms() / 2
: absl::ToInt64Milliseconds(kDefaultHeartbeatTimeout) / 2;
CallOptions call_opts;
call_opts.SetTimeout(heartbeat_interval_ms);
while (true) {
absl::Status status;
absl::Notification n;
VLOG(10) << "HeartbeatRequest: " << request.DebugString();
leader_client_->HeartbeatAsync(&call_opts, &request, &response,
[&](absl::Status s) {
status = s;
n.Notify();
});
n.WaitForNotification();
VLOG(10) << "HeartbeatResponse: " << status;
if (!status.ok()) {
absl::SleepFor(absl::Seconds(1));
{
absl::MutexLock l(&heartbeat_thread_shutdown_mu_);
if (shutting_down_) {
return;
}
}
SetError(status);
} else if (response.leader_incarnation() != leader_incarnation_) {
SetError(MakeCoordinationError(
absl::AbortedError("Leader incarnation ID mismatch: the "
"coordination leader has restarted.")));
}
{
absl::MutexLock l(&heartbeat_thread_shutdown_mu_);
heartbeat_thread_cv_.WaitWithTimeout(
&heartbeat_thread_shutdown_mu_,
absl::Milliseconds(heartbeat_interval_ms));
if (shutting_down_) {
return;
}
}
}
}));
return absl::OkStatus();
}
absl::Status CoordinationServiceAgentImpl::WaitForAllTasks(
const DeviceInfo& local_devices) {
absl::Status agent_running_status = ValidateRunningAgent();
if (!agent_running_status.ok()) {
return agent_running_status;
}
WaitForAllTasksRequest request;
*request.mutable_source_task() = task_;
*request.mutable_device_info() = local_devices;
VLOG(3) << "WaitForAllTasksRequest: " << request.DebugString();
WaitForAllTasksResponse response;
absl::Status status;
absl::Notification n;
leader_client_->WaitForAllTasksAsync(&request, &response,
[&](absl::Status s) {
status = s;
n.Notify();
});
n.WaitForNotification();
if (!status.ok()) {
VLOG(3) << "WaitForAllTasksResponse: " << status;
SetError(status);
return status;
}
VLOG(3) << "WaitForAllTasksResponse: " << response.DebugString();
cluster_devices_ = response.device_info();
return absl::OkStatus();
}
const DeviceInfo& CoordinationServiceAgentImpl::GetClusterDeviceInfo() {
return cluster_devices_;
}
absl::StatusOr<CoordinatedTask> CoordinationServiceAgentImpl::GetOwnTask() {
if (!IsInitialized()) {
return MakeCoordinationError(absl::FailedPreconditionError(
"Agent has not been initialized; we do not "
"know the associated task yet."));
}
return task_;
}
absl::StatusOr<std::vector<CoordinatedTaskStateInfo>>
CoordinationServiceAgentImpl::GetTaskState(
const std::vector<CoordinatedTask>& tasks) {
GetTaskStateRequest request;
*request.mutable_source_task() = {tasks.begin(), tasks.end()};
GetTaskStateResponse response;
absl::Notification n;
absl::StatusOr<std::vector<CoordinatedTaskStateInfo>> result;
leader_client_->GetTaskStateAsync(
&request, &response, [&](const absl::Status& s) {
if (s.ok()) {
result = std::vector<CoordinatedTaskStateInfo>(
std::make_move_iterator(response.task_state().begin()),
std::make_move_iterator(response.task_state().end()));
} else {
result = s;
}
n.Notify();
});
n.WaitForNotification();
return result;
}
absl::Status CoordinationServiceAgentImpl::ReportError(
const absl::Status& error) {
{
absl::MutexLock l(&state_mu_);
if (state_ == CoordinatedTaskState::TASKSTATE_UNINITIALIZED) {
return MakeCoordinationError(absl::FailedPreconditionError(
"Coordination service agent must be initialized first before "
"reporting error."));
} else if (state_ == CoordinatedTaskState::TASKSTATE_ERROR) {
return MakeCoordinationError(absl::FailedPreconditionError(
"Coordination service agent is already in error state."));
}
}
SetError(MakeCoordinationError(error, task_,
true));
LOG(INFO) << "Reporting error to coordination service: " << error;
ReportErrorToServiceRequest request;
request.set_error_code(error.raw_code());
request.set_error_message(std::string(error.message()));
*request.mutable_error_origin() = task_;
VLOG(5) << "ReportErrorToServiceRequest: " << request.DebugString();
ReportErrorToServiceResponse response;
absl::Notification n;
leader_client_->ReportErrorToServiceAsync(
&request, &response, [&](absl::Status s) {
VLOG(5) << "ReportErrorToServiceResponse: " << s;
if (!s.ok()) {
LOG(ERROR)
<< "Encountered another error when reporting error to "
"coordination service: "
<< s
<< "\nThis is usually caused by an earlier error during "
"execution. Check the logs (this task or the leader) for "
"an earlier error to debug further.";
}
n.Notify();
});
n.WaitForNotification();
return absl::OkStatus();
}
absl::Status CoordinationServiceAgentImpl::Shutdown() {
return | #include "xla/tsl/distributed_runtime/coordination/coordination_service_agent.h"
#include <memory>
#include <ostream>
#include <string>
#include <utility>
#include <vector>
#include "absl/log/check.h"
#include "absl/log/log.h"
#include "absl/memory/memory.h"
#include "absl/status/status.h"
#include "absl/time/clock.h"
#include "absl/time/time.h"
#include "xla/tsl/distributed_runtime/call_options.h"
#include "xla/tsl/distributed_runtime/coordination/coordination_client.h"
#include "tsl/lib/core/status_test_util.h"
#include "tsl/platform/env.h"
#include "tsl/platform/status.h"
#include "tsl/platform/test.h"
#include "tsl/protobuf/coordination_config.pb.h"
#include "tsl/protobuf/coordination_service.pb.h"
namespace tsl {
namespace {
using tensorflow::CoordinatedTask;
using tensorflow::CoordinationServiceConfig;
using tensorflow::KeyValueEntry;
using ::testing::_;
using ::testing::DoAll;
using ::testing::InvokeArgument;
using ::testing::SetArgPointee;
using ::testing::UnorderedPointwise;
using ::testing::WithArgs;
class ProtoStringMatcher {
public:
explicit ProtoStringMatcher(const tsl::protobuf::Message& expected)
: expected_(expected.DebugString()) {}
template <typename Message>
bool MatchAndExplain(const Message& p,
::testing::MatchResultListener*) const {
return p.DebugString() == expected_;
}
void DescribeTo(std::ostream* os) const { *os << expected_; }
void DescribeNegationTo(std::ostream* os) const {
*os << "not equal to expected message: " << expected_;
}
private:
const std::string expected_;
};
MATCHER(KvEq, "simple KeyValueEntry matcher") {
const KeyValueEntry& kv0 = std::get<0>(arg);
const KeyValueEntry& kv1 = std::get<1>(arg);
return kv0.key() == kv1.key() && kv0.value() == kv1.value();
}
KeyValueEntry CreateKv(const std::string& key, const std::string& value) {
KeyValueEntry kv;
kv.set_key(key);
kv.set_value(value);
return kv;
}
class TestCoordinationClient : public CoordinationClient {
public:
TestCoordinationClient() = default;
MOCK_METHOD(void, GetKeyValueAsync,
(CallOptions * call_opts, const GetKeyValueRequest*,
GetKeyValueResponse*, StatusCallback),
(override));
MOCK_METHOD(void, TryGetKeyValueAsync,
(const TryGetKeyValueRequest*, TryGetKeyValueResponse*,
StatusCallback),
(override));
MOCK_METHOD(void, GetKeyValueDirAsync,
(const GetKeyValueDirRequest*, GetKeyValueDirResponse*,
StatusCallback),
(override));
MOCK_METHOD(void, InsertKeyValueAsync,
(const InsertKeyValueRequest*, InsertKeyValueResponse*,
StatusCallback),
(override));
MOCK_METHOD(void, DeleteKeyValueAsync,
(const DeleteKeyValueRequest*, DeleteKeyValueResponse*,
StatusCallback),
(override));
MOCK_METHOD(void, RegisterTaskAsync,
(CallOptions*, const RegisterTaskRequest*, RegisterTaskResponse*,
StatusCallback),
(override));
MOCK_METHOD(void, ShutdownTaskAsync,
(CallOptions*, const ShutdownTaskRequest*, ShutdownTaskResponse*,
StatusCallback),
(override));
MOCK_METHOD(void, ResetTaskAsync,
(const ResetTaskRequest*, ResetTaskResponse*, StatusCallback),
(override));
MOCK_METHOD(void, ReportErrorToServiceAsync,
(const ReportErrorToServiceRequest*,
ReportErrorToServiceResponse*, StatusCallback),
(override));
MOCK_METHOD(void, BarrierAsync,
(const BarrierRequest*, BarrierResponse*, StatusCallback),
(override));
MOCK_METHOD(void, GetTaskStateAsync,
(const GetTaskStateRequest*, GetTaskStateResponse*,
StatusCallback),
(override));
MOCK_METHOD(void, HeartbeatAsync,
(CallOptions*, const HeartbeatRequest*, HeartbeatResponse*,
StatusCallback),
(override));
#define UNIMPLEMENTED(method) \
void method##Async(const method##Request* request, \
method##Response* response, StatusCallback done) \
override { \
done(absl::UnimplementedError(#method "Async")); \
}
UNIMPLEMENTED(WaitForAllTasks);
UNIMPLEMENTED(CancelBarrier);
#undef UNIMPLEMENTED
void ReportErrorToTaskAsync(CallOptions* call_opts,
const ReportErrorToTaskRequest* request,
ReportErrorToTaskResponse* response,
StatusCallback done) override {
done(absl::UnimplementedError("ReportErrorToTaskAsync"));
}
};
class CoordinationServiceAgentTest : public ::testing::Test {
public:
void SetUp() override {
ON_CALL(*client_, RegisterTaskAsync(_, _, _, _))
.WillByDefault(InvokeArgument<3>(absl::OkStatus()));
ON_CALL(*client_, HeartbeatAsync(_, _, _, _))
.WillByDefault(InvokeArgument<3>(absl::OkStatus()));
ON_CALL(*client_, ShutdownTaskAsync(_, _, _, _))
.WillByDefault(InvokeArgument<3>(absl::OkStatus()));
ON_CALL(*client_, ReportErrorToServiceAsync(_, _, _))
.WillByDefault(InvokeArgument<2>(absl::OkStatus()));
ON_CALL(*client_, ResetTaskAsync(_, _, _))
.WillByDefault(InvokeArgument<2>(absl::OkStatus()));
ON_CALL(*client_, BarrierAsync(_, _, _))
.WillByDefault(InvokeArgument<2>(absl::OkStatus()));
ON_CALL(*client_, GetTaskStateAsync(_, _, _))
.WillByDefault(InvokeArgument<2>(absl::OkStatus()));
}
void InitializeAgent(CoordinationServiceConfig config = {}) {
config.set_service_leader("test_leader");
TF_ASSERT_OK(agent_->Initialize(
Env::Default(), "test_job",
0, config, std::move(client_),
[](absl::Status s) {
LOG(ERROR) << "Coordination agent is set to error: " << s;
}));
}
TestCoordinationClient* GetClient() {
CHECK(client_ != nullptr)
<< "GetClient() was called after InitializeAgent()";
return client_.get();
}
protected:
std::unique_ptr<CoordinationServiceAgent> agent_ =
CreateCoordinationServiceAgent();
std::unique_ptr<TestCoordinationClient> client_ =
std::make_unique<TestCoordinationClient>();
};
TEST_F(CoordinationServiceAgentTest, GetKeyValue_Simple_Success) {
const std::string& test_key = "test_key";
const std::string& test_value = "test_value";
GetKeyValueResponse mocked_response;
auto kv = mocked_response.mutable_kv();
kv->set_key(test_key);
kv->set_value(test_value);
ON_CALL(*GetClient(), GetKeyValueAsync(_, _, _, _))
.WillByDefault(DoAll(SetArgPointee<2>(mocked_response),
InvokeArgument<3>(absl::OkStatus())));
InitializeAgent();
auto result = agent_->GetKeyValue(test_key);
TF_ASSERT_OK(result.status());
EXPECT_EQ(*result, test_value);
}
TEST_F(CoordinationServiceAgentTest, GetKeyValue_WithTimeout_Success) {
const std::string& test_key = "test_key";
const std::string& test_value = "test_value";
GetKeyValueResponse mocked_response;
auto kv = mocked_response.mutable_kv();
kv->set_key(test_key);
kv->set_value(test_value);
ON_CALL(*GetClient(), GetKeyValueAsync(_, _, _, _))
.WillByDefault(DoAll(SetArgPointee<2>(mocked_response),
InvokeArgument<3>(absl::OkStatus())));
InitializeAgent();
auto result = agent_->GetKeyValue(test_key, absl::Seconds(10));
TF_ASSERT_OK(result.status());
EXPECT_EQ(*result, test_value);
}
TEST_F(CoordinationServiceAgentTest, GetKeyValue_Timeout_ReturnError) {
const std::string& test_key = "test_key";
StatusCallback owned_done;
ON_CALL(*GetClient(), GetKeyValueAsync(_, _, _, _))
.WillByDefault(WithArgs<3>([&](StatusCallback done) {
owned_done = done;
}));
InitializeAgent();
auto result = agent_->GetKeyValue(test_key, absl::Seconds(1));
EXPECT_TRUE(absl::IsDeadlineExceeded(result.status()));
owned_done(absl::CancelledError("error"));
}
TEST_F(CoordinationServiceAgentTest,
GetKeyValue_DelayedResponse_TimeoutWithoutMemoryError) {
const std::string& test_key = "test_key";
const std::string& test_value = "test_value";
auto client = std::make_unique<TestCoordinationClient>();
GetKeyValueResponse* owned_response;
StatusCallback owned_done;
ON_CALL(*GetClient(), GetKeyValueAsync(_, _, _, _))
.WillByDefault(WithArgs<2, 3>(
[&](GetKeyValueResponse* response, StatusCallback done) {
owned_response = response;
owned_done = done;
}));
InitializeAgent();
auto result = agent_->GetKeyValue(test_key, absl::Seconds(1));
EXPECT_TRUE(absl::IsDeadlineExceeded(result.status()));
auto kv = owned_response->mutable_kv();
kv->set_key(test_key);
kv->set_value(test_value);
owned_done(absl::OkStatus());
}
TEST_F(CoordinationServiceAgentTest,
GetKeyValue_DelayedResponseBeforeTimeout_Success) {
const std::string& test_key = "test_key";
const std::string& test_value = "test_value";
auto client = std::make_unique<TestCoordinationClient>();
std::unique_ptr<Thread> async_thread;
GetKeyValueResponse* owned_response;
StatusCallback owned_done;
ON_CALL(*GetClient(), GetKeyValueAsync(_, _, _, _))
.WillByDefault(WithArgs<2, 3>(
[&](GetKeyValueResponse* response, StatusCallback done) {
owned_response = response;
owned_done = done;
async_thread = absl::WrapUnique(Env::Default()->StartThread(
ThreadOptions(), "async_thread", [&]() {
absl::SleepFor(absl::Seconds(5));
auto kv = owned_response->mutable_kv();
kv->set_key(test_key);
kv->set_value(test_value);
owned_done(absl::OkStatus());
}));
}));
InitializeAgent();
auto result = agent_->GetKeyValue(test_key, absl::Seconds(10));
TF_ASSERT_OK(result.status());
EXPECT_EQ(*result, test_value);
}
TEST_F(CoordinationServiceAgentTest, CancelGetKeyValue_Success) {
const std::string test_key = "test_key";
ON_CALL(*GetClient(), GetKeyValueAsync(_, _, _, _))
.WillByDefault(
WithArgs<0, 3>([](CallOptions* call_opts, StatusCallback done) {
call_opts->SetCancelCallback([callback = std::move(done)]() {
callback(absl::CancelledError("RPC call cancelled."));
});
}));
InitializeAgent();
absl::Status status;
std::shared_ptr<CallOptions> get_kv_call_opts = agent_->GetKeyValueAsync(
test_key, [&status](const absl::StatusOr<std::string>& result) {
status = result.status();
});
get_kv_call_opts->StartCancel();
EXPECT_TRUE(absl::IsCancelled(status)) << status;
get_kv_call_opts->ClearCancelCallback();
}
TEST_F(CoordinationServiceAgentTest, TryGetKeyValue_Simple_Success) {
const std::string& test_key = "test_key";
const std::string& test_value = "test_value";
TryGetKeyValueResponse mocked_response;
auto kv = mocked_response.mutable_kv();
kv->set_key(test_key);
kv->set_value(test_value);
ON_CALL(*GetClient(), TryGetKeyValueAsync(_, _, _))
.WillByDefault(DoAll(SetArgPointee<1>(mocked_response),
InvokeArgument<2>(absl::OkStatus())));
InitializeAgent();
auto result = agent_->TryGetKeyValue(test_key);
TF_ASSERT_OK(result.status());
EXPECT_EQ(*result, test_value);
}
TEST_F(CoordinationServiceAgentTest, GetKeyValueDir_Simple_Success) {
const std::string test_key = "test_key_dir";
std::vector<KeyValueEntry> test_values;
test_values.push_back(CreateKv("test_key_dir/task_0", "0"));
test_values.push_back(CreateKv("test_key_dir/task_1", "1"));
GetKeyValueDirResponse mocked_response;
mocked_response.set_directory_key(test_key);
*mocked_response.mutable_kv() = {test_values.begin(), test_values.end()};
ON_CALL(*GetClient(), GetKeyValueDirAsync(_, _, _))
.WillByDefault(DoAll(SetArgPointee<1>(mocked_response),
InvokeArgument<2>(absl::OkStatus())));
InitializeAgent();
auto result = agent_->GetKeyValueDir(test_key);
TF_ASSERT_OK(result.status());
EXPECT_THAT(*result, UnorderedPointwise(KvEq(), test_values));
}
TEST_F(CoordinationServiceAgentTest, ShutdownInErrorShouldReturnError) {
InitializeAgent();
TF_ASSERT_OK(agent_->Connect());
TF_ASSERT_OK(agent_->ReportError(absl::InternalError("Test Error.")));
absl::Status s = agent_->Shutdown();
EXPECT_TRUE(absl::IsFailedPrecondition(s));
}
TEST_F(CoordinationServiceAgentTest, Reset_ConnectedButNotInError_Fail) {
InitializeAgent();
TF_ASSERT_OK(agent_->Connect());
auto status = agent_->Reset();
EXPECT_TRUE(absl::IsFailedPrecondition(status));
}
TEST_F(CoordinationServiceAgentTest, ConnectAfterResetError) {
InitializeAgent();
TF_ASSERT_OK(agent_->Connect());
TF_ASSERT_OK(agent_->ReportError(absl::InternalError("Test Error.")));
TF_ASSERT_OK(agent_->Reset());
TF_EXPECT_OK(agent_->Connect());
}
TEST_F(CoordinationServiceAgentTest, ResetCanBeRetried) {
EXPECT_CALL(*GetClient(), ResetTaskAsync(_, _, _))
.WillOnce(InvokeArgument<2>(absl::InternalError("Reset error")))
.WillOnce(InvokeArgument<2>(absl::OkStatus()));
InitializeAgent();
TF_ASSERT_OK(agent_->Connect());
TF_ASSERT_OK(agent_->ReportError(absl::InternalError("Test Error.")));
absl::Status reset_status = agent_->Reset();
EXPECT_TRUE(absl::IsInternal(reset_status));
TF_ASSERT_OK(agent_->Reset());
TF_EXPECT_OK(agent_->Connect());
}
TEST_F(CoordinationServiceAgentTest, GetOwnTask) {
InitializeAgent();
auto result = agent_->GetOwnTask();
TF_ASSERT_OK(result.status());
CoordinatedTask actual_task = *result;
CoordinatedTask expected_task;
expected_task.set_job_name("test_job");
expected_task.set_task_id(0);
EXPECT_EQ(actual_task.job_name(), expected_task.job_name());
EXPECT_EQ(actual_task.task_id(), expected_task.task_id());
}
TEST_F(CoordinationServiceAgentTest, GetOwnTask_Uninitialized) {
auto result = agent_->GetOwnTask();
EXPECT_TRUE(absl::IsFailedPrecondition(result.status()));
}
TEST_F(CoordinationServiceAgentTest, WaitAtBarrier_SameIdUsedTwice_Fails) {
InitializeAgent();
const std::string barrier_id = "only_use_once";
TF_ASSERT_OK(agent_->Connect());
TF_ASSERT_OK(
agent_->WaitAtBarrier(barrier_id, absl::Seconds(1), {}));
auto result =
agent_->WaitAtBarrier(barrier_id, absl::Seconds(1), {});
EXPECT_TRUE(absl::IsFailedPrecondition(result));
}
TEST_F(CoordinationServiceAgentTest, GetEnv_SucceedsAfterInit) {
EXPECT_TRUE(absl::IsFailedPrecondition(agent_->GetEnv().status()));
InitializeAgent();
absl::StatusOr<Env*> result = agent_->GetEnv();
TF_ASSERT_OK(result.status());
EXPECT_EQ(*result, Env::Default());
}
TEST_F(CoordinationServiceAgentTest, Connect_AbortedErrorShouldBeRetried) {
EXPECT_CALL(*GetClient(), RegisterTaskAsync(_, _, _, _))
.WillOnce(
InvokeArgument<3>(absl::AbortedError("DuplicateTaskRegistration")))
.WillOnce(
InvokeArgument<3>(absl::AbortedError("DuplicateTaskRegistration")))
.WillOnce(InvokeArgument<3>(absl::OkStatus()));
InitializeAgent();
TF_EXPECT_OK(agent_->Connect());
}
TEST_F(CoordinationServiceAgentTest, Connect_AbortedErrorShouldFailEventually) {
EXPECT_CALL(*GetClient(), RegisterTaskAsync(_, _, _, _))
.WillRepeatedly(
InvokeArgument<3>(absl::AbortedError("DuplicateTaskRegistration")));
CoordinationServiceConfig config;
config.set_cluster_register_timeout_in_ms(
absl::ToInt64Milliseconds(absl::Seconds(3)));
InitializeAgent(config);
absl::Status s = agent_->Connect();
EXPECT_TRUE(absl::IsAborted(s));
}
TEST_F(CoordinationServiceAgentTest, Connect_InternalErrorShouldBeRetried) {
EXPECT_CALL(*GetClient(), RegisterTaskAsync(_, _, _, _))
.WillOnce(InvokeArgument<3>(
absl::InternalError("Coordination service is not enabled.")))
.WillOnce(InvokeArgument<3>(
absl::InternalError("Coordination service is not enabled.")))
.WillOnce(InvokeArgument<3>(absl::OkStatus()));
InitializeAgent();
TF_EXPECT_OK(agent_->Connect());
}
}
} | 2,238 |
#ifndef XLA_TSL_DISTRIBUTED_RUNTIME_COORDINATION_COORDINATION_SERVICE_H_
#define XLA_TSL_DISTRIBUTED_RUNTIME_COORDINATION_COORDINATION_SERVICE_H_
#include <cstdint>
#include <functional>
#include <memory>
#include <string>
#include <string_view>
#include <unordered_map>
#include <utility>
#include <vector>
#include "absl/log/log.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/time/time.h"
#include "xla/tsl/distributed_runtime/coordination/coordination_client.h"
#include "tsl/platform/macros.h"
#include "tsl/platform/status.h"
#include "tsl/protobuf/coordination_config.pb.h"
namespace tsl {
class Env;
#define REGISTER_COORDINATION_SERVICE(service_type_name, factory_fn) \
REGISTER_COORDINATION_SERVICE_UNIQ_HELPER(__COUNTER__, service_type_name, \
factory_fn)
#define REGISTER_COORDINATION_SERVICE_UNIQ_HELPER(counter, service_type_name, \
factory_fn) \
static bool static_coordination_service_##counter TF_ATTRIBUTE_UNUSED = \
[]() { \
::tsl::CoordinationServiceInterface::RegisterCoordinationService( \
service_type_name, std::move(factory_fn)); \
return true; \
}()
class CoordinationServiceInterface {
public:
using CoordinationServiceFactory =
std::function<std::unique_ptr<CoordinationServiceInterface>(
Env* env, const tensorflow::CoordinationServiceConfig& config,
std::unique_ptr<CoordinationClientCache> cache)>;
using StatusOrValueCallback =
std::function<void(const absl::StatusOr<std::string_view>&)>;
virtual ~CoordinationServiceInterface() = default;
static void RegisterCoordinationService(
std::string_view service_type_name,
CoordinationServiceFactory factory_fn) {
auto factories = GetCoordinationServiceFactories();
factories->emplace(service_type_name, factory_fn);
}
static std::unique_ptr<CoordinationServiceInterface>
EnableCoordinationService(Env* env,
const tensorflow::CoordinationServiceConfig& config,
std::unique_ptr<CoordinationClientCache> cache) {
const auto* factories = GetCoordinationServiceFactories();
auto factories_iter = factories->find(config.service_type());
if (factories_iter == factories->end()) {
LOG(ERROR) << "No coordination service factory found for service type "
<< config.service_type();
return nullptr;
}
auto service = factories_iter->second(env, config, std::move(cache));
if (service != nullptr) {
*GetCoordinationServiceInstancePtr() = service.get();
}
return service;
}
static CoordinationServiceInterface* GetCoordinationServiceInstance() {
return *GetCoordinationServiceInstancePtr();
}
virtual void SetDeviceAggregationFunction(
std::function<
tensorflow::DeviceInfo(const tensorflow::DeviceInfo& devices)>
post_aggregate_device_fn) = 0;
virtual absl::Status RegisterTask(const tensorflow::CoordinatedTask& task,
uint64_t incarnation) = 0;
virtual void WaitForAllTasks(const tensorflow::CoordinatedTask& task,
const tensorflow::DeviceInfo& devices,
StatusCallback done) = 0;
virtual void ShutdownTaskAsync(const tensorflow::CoordinatedTask& task,
StatusCallback done) = 0;
virtual absl::Status ResetTask(const tensorflow::CoordinatedTask& task) = 0;
virtual absl::Status RecordHeartbeat(const tensorflow::CoordinatedTask& task,
uint64_t incarnation) = 0;
virtual absl::Status ReportTaskError(const tensorflow::CoordinatedTask& task,
absl::Status error) = 0;
virtual std::vector<tensorflow::CoordinatedTaskStateInfo> GetTaskState(
const std::vector<tensorflow::CoordinatedTask>& task) = 0;
virtual absl::Status InsertKeyValue(std::string_view key,
std::string_view value) = 0;
virtual absl::Status InsertKeyValue(std::string_view key,
std::string_view value,
bool allow_overwrite) = 0;
virtual void GetKeyValueAsync(std::string_view key,
StatusOrValueCallback done) = 0;
virtual absl::StatusOr<std::string> TryGetKeyValue(std::string_view key) = 0;
virtual std::vector<tensorflow::KeyValueEntry> GetKeyValueDir(
std::string_view directory_key) = 0;
virtual absl::Status DeleteKeyValue(std::string_view key) = 0;
virtual void BarrierAsync(
std::string_view barrier_id, absl::Duration timeout,
const tensorflow::CoordinatedTask& task,
const std::vector<tensorflow::CoordinatedTask>& participating_tasks,
StatusCallback done) = 0;
virtual absl::Status CancelBarrier(
std::string_view barrier_id, const tensorflow::CoordinatedTask& task) = 0;
private:
friend class CoordinationServiceRpcHandler;
friend class CoordinationServiceTest_ListClusterDevices_TfDevice_Test;
friend class CoordinationServiceTest_ListClusterDevices_XlaDevice_Test;
friend class
CoordinationServiceTest_ListClusterDevices_DevicesAreNotAddedTwice_Test;
virtual const tensorflow::DeviceInfo& ListClusterDevices() = 0;
virtual uint64_t GetServiceIncarnation() = 0;
static std::unordered_map<std::string, CoordinationServiceFactory>*
GetCoordinationServiceFactories() {
static auto* coordination_service_factories =
new std::unordered_map<std::string, CoordinationServiceFactory>();
return coordination_service_factories;
}
static CoordinationServiceInterface** GetCoordinationServiceInstancePtr() {
static CoordinationServiceInterface* instance = nullptr;
return &instance;
}
};
}
#endif
#include "xla/tsl/distributed_runtime/coordination/coordination_service.h"
#include <algorithm>
#include <cassert>
#include <cstddef>
#include <cstdint>
#include <functional>
#include <map>
#include <memory>
#include <string>
#include <string_view>
#include <utility>
#include <vector>
#include "absl/base/thread_annotations.h"
#include "absl/container/flat_hash_map.h"
#include "absl/container/flat_hash_set.h"
#include "absl/hash/hash.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/synchronization/mutex.h"
#include "absl/synchronization/notification.h"
#include "absl/time/time.h"
#include "xla/tsl/distributed_runtime/call_options.h"
#include "xla/tsl/distributed_runtime/coordination/coordination_client.h"
#include "xla/tsl/distributed_runtime/coordination/coordination_service_error_util.h"
#include "xla/tsl/util/device_name_utils.h"
#include "tsl/platform/env.h"
#include "tsl/platform/random.h"
#include "tsl/platform/status.h"
#include "tsl/protobuf/coordination_config.pb.h"
#include "tsl/protobuf/coordination_service.pb.h"
namespace tsl {
namespace {
using tensorflow::CoordinatedTask;
using tensorflow::CoordinatedTaskState;
using tensorflow::CoordinatedTaskStateInfo;
using tensorflow::CoordinationServiceConfig;
using tensorflow::CoordinationServiceError;
using tensorflow::DeviceInfo;
using tensorflow::KeyValueEntry;
constexpr absl::Duration kDevicePropagationTimeout = absl::Hours(1);
constexpr int kDefaultHeartbeatTimeoutMs = 10 * 1000;
constexpr int kServiceToClientTimeoutMs = 10 * 1000;
constexpr size_t kOngoingBarriersSoftLimit = 20;
constexpr char kHealthCheckThread[] = "CoordinationServiceHealthCheck";
constexpr int kPendingTaskLogLimit = 20;
constexpr int kPendingStragglerLogLimit = 3;
std::string GetTaskName(std::string_view job_name, int task_id) {
return absl::StrCat("/job:", job_name, "/replica:", 0, "/task:", task_id);
}
std::string GetTaskName(const CoordinatedTask& task) {
return GetTaskName(task.job_name(), task.task_id());
}
CoordinatedTask GetTaskFromName(std::string_view task_name) {
DeviceNameUtils::ParsedName parsed;
DeviceNameUtils::ParseFullName(task_name, &parsed);
CoordinatedTask task;
task.set_job_name(parsed.job);
task.set_task_id(parsed.task);
return task;
}
struct CoordinatedTaskHash {
uint64_t operator()(const CoordinatedTask& task) const {
return absl::HashOf(task.job_name(), task.task_id());
}
};
struct CoordinatedTaskEqual {
bool operator()(const CoordinatedTask& lhs,
const CoordinatedTask& rhs) const {
return lhs.job_name() == rhs.job_name() && lhs.task_id() == rhs.task_id();
}
};
class CoordinationServiceStandaloneImpl : public CoordinationServiceInterface {
public:
CoordinationServiceStandaloneImpl(
Env* env, const CoordinationServiceConfig& config,
std::unique_ptr<CoordinationClientCache> client_cache);
~CoordinationServiceStandaloneImpl() override { Stop(); }
void SetDeviceAggregationFunction(
std::function<DeviceInfo(const DeviceInfo& devices)>
post_aggregate_device_fn) override;
void LogConnectStatusLocked() const ABSL_EXCLUSIVE_LOCKS_REQUIRED(state_mu_);
absl::Status RegisterTask(const CoordinatedTask& task,
uint64_t incarnation) override;
void WaitForAllTasks(const CoordinatedTask& task, const DeviceInfo& devices,
StatusCallback done) override;
void ShutdownTaskAsync(const CoordinatedTask& task,
StatusCallback done) override;
absl::Status ResetTask(const CoordinatedTask& task) override;
absl::Status RecordHeartbeat(const CoordinatedTask& task,
uint64_t incarnation) override;
absl::Status ReportTaskError(const CoordinatedTask& task,
absl::Status error) override;
std::vector<CoordinatedTaskStateInfo> GetTaskState(
const std::vector<CoordinatedTask>& task) override;
absl::Status InsertKeyValue(std::string_view key,
std::string_view value) override;
absl::Status InsertKeyValue(std::string_view key, std::string_view value,
bool allow_overwrite) override;
void GetKeyValueAsync(std::string_view key,
StatusOrValueCallback done) override;
absl::StatusOr<std::string> TryGetKeyValue(std::string_view key) override;
std::vector<KeyValueEntry> GetKeyValueDir(
std::string_view directory_key) override;
absl::Status DeleteKeyValue(std::string_view key) override;
void BarrierAsync(std::string_view barrier_id, absl::Duration timeout,
const CoordinatedTask& task,
const std::vector<CoordinatedTask>& participating_tasks,
StatusCallback done) override;
absl::Status CancelBarrier(std::string_view barrier_id,
const CoordinatedTask& task) override;
private:
const DeviceInfo& ListClusterDevices() override
ABSL_EXCLUSIVE_LOCKS_REQUIRED(state_mu_);
uint64_t GetServiceIncarnation() override;
void StartCheckStaleness();
void Stop(bool shut_staleness_thread = true);
bool ServiceHasStopped() const ABSL_EXCLUSIVE_LOCKS_REQUIRED(state_mu_);
void ReportServiceErrorToTaskAsync(const CoordinatedTask& destination_task,
absl::Status error);
void PropagateError(const CoordinatedTask& source_task,
bool is_reported_by_task = false)
ABSL_LOCKS_EXCLUDED(state_mu_);
void SetTaskError(std::string_view task_name, absl::Status error)
ABSL_EXCLUSIVE_LOCKS_REQUIRED(state_mu_);
void AggregateClusterDevices() ABSL_EXCLUSIVE_LOCKS_REQUIRED(state_mu_);
absl::Status DisconnectTask(const CoordinatedTask& task)
ABSL_EXCLUSIVE_LOCKS_REQUIRED(state_mu_);
struct BarrierState {
bool passed = false;
absl::Status result = absl::UnknownError(
"Invalid barrier result.");
uint64_t deadline_in_micros = 0;
int num_pending_tasks = 0;
absl::flat_hash_map<CoordinatedTask, bool, CoordinatedTaskHash,
CoordinatedTaskEqual>
tasks_at_barrier;
std::vector<StatusCallback> done_callbacks;
};
void PassBarrier(std::string_view barrier_id, absl::Status result,
BarrierState* barrier)
ABSL_EXCLUSIVE_LOCKS_REQUIRED(state_mu_);
bool ValidateTaskArgs(
const std::vector<CoordinatedTask>& tasks_args,
const absl::flat_hash_map<CoordinatedTask, bool, CoordinatedTaskHash,
CoordinatedTaskEqual>& tasks_at_barrier,
int64_t cluster_size);
bool isRecoverableJob(std::string_view task_name) const;
class TaskState {
public:
CoordinatedTaskState GetState() { return state_; }
absl::Status GetStatus() { return status_; }
uint64_t GetTaskIncarnation() { return task_incarnation_; }
void SetConnected(uint64_t task_incarnation);
void Disconnect(uint64_t grace_period_duration_us);
absl::Status RecordHeartbeat(uint64_t task_incarnation);
int64_t TimeSinceLastHeartbeatMs();
uint64_t GetDisconnectedGracePeriodMicros();
void SetError(absl::Status status);
DeviceInfo GetDeviceInfo() { return devices_; }
void CollectDeviceInfo(const DeviceInfo& devices) { devices_ = devices; }
bool DeviceInfoIsCollected() { return devices_.device_size() != 0; }
absl::flat_hash_set<std::string> GetOngoingBarriers();
void JoinBarrier(std::string_view barrier_id);
void ExitBarrier(std::string_view barrier_id);
private:
uint64_t task_incarnation_ = 0;
CoordinatedTaskState state_ = CoordinatedTaskState::TASKSTATE_DISCONNECTED;
absl::Status status_;
absl::Mutex last_heartbeat_mu_;
uint64_t last_heartbeat_us_ ABSL_GUARDED_BY(last_heartbeat_mu_);
uint64_t disconnect_grace_period_us_ = 0;
DeviceInfo devices_;
absl::flat_hash_set<std::string> ongoing_barriers_for_task_;
};
std::unique_ptr<CoordinationClientCache> client_cache_;
Env& env_;
const uint64_t service_incarnation_ = random::New64();
const uint64_t heartbeat_timeout_ms_;
const absl::Duration shutdown_barrier_timeout_;
bool allow_new_incarnation_to_reconnect_ = false;
std::function<DeviceInfo(const DeviceInfo& devices)>
post_aggregate_device_fn_;
const std::string device_propagation_barrier_id_ =
absl::StrCat("WaitForAllTasks::", std::to_string(service_incarnation_));
const std::string shutdown_barrier_id_ =
absl::StrCat("Shutdown::", std::to_string(service_incarnation_));
absl::Mutex state_mu_;
absl::flat_hash_map<std::string, std::unique_ptr<TaskState>> cluster_state_
ABSL_GUARDED_BY(state_mu_);
DeviceInfo cluster_devices_ ABSL_GUARDED_BY(state_mu_);
absl::Mutex kv_mu_;
std::map<std::string, std::string> kv_store_ ABSL_GUARDED_BY(kv_mu_);
absl::flat_hash_map<std::string, std::vector<StatusOrValueCallback>> get_cb_
ABSL_GUARDED_BY(kv_mu_);
absl::CondVar check_staleness_thread_cv_;
bool shutting_down_ ABSL_GUARDED_BY(state_mu_) = false;
std::unique_ptr<Thread> check_staleness_thread_;
absl::flat_hash_map<std::string, BarrierState> barriers_
ABSL_GUARDED_BY(state_mu_);
absl::flat_hash_set<std::string> ongoing_barriers_ ABSL_GUARDED_BY(state_mu_);
absl::flat_hash_set<std::string> recoverable_jobs_;
CoordinationServiceStandaloneImpl(const CoordinationServiceStandaloneImpl&) =
delete;
void operator=(const CoordinationServiceStandaloneImpl&) = delete;
};
void CoordinationServiceStandaloneImpl::TaskState::SetConnected(
uint64_t task_incarnation) {
state_ = CoordinatedTaskState::TASKSTATE_CONNECTED;
status_ = absl::OkStatus();
task_incarnation_ = task_incarnation;
absl::MutexLock l(&last_heartbeat_mu_);
last_heartbeat_us_ = Env::Default()->NowMicros();
}
void CoordinationServiceStandaloneImpl::TaskState::Disconnect(
uint64_t grace_period_duration_us) {
disconnect_grace_period_us_ =
Env::Default()->NowMicros() + grace_period_duration_us;
state_ = CoordinatedTaskState::TASKSTATE_DISCONNECTED;
status_ = absl::OkStatus();
}
void CoordinationServiceStandaloneImpl::TaskState::SetError(
const absl::Status status) {
if (state_ == CoordinatedTaskState::TASKSTATE_ERROR) return;
state_ = CoordinatedTaskState::TASKSTATE_ERROR;
status_ = status;
}
absl::Status CoordinationServiceStandaloneImpl::TaskState::RecordHeartbeat(
uint64_t task_incarnation) {
if (!status_.ok()) return status_;
if (task_incarnation != task_incarnation_) {
return MakeCoordinationError(absl::AbortedError(absl::StrCat(
"Incarnation ID mismatch: expecting ", task_incarnation_, " but got ",
task_incarnation, ". This means the remote task has restarted.")));
}
absl::MutexLock l(&last_heartbeat_mu_);
last_heartbeat_us_ = Env::Default()->NowMicros();
return absl::OkStatus();
}
int64_t
CoordinationServiceStandaloneImpl::TaskState::TimeSinceLastHeartbeatMs() {
absl::MutexLock l(&last_heartbeat_mu_);
return (Env::Default()->NowMicros() - last_heartbeat_us_) / 1000;
}
uint64_t CoordinationServiceStandaloneImpl::TaskState::
GetDisconnectedGracePeriodMicros() {
return disconnect_grace_period_us_;
}
absl::flat_hash_set<std::string>
CoordinationServiceStandaloneImpl::TaskState::GetOngoingBarriers() {
return ongoing_barriers_for_task_;
}
void CoordinationServiceStandaloneImpl::TaskState::JoinBarrier(
std::string_view barrier_id) {
ongoing_barriers_for_task_.emplace(barrier_id);
}
void CoordinationServiceStandaloneImpl::TaskState::ExitBarrier(
std::string_view barrier_id) {
ongoing_barriers_for_task_.erase(barrier_id);
}
void CoordinationServiceStandaloneImpl::SetDeviceAggregationFunction(
std::function<DeviceInfo(const DeviceInfo& devices)>
post_aggregate_device_fn) {
post_aggregate_device_fn_ = std::move(post_aggregate_device_fn);
}
CoordinationServiceStandaloneImpl::CoordinationServiceStandaloneImpl(
Env* env, const CoordinationServiceConfig& config,
std::unique_ptr<CoordinationClientCache> client_cache)
: client_cache_(std::move(client_cache)),
env_(*env),
heartbeat_timeout_ms_([&config]() -> uint64_t {
return config.heartbeat_timeout_in_ms() > 0
? config.heartbeat_timeout_in_ms()
: kDefaultHeartbeatTimeoutMs;
}()),
shutdown_barrier_timeout_(
absl::Milliseconds(config.shutdown_barrier_timeout_in_ms())),
allow_new_incarnation_to_reconnect_(
config.allow_new_incarnation_to_reconnect()) {
LOG(INFO) << "Initializing CoordinationService";
recoverable_jobs_ = absl::flat_hash_set<std::string>(
config.recoverable_jobs().cbegin(), config.recoverable_jobs().cend());
for (const auto& job : config.coordinated_job_list()) {
for (int i = 0; i < job.num_tasks(); ++i) {
const std::string task_name = GetTaskName(job.name(), i);
cluster_state_.emplace(task_name, std::make_unique<TaskState>());
}
}
StartCheckStaleness();
}
void CoordinationServiceStandaloneImpl::StartCheckStaleness() {
check_staleness_thread_.reset(
env_.StartThread({}, kHealthCheckThread, [this]() {
const bool has_service_to_client_connection = client_cache_ != nullptr;
std::vector<std::string_view> stale_task_names;
absl::flat_hash_map<std::string, BarrierState*> expired_barriers;
while (true) {
{
absl::MutexLock l(&state_mu_);
check_staleness_thread_cv_.WaitWithTimeout(&state_mu_,
absl::Seconds(1));
if (shutting_down_) {
return;
}
}
absl::Status status = absl::OkStatus();
{
absl::MutexLock l(&state_mu_);
for (const auto& [task_name, task_state] : cluster_state_) {
if (task_state->GetState() !=
CoordinatedTaskState::TASKSTATE_CONNECTED) {
continue;
}
const bool is_stale = task_state->TimeSinceLastHeartbeatMs() >
heartbeat_timeout_ms_;
VLOG(10) << "Checking staleness for " << task_name
<< " stale?=" << is_stale;
if (is_stale) {
stale_task_names.push_back(task_name);
status = MakeCoordinationError(absl::UnavailableError(
absl::StrCat("Task ", task_name,
" heartbeat timeout. This indicates that the "
"remote task "
"has failed, got preempted, or crashed "
"unexpectedly. Check "
"the task logs for an earlier error to debug "
"further.")));
SetTaskError(task_name, status);
}
}
}
if (!stale_task_names.empty()) {
if (!has_service_to_client_connection) {
LOG(ERROR)
<< "Stopping coordination service as the following tasks are "
"unhealthy (stopped sending heartbeats):\n"
<< absl::StrJoin(stale_task_names, "\n")
<< "\nCheck the task logs for an earlier error to debug "
"further.";
Stop(false);
return;
}
for (const auto& stale_task_name : stale_task_names) {
PropagateError(GetTaskFromName(stale_task_name));
}
stale_task_names.clear();
}
uint64_t current_time_micros = Env::Default()->NowMicros();
{
absl::MutexLock l(&state_mu_);
for (std::string_view barrier_id : ongoing_barriers_) {
auto* barrier = &barriers_[barrier_id];
if (current_time_micros > barrier->deadline_in_micros) {
expired_barriers[barrier_id] = barrier;
}
}
for (const auto& [barrier_id, barrier] : expired_barriers) {
std::string pending_tasks;
int pending_task_count = 0;
for (const auto& [task, at_barrier] : barrier->tasks_at_barrier) {
if (!at_barrier) {
++pending_task_count;
if (pending_task_count <= kPendingTaskLogLimit) {
absl::StrAppend(&pending_tasks, GetTaskName(task), "\n");
} else {
break;
}
}
}
const absl::Status error = MakeCoordinationError(
absl::DeadlineExceededError(absl::StrCat(
"Barrier timed out. Barrier_id: ", barrier_id, | #include "xla/tsl/distributed_runtime/coordination/coordination_service.h"
#include <cstdint>
#include <memory>
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>
#include "absl/base/thread_annotations.h"
#include "absl/log/log.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/match.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/string_view.h"
#include "absl/synchronization/mutex.h"
#include "absl/synchronization/notification.h"
#include "absl/time/time.h"
#include "xla/tsl/distributed_runtime/call_options.h"
#include "xla/tsl/distributed_runtime/coordination/coordination_client.h"
#include "xla/tsl/distributed_runtime/coordination/coordination_service_error_util.h"
#include "xla/tsl/distributed_runtime/coordination/test_device.pb.h"
#include "tsl/lib/core/status_test_util.h"
#include "tsl/platform/env.h"
#include "tsl/platform/random.h"
#include "tsl/platform/status.h"
#include "tsl/platform/test.h"
#include "tsl/platform/types.h"
#include "tsl/protobuf/coordination_config.pb.h"
#include "tsl/protobuf/coordination_service.pb.h"
namespace tsl {
namespace {
using ::testing::EqualsProto;
using ::testing::IsEmpty;
using ::testing::UnorderedElementsAre;
using tensorflow::CoordinatedJob;
using tensorflow::CoordinatedTask;
using tensorflow::CoordinationServiceConfig;
using tensorflow::DeviceInfo;
using tensorflow::KeyValueEntry;
using tensorflow::TestDevice;
using tensorflow::TestDeviceList;
constexpr absl::Duration kHeartbeatTimeout = absl::Seconds(2);
constexpr absl::Duration kShutdownBarrierTimeout = absl::Milliseconds(500);
constexpr char kCoordinationServiceType[] = "standalone";
KeyValueEntry CreateKv(const std::string& key, const std::string& value) {
KeyValueEntry kv;
kv.set_key(key);
kv.set_value(value);
return kv;
}
CoordinationServiceConfig GetCoordinationServiceConfig(int num_tasks) {
CoordinationServiceConfig config;
config.set_service_type(kCoordinationServiceType);
CoordinatedJob* job = config.mutable_coordinated_job_list()->Add();
job->set_name("worker");
job->set_num_tasks(num_tasks);
return config;
}
class TestCoordinationClient : public CoordinationClient {
public:
TestCoordinationClient() = default;
absl::Status GetStatus() {
absl::MutexLock l(&mu_);
return status_;
}
void RegisterTaskAsync(CallOptions* opts, const RegisterTaskRequest* request,
RegisterTaskResponse* response,
StatusCallback done) override {
done(absl::OkStatus());
}
void ReportErrorToTaskAsync(CallOptions* call_opts,
const ReportErrorToTaskRequest* request,
ReportErrorToTaskResponse* response,
StatusCallback done) override {
absl::MutexLock l(&mu_);
status_ = absl::Status(static_cast<absl::StatusCode>(request->error_code()),
request->error_message());
done(absl::OkStatus());
}
#define UNIMPLEMENTED(method) \
void method##Async(const method##Request* request, \
method##Response* response, StatusCallback done) \
override{done(absl::UnimplementedError(#method "Async")); \
}
UNIMPLEMENTED(WaitForAllTasks);
UNIMPLEMENTED(ResetTask);
UNIMPLEMENTED(ReportErrorToService);
UNIMPLEMENTED(GetTaskState);
UNIMPLEMENTED(InsertKeyValue);
UNIMPLEMENTED(TryGetKeyValue);
UNIMPLEMENTED(GetKeyValueDir);
UNIMPLEMENTED(DeleteKeyValue);
UNIMPLEMENTED(Barrier);
UNIMPLEMENTED(CancelBarrier);
#undef UNIMPLEMENTED
#define UNIMPLEMENTED_WITH_CALL_OPTS(method) \
void method##Async(CallOptions* call_opts, const method##Request* request, \
method##Response* response, StatusCallback done) \
override{done(absl::UnimplementedError(#method "Async")); \
}
UNIMPLEMENTED_WITH_CALL_OPTS(GetKeyValue);
UNIMPLEMENTED_WITH_CALL_OPTS(Heartbeat);
UNIMPLEMENTED_WITH_CALL_OPTS(ShutdownTask);
#undef UNIMPLEMENTED_WITH_CALL_OPTS
private:
absl::Mutex mu_;
absl::Status status_ ABSL_GUARDED_BY(mu_);
};
class TestCoordinationClientCache : public CoordinationClientCache {
public:
void AddTask(const std::string& target, CoordinationClient* client) {
clients_.emplace(target, client);
}
CoordinationClient* GetClient(const string& target) override {
auto it = clients_.find(target);
if (it == clients_.end()) return nullptr;
return it->second;
}
std::unique_ptr<CoordinationClient> GetOwnedClient(
const string& target) override {
LOG(ERROR) << "GetOwnedClient is not supported.";
return nullptr;
}
private:
std::unordered_map<std::string, CoordinationClient*> clients_;
};
class CoordinationBarrierTest : public ::testing::Test {
protected:
CoordinationBarrierTest() {
const int num_tasks = 3;
auto client_cache = std::make_unique<TestCoordinationClientCache>();
for (int i = 0; i < num_tasks; ++i) {
CoordinatedTask task;
task.set_job_name("worker");
task.set_task_id(i);
auto client = std::make_unique<TestCoordinationClient>();
client_cache->AddTask(absl::StrCat("/job:worker/replica:0/task:", i),
client.get());
tasks_.push_back(task);
clients_.push_back(std::move(client));
}
CoordinationServiceConfig config = GetCoordinationServiceConfig(num_tasks);
coord_service_ = CoordinationServiceInterface::EnableCoordinationService(
Env::Default(), config, std::move(client_cache));
for (int i = 0; i < num_tasks; ++i) {
absl::Status s =
coord_service_->RegisterTask(tasks_[i], 0);
if (!s.ok()) {
LOG(FATAL) << "RegisterTask() failed in CoordinationBarrierTest(): "
<< s;
}
}
}
CoordinationServiceInterface* GetCoordinationService() {
return coord_service_.get();
}
CoordinatedTask GetTask(int i) { return tasks_[i]; }
std::string GetTaskName(const CoordinatedTask& task) {
return absl::StrCat("/job:", task.job_name(), "/replica:", 0,
"/task:", task.task_id());
}
std::vector<TestCoordinationClient*> GetClients() {
std::vector<TestCoordinationClient*> clients;
for (const auto& client : clients_) {
clients.push_back(client.get());
}
return clients;
}
private:
std::unique_ptr<CoordinationServiceInterface> coord_service_;
std::vector<CoordinatedTask> tasks_;
std::vector<std::unique_ptr<TestCoordinationClient>> clients_;
};
class CoordinateTwoTasksTest : public ::testing::Test {
protected:
CoordinateTwoTasksTest() {
task_0_.set_job_name("worker");
task_0_.set_task_id(0);
task_1_.set_job_name("worker");
task_1_.set_task_id(1);
}
void EnableCoordinationService(
bool has_service_to_client_connection = true,
bool enable_shutdown_barrier = false,
bool set_worker_job_recoverable = false,
bool allow_new_incarnation_to_reconnect = false) {
CoordinationServiceConfig config =
GetCoordinationServiceConfig(2);
auto client_cache = std::make_unique<TestCoordinationClientCache>();
if (has_service_to_client_connection) {
client_cache->AddTask("/job:worker/replica:0/task:0", &client_0_);
client_cache->AddTask("/job:worker/replica:0/task:1", &client_1_);
} else {
client_cache = nullptr;
}
config.set_heartbeat_timeout_in_ms(kHeartbeatTimeout /
absl::Milliseconds(1));
if (set_worker_job_recoverable) {
config.mutable_recoverable_jobs()->Add("worker");
}
if (enable_shutdown_barrier) {
config.set_shutdown_barrier_timeout_in_ms(kShutdownBarrierTimeout /
absl::Milliseconds(1));
}
if (allow_new_incarnation_to_reconnect) {
config.set_allow_new_incarnation_to_reconnect(true);
}
coord_service_ = CoordinationServiceInterface::EnableCoordinationService(
Env::Default(), config, std::move(client_cache));
}
CoordinatedTask task_0_;
const uint64_t incarnation_0_ = random::New64();
const uint64_t incarnation_0_new_ = random::New64();
TestCoordinationClient client_0_;
CoordinatedTask task_1_;
const uint64_t incarnation_1_ = random::New64();
const uint64_t incarnation_1_new_ = random::New64();
TestCoordinationClient client_1_;
std::unique_ptr<CoordinationServiceInterface> coord_service_;
};
TestDevice CreateTestDevice(absl::string_view name, int local_id = 0) {
TestDevice device;
device.set_name(name);
device.set_local_id(local_id);
return device;
}
TEST_F(CoordinateTwoTasksTest, TestStandaloneService) {
EnableCoordinationService();
CoordinatedTask task_2;
task_2.set_job_name("worker");
task_2.set_task_id(2);
ASSERT_OK(coord_service_->RegisterTask(task_0_, incarnation_0_));
absl::Notification wait_for_all;
coord_service_->WaitForAllTasks(task_0_, {}, [&](absl::Status s) {
ASSERT_OK(s);
wait_for_all.Notify();
});
ASSERT_FALSE(wait_for_all.HasBeenNotified());
ASSERT_OK(coord_service_->RegisterTask(task_1_, incarnation_1_));
coord_service_->WaitForAllTasks(task_1_, {},
[&](absl::Status s) { ASSERT_OK(s); });
wait_for_all.WaitForNotification();
ASSERT_OK(coord_service_->RecordHeartbeat(task_0_, incarnation_0_));
ASSERT_OK(coord_service_->RecordHeartbeat(task_1_, incarnation_1_));
EXPECT_TRUE(
absl::IsInvalidArgument(coord_service_->RecordHeartbeat(task_2, 0)));
EXPECT_TRUE(absl::IsAborted(coord_service_->RecordHeartbeat(task_1_, 0)));
EXPECT_TRUE(absl::IsAborted(coord_service_->RecordHeartbeat(task_1_, 0)));
EXPECT_TRUE(absl::IsAborted(client_0_.GetStatus()));
}
TEST(CoordinationServiceTest, TestCoordinatedJobs) {
CoordinatedTask chief;
chief.set_job_name("chief");
chief.set_task_id(0);
CoordinatedTask task_0;
task_0.set_job_name("worker");
task_0.set_task_id(0);
CoordinatedTask task_1;
task_1.set_job_name("worker");
task_1.set_task_id(1);
CoordinatedTask evaluator;
evaluator.set_job_name("evaluator");
evaluator.set_task_id(0);
CoordinationServiceConfig config;
config.set_service_type(kCoordinationServiceType);
CoordinatedJob* chief_job = config.mutable_coordinated_job_list()->Add();
chief_job->set_name("chief");
chief_job->set_num_tasks(1);
CoordinatedJob* worker_job = config.mutable_coordinated_job_list()->Add();
worker_job->set_name("worker");
worker_job->set_num_tasks(2);
auto client_cache = std::make_unique<TestCoordinationClientCache>();
TestCoordinationClient ci;
client_cache->AddTask("/job:chief/replica:0/task:0", &ci);
TestCoordinationClient wi0;
client_cache->AddTask("/job:worker/replica:0/task:0", &wi0);
TestCoordinationClient wi1;
client_cache->AddTask("/job:worker/replica:0/task:1", &wi1);
TestCoordinationClient ei;
client_cache->AddTask("/job:evaluator/replica:0/task:0", &ei);
std::unique_ptr<CoordinationServiceInterface> coord_service =
CoordinationServiceInterface::EnableCoordinationService(
Env::Default(), config, std::move(client_cache));
absl::Notification register_chief;
ASSERT_OK(coord_service->RegisterTask(chief, 0));
coord_service->WaitForAllTasks(chief, {}, [&](absl::Status s) {
ASSERT_OK(s);
register_chief.Notify();
});
absl::Notification register_task0;
ASSERT_OK(coord_service->RegisterTask(task_0, 0));
coord_service->WaitForAllTasks(task_0, {}, [&](absl::Status s) {
ASSERT_OK(s);
register_task0.Notify();
});
absl::Notification register_task1;
ASSERT_OK(coord_service->RegisterTask(task_1, 0));
coord_service->WaitForAllTasks(task_1, {}, [&](absl::Status s) {
ASSERT_OK(s);
register_task1.Notify();
});
register_chief.WaitForNotification();
register_task0.WaitForNotification();
register_task1.WaitForNotification();
absl::Status status =
coord_service->RegisterTask(evaluator, 0);
EXPECT_TRUE(absl::IsInvalidArgument(status)) << status;
EXPECT_TRUE(!status.message().empty());
}
TEST(CoordinationServiceTest, RegisterTask_AlreadyConnected_Succeeds) {
const CoordinationServiceConfig config =
GetCoordinationServiceConfig(1);
CoordinatedTask task_0;
task_0.set_job_name("worker");
task_0.set_task_id(0);
std::unique_ptr<CoordinationServiceInterface> coord_service =
CoordinationServiceInterface::EnableCoordinationService(
Env::Default(), config,
nullptr);
ASSERT_OK(coord_service->RegisterTask(task_0, 0));
const absl::Status status =
coord_service->RegisterTask(task_0, 0);
TF_EXPECT_OK(status) << status;
}
TEST(CoordinationServiceTest,
RegisterTask_AlreadyConnectedDifferentIncarnation_Fails) {
const CoordinationServiceConfig config =
GetCoordinationServiceConfig(1);
CoordinatedTask task_0;
task_0.set_job_name("worker");
task_0.set_task_id(0);
std::unique_ptr<CoordinationServiceInterface> coord_service =
CoordinationServiceInterface::EnableCoordinationService(
Env::Default(), config,
nullptr);
ASSERT_OK(coord_service->RegisterTask(task_0, 0));
const absl::Status status =
coord_service->RegisterTask(task_0, 1);
EXPECT_TRUE(absl::IsAborted(status)) << status;
EXPECT_TRUE(!status.message().empty());
}
TEST(CoordinationServiceTest, RegisterTask_AlreadyInError_Fails) {
CoordinationServiceConfig config =
GetCoordinationServiceConfig(1);
CoordinatedTask task_0;
task_0.set_job_name("worker");
task_0.set_task_id(0);
std::unique_ptr<CoordinationServiceInterface> coord_service =
CoordinationServiceInterface::EnableCoordinationService(
Env::Default(), config,
nullptr);
ASSERT_OK(coord_service->RegisterTask(task_0, 0));
ASSERT_OK(coord_service->ReportTaskError(task_0,
absl::InternalError("test_error")));
const absl::Status status =
coord_service->RegisterTask(task_0, 0);
EXPECT_TRUE(absl::IsAborted(status)) << status;
EXPECT_TRUE(!status.message().empty());
}
TEST_F(CoordinateTwoTasksTest, TestTaskHeartbeatTimeout) {
EnableCoordinationService();
ASSERT_OK(coord_service_->RegisterTask(task_0_, incarnation_0_));
ASSERT_OK(coord_service_->RegisterTask(task_1_, incarnation_1_));
Env::Default()->SleepForMicroseconds(
absl::ToInt64Microseconds(2 * kHeartbeatTimeout));
EXPECT_TRUE(absl::IsUnavailable(
coord_service_->RecordHeartbeat(task_0_, incarnation_0_)));
EXPECT_TRUE(absl::IsUnavailable(
coord_service_->RecordHeartbeat(task_1_, incarnation_1_)));
}
TEST_F(CoordinateTwoTasksTest,
HeartbeatTimeoutWithoutServerToClientConnection) {
EnableCoordinationService(false);
ASSERT_OK(coord_service_->RegisterTask(task_0_, incarnation_0_));
ASSERT_OK(coord_service_->RegisterTask(task_1_, incarnation_1_));
Env::Default()->SleepForMicroseconds(
absl::ToInt64Microseconds(2 * kHeartbeatTimeout));
EXPECT_TRUE(absl::IsInternal(
coord_service_->RecordHeartbeat(task_0_, incarnation_0_)));
EXPECT_TRUE(absl::IsInternal(
coord_service_->RecordHeartbeat(task_1_, incarnation_1_)));
}
TEST_F(CoordinateTwoTasksTest, TestTaskRestart) {
EnableCoordinationService();
ASSERT_OK(coord_service_->RegisterTask(task_0_, incarnation_0_));
ASSERT_OK(coord_service_->RegisterTask(task_1_, incarnation_1_));
absl::Status s =
coord_service_->RegisterTask(task_1_, random::New64());
EXPECT_TRUE(absl::IsAborted(s)) << s;
EXPECT_TRUE(absl::IsAborted(client_0_.GetStatus())) << client_0_.GetStatus();
}
TEST_F(CoordinateTwoTasksTest, InsertKeyValue_Duplicate_Fail) {
EnableCoordinationService();
ASSERT_OK(coord_service_->InsertKeyValue("key0", "original_value"));
EXPECT_TRUE(absl::IsAlreadyExists(
coord_service_->InsertKeyValue("key0", "never_added")));
auto result = coord_service_->TryGetKeyValue("key0");
TF_EXPECT_OK(result.status());
EXPECT_EQ(result.value(), "original_value");
}
TEST_F(CoordinateTwoTasksTest, InsertKeyValue_Duplicate_Overwrite) {
EnableCoordinationService();
ASSERT_OK(coord_service_->InsertKeyValue("key0", "original_value"));
TF_EXPECT_OK(coord_service_->InsertKeyValue("key0", "overwritten_value",
true));
auto result = coord_service_->TryGetKeyValue("key0");
TF_EXPECT_OK(result.status());
EXPECT_EQ(result.value(), "overwritten_value");
}
TEST_F(CoordinateTwoTasksTest, TestSetGetValues) {
EnableCoordinationService();
ASSERT_OK(coord_service_->InsertKeyValue("key0", "value0"));
ASSERT_OK(coord_service_->InsertKeyValue("/path", "value"));
ASSERT_OK(coord_service_->InsertKeyValue("/path/to/key1", "value1"));
ASSERT_OK(coord_service_->InsertKeyValue("path/to
absl::Notification n1;
absl::StatusOr<std::string_view> ret;
coord_service_->GetKeyValueAsync(
"key0", [&](const absl::StatusOr<std::string_view>& status_or_value) {
ret = status_or_value;
n1.Notify();
});
n1.WaitForNotification();
ASSERT_OK(ret.status());
EXPECT_EQ(ret.value(), "value0");
absl::Notification n2;
coord_service_->GetKeyValueAsync(
"path
[&](const absl::StatusOr<std::string_view>& status_or_value) {
ret = status_or_value;
n2.Notify();
});
n2.WaitForNotification();
EXPECT_EQ(ret.value(), "value1");
ASSERT_OK(coord_service_->DeleteKeyValue("key0"));
absl::Notification n3;
coord_service_->GetKeyValueAsync(
"key0", [&](const absl::StatusOr<std::string_view>& status_or_value) {
ret = status_or_value;
n3.Notify();
});
EXPECT_FALSE(n3.HasBeenNotified());
ASSERT_OK(coord_service_->InsertKeyValue("key0", "value0_new"));
n3.WaitForNotification();
EXPECT_EQ(ret.value(), "value0_new");
ASSERT_OK(coord_service_->DeleteKeyValue("/path"));
auto n4 = std::make_shared<absl::Notification>();
coord_service_->GetKeyValueAsync(
"/path/to/key1",
[n4](const absl::StatusOr<std::string_view>& status_or_value) {
n4->Notify();
});
EXPECT_FALSE(n4->HasBeenNotified());
}
TEST(CoordinationServiceTest, TryGetKeyValue) {
const CoordinationServiceConfig config =
GetCoordinationServiceConfig(1);
auto client_cache = std::make_unique<TestCoordinationClientCache>();
std::unique_ptr<CoordinationServiceInterface> coord_service =
CoordinationServiceInterface::EnableCoordinationService(
Env::Default(), config, std::move(client_cache));
absl::StatusOr<std::string> result =
coord_service->TryGetKeyValue("test_key");
EXPECT_TRUE(absl::IsNotFound(result.status()));
ASSERT_OK(coord_service->InsertKeyValue("test_key", "test_value"));
result = coord_service->TryGetKeyValue("test_key");
EXPECT_EQ(result.value(), "test_value");
ASSERT_OK(coord_service->DeleteKeyValue("test_key"));
result = coord_service->TryGetKeyValue("test_key");
EXPECT_TRUE(absl::IsNotFound(result.status()));
}
TEST_F(CoordinateTwoTasksTest, GetKeyValueDir_SingleValueInDirectory) {
EnableCoordinationService();
KeyValueEntry kv = CreateKv("dir/path", "value0");
ASSERT_OK(coord_service_->InsertKeyValue(kv.key(), kv.value()));
std::vector<KeyValueEntry> result = coord_service_->GetKeyValueDir("dir");
EXPECT_THAT(result, UnorderedElementsAre(EqualsProto(kv)));
}
TEST_F(CoordinateTwoTasksTest, GetKeyValueDir_MultipleValuesInDirectory) {
EnableCoordinationService();
KeyValueEntry kv = CreateKv("dir/path", "value0");
KeyValueEntry kv2 = CreateKv("dir/path2", "value1");
KeyValueEntry kv_sub = CreateKv("dir/sub_dir/path", "value_sub");
ASSERT_OK(coord_service_->InsertKeyValue(kv.key(), kv.value()));
ASSERT_OK(coord_service_->InsertKeyValue(kv2.key(), kv2.value()));
ASSERT_OK(coord_service_->InsertKeyValue(kv_sub.key(), kv_sub.value()));
std::vector<KeyValueEntry> result = coord_service_->GetKeyValueDir("dir");
EXPECT_THAT(result, UnorderedElementsAre(EqualsProto(kv), EqualsProto(kv2),
EqualsProto(kv_sub)));
}
TEST_F(CoordinateTwoTasksTest, GetKeyValueDir_Empty_ReturnsEmptyList) {
EnableCoordinationService();
std::vector<KeyValueEntry> result = coord_service_->GetKeyValueDir("dir");
EXPECT_THAT(result, IsEmpty());
}
TEST_F(CoordinateTwoTasksTest, GetKeyValueDir_WrongDir_ReturnsEmptyList) {
EnableCoordinationService();
ASSERT_OK(coord_service_->InsertKeyValue("dir0/path", "value0"));
std::vector<KeyValueEntry> result = coord_service_->GetKeyValueDir("dir");
EXPECT_THAT(result, IsEmpty());
}
TEST_F(CoordinateTwoTasksTest, GetKeyValueDir_WrongDirPrefix_ReturnsEmptyList) {
EnableCoordinationService();
ASSERT_OK(coord_service_->InsertKeyValue("wrong_dir/dir/path", "value0"));
std::vector<KeyValueEntry> result = coord_service_->GetKeyValueDir("dir");
EXPECT_THAT(result, IsEmpty());
}
TEST_F(CoordinateTwoTasksTest,
GetKeyValueDir_NonDirectoryPrefix_ReturnsEmptyList) {
EnableCoordinationService();
ASSERT_OK(coord_service_->InsertKeyValue("dir_key", "value0"));
std::vector<KeyValueEntry> result = coord_service_->GetKeyValueDir("dir");
EXPECT_THAT(result, IsEmpty());
}
TEST_F(CoordinateTwoTasksTest,
GetKeyValueDir_NonDirectoryKey_ReturnsEmptyList) {
EnableCoordinationService();
ASSERT_OK(coord_service_->InsertKeyValue("dir", "value0"));
std::vector<KeyValueEntry> result = coord_service_->GetKeyValueDir("dir");
EXPECT_THAT(result, IsEmpty());
}
}
TEST(CoordinationServiceTest, ListClusterDevices_TfDevice) {
const CoordinationServiceConfig config =
GetCoordinationServiceConfig(3);
CoordinatedTask task_0;
task_0.set_job_name("worker");
task_0.set_task_id(0);
CoordinatedTask task_1;
task_1.set_job_name("worker");
task_1.set_task_id(1);
CoordinatedTask task_2;
task_2.set_job_name("worker");
task_2.set_task_id(2);
absl::Status status = absl::OkStatus();
auto client_cache = std::make_unique<TestCoordinationClientCache>();
std::unique_ptr<CoordinationServiceInterface> coord_service =
CoordinationServiceInterface::EnableCoordinationService(
Env::Default(), config, std::move(client_cache));
absl::Notification n;
DeviceInfo local_devices_0;
DeviceInfo local_devices_1;
DeviceInfo local_devices_2;
local_devices_0.mutable_device()->Add()->PackFrom(
CreateTestDevice("task0_device0"));
local_devices_0.mutable_device()->Add()->PackFrom(
CreateTestDevice("task0_device1"));
local_devices_1.mutable_device()->Add()->PackFrom(
CreateTestDevice("task1_device0"));
local_devices_2.mutable_device()->Add()->PackFrom(
CreateTestDevice("task2_device0"));
DeviceInfo cluster_devices;
coord_service->WaitForAllTasks(task_0, local_devices_0,
[&](absl::Status s) { ASSERT_OK(s); });
coord_service->WaitForAllTasks(task_1, local_devices_1,
[&](absl::Status s) { ASSERT_OK(s); });
coord_service->WaitForAllTasks(task_2, local_devices_2, [&](absl::Status s) {
ASSERT_OK(s);
cluster_devices = coord_service->ListClusterDevices();
n.Notify();
});
n.WaitForNotification();
DeviceInfo expected_cluster_devices;
auto expected_devices = expected_cluster_devices.mutable_device();
expected_devices->Add(local_devices_0.device().begin(),
local_devices_0.device().end());
expected_devices->Add(local_devices_1.device().begin(),
local_devices_1.device().end());
expected_devices->Add(local_devices_2.device().begin(),
local_devices_2.device().end());
EXPECT_THAT(cluster_devices, EqualsProto(expected_cluster_devices));
}
TEST(CoordinationServiceTest, ListClusterDevices_XlaDevice) {
const CoordinationServiceConfig config =
GetCoordinationServiceConfig(3);
CoordinatedTask task_0;
task_0.set_job_name("worker");
task_0.set_task_id(0);
CoordinatedTask task_1;
task_1.set_job_name("worker");
task_1.set_task_id(1);
CoordinatedTask task_2;
task_2.set_job_name("worker");
task_2.set_task_id(2);
absl::Status status = absl::OkStatus();
auto client_cache = std::make_unique<TestCoordinationClientCache>();
std::unique_ptr<CoordinationServiceInterface> coord_service =
CoordinationServiceInterface::EnableCoordinationService(
Env::Default(), config, std::move(client_cache));
coord_service->SetDeviceAggregationFunction(
[](const DeviceInfo& raw_global_devices) {
TestDeviceList global_device_list;
int global_id = 0;
for (const auto& device : raw_global_devices.device()) {
TestDevice local_device;
device.UnpackTo(&local_device);
local_device.set_global_id(global_id++);
*global_device_list.mutable_device()->Add() = local_device;
}
DeviceInfo global_devices;
global_devices.mutable_device()->Add()->PackFrom(global_device_list);
return global_devices;
});
absl::Notification n;
DeviceInfo local_devices_0;
DeviceInfo local_devices_1;
DeviceInfo local_devices_2;
TestDevice local_0 = CreateTestDevice("task0_device0", 0);
TestDevice local_0_1 = CreateTestDevice("task0_device1", 1);
TestDevice local_1 = CreateTestDevice("task1_device0", 0);
TestDevice local_2 = CreateTestDevice("task2_device0", 0);
local_devices_0.mutable_device()->Add()->PackFrom(local_0);
local_devices_0.mutable_device()->Add()->PackFrom(local_0_1);
local_devices_1.mutable_device()->Add()->PackFrom(local_1);
local_devices_2.mutable_device()->Add()->PackFrom(local_2);
DeviceInfo cluster_devices;
coord_service->WaitForAllTasks(task_1, local_devices_1,
[&](absl::Status s) { ASSERT_OK(s); });
coord_service->WaitForAllTasks(task_0, local_devices_0,
[&](absl::Status s) { ASSERT_OK(s); });
coord_service->WaitForAllTasks(task_2, local_devices_2, [&](absl::Status s) {
ASSERT_OK(s);
cluster_devices = coord_service->ListClusterDevices();
n.Notify();
});
n.WaitForNotification();
DeviceInfo expected_cluster_devices;
TestDeviceList global_device_list;
local_0.set_global_id(0);
local_0_1.set_global_id(1);
local_1.set_global_id(2);
local_2.set_global_id(3);
*global_device_list.add_device() = local_0;
*global_device_list.add_device() = local_0_1;
*global_device_list.add_device() = local_1;
*global_device_list.add_device() = local_2;
expected_cluster_devices.mutable_device()->Add()->PackFrom(
global_device_list);
EXPECT_THAT(cluster_devices, EqualsProto(expected_cluster_devices));
}
TEST(CoordinationServiceTest, ListClusterDevices_DevicesAreNotAddedTwice) {
const CoordinationServiceConfig config =
GetCoordinationServiceConfig(2);
CoordinatedTask task_0;
task_0.set_job_name("worker");
task_0.set_task_id(0);
CoordinatedTask task_1;
task_1.set_job_name("worker");
task_1.set_task_id(1);
absl::Status status = absl::OkStatus();
auto client_cache = std::make_unique<TestCoordinationClientCache>();
std::unique_ptr<CoordinationServiceInterface> coord_service =
CoordinationServiceInterface::EnableCoordinationService(
Env::Default(), config, std::move(client_cache));
absl::Notification n;
DeviceInfo local_devices_0;
DeviceInfo local_devices_1;
local_devices_0.mutable_device()->Add()->PackFrom(
CreateTestDevice("task0_device0"));
local_devices_0.mutable_device()->Add()->PackFrom(
CreateTestDevice("task0_device1"));
local_devices_1.mutable_device()->Add()->PackFrom(
CreateTestDevice("task1_device0"));
DeviceInfo cluster_devices;
coord_service->WaitForAllTasks(task_0, local_devices_0,
[](absl::Status s) { ASSERT_OK(s); });
coord_service->WaitForAllTasks(task_0, local_devices_0,
[](absl::Status s) { ASSERT_OK(s); });
coord_service->WaitForAllTasks(task_1, local_devices_1,
[coord_servi | 2,239 |
#ifndef XLA_TSL_C_TSL_STATUS_H_
#define XLA_TSL_C_TSL_STATUS_H_
#ifdef __cplusplus
extern "C" {
#endif
typedef struct TSL_Status TSL_Status;
typedef enum TSL_Code {
TSL_OK = 0,
TSL_CANCELLED = 1,
TSL_UNKNOWN = 2,
TSL_INVALID_ARGUMENT = 3,
TSL_DEADLINE_EXCEEDED = 4,
TSL_NOT_FOUND = 5,
TSL_ALREADY_EXISTS = 6,
TSL_PERMISSION_DENIED = 7,
TSL_UNAUTHENTICATED = 16,
TSL_RESOURCE_EXHAUSTED = 8,
TSL_FAILED_PRECONDITION = 9,
TSL_ABORTED = 10,
TSL_OUT_OF_RANGE = 11,
TSL_UNIMPLEMENTED = 12,
TSL_INTERNAL = 13,
TSL_UNAVAILABLE = 14,
TSL_DATA_LOSS = 15,
} TSL_Code;
extern TSL_Status* TSL_NewStatus(void);
extern void TSL_DeleteStatus(TSL_Status*);
extern void TSL_SetStatus(TSL_Status* s, TSL_Code code, const char* msg);
extern void TSL_SetPayload(TSL_Status* s, const char* key, const char* value);
typedef void (*TSL_PayloadVisitor)(const char* key, const char* value,
void* capture);
extern void TSL_ForEachPayload(const TSL_Status* s, TSL_PayloadVisitor visitor,
void* capture);
extern void TSL_SetStatusFromIOError(TSL_Status* s, int error_code,
const char* context);
extern TSL_Code TSL_GetCode(const TSL_Status* s);
extern const char* TSL_Message(const TSL_Status* s);
#ifdef __cplusplus
}
#endif
#endif
#include "xla/tsl/c/tsl_status.h"
#include <string>
#include "xla/tsl/c/tsl_status_internal.h"
#include "tsl/platform/errors.h"
#include "tsl/platform/status.h"
using ::tsl::Status;
using ::tsl::error::Code;
using ::tsl::errors::IOError;
TSL_Status* TSL_NewStatus() { return new TSL_Status; }
void TSL_DeleteStatus(TSL_Status* s) { delete s; }
void TSL_SetStatus(TSL_Status* s, TSL_Code code, const char* msg) {
if (code == TSL_OK) {
s->status = absl::OkStatus();
return;
}
s->status =
Status(static_cast<absl::StatusCode>(code), tsl::StringPiece(msg));
}
void TSL_SetPayload(TSL_Status* s, const char* key, const char* value) {
s->status.SetPayload(key, absl::Cord(absl::string_view(value)));
}
void TSL_ForEachPayload(const TSL_Status* s, TSL_PayloadVisitor visitor,
void* capture) {
s->status.ForEachPayload([visitor, capture](absl::string_view type_url,
const absl::Cord& payload) {
std::string type_url_str(type_url);
std::string payload_str(payload);
visitor(type_url_str.c_str(), payload_str.c_str(), capture);
});
}
void TSL_SetStatusFromIOError(TSL_Status* s, int error_code,
const char* context) {
s->status = IOError(context, error_code);
}
TSL_Code TSL_GetCode(const TSL_Status* s) {
return static_cast<TSL_Code>(s->status.code());
}
const char* TSL_Message(const TSL_Status* s) {
return absl::StatusMessageAsCStr(s->status);
} | #include "xla/tsl/c/tsl_status.h"
#include <string>
#include <unordered_map>
#include <utility>
#include "xla/tsl/c/tsl_status_internal.h"
#include "tsl/platform/errors.h"
#include "tsl/platform/test.h"
namespace tsl {
namespace {
TEST(TSL_Status, PayloadsSet) {
TSL_Status* tsl_status = TSL_NewStatus();
TSL_SetStatus(tsl_status, TSL_CANCELLED, "Error Message");
TSL_SetPayload(tsl_status, "a", "1");
TSL_SetPayload(tsl_status, "b", "2");
TSL_SetPayload(tsl_status, "c", "3");
std::unordered_map<std::string, std::string> payloads;
TSL_ForEachPayload(
tsl_status,
[](const char* key, const char* value, void* capture) {
std::unordered_map<std::string, std::string>* payloads =
static_cast<std::unordered_map<std::string, std::string>*>(capture);
payloads->emplace(key, value);
},
&payloads);
EXPECT_EQ(payloads.size(), 3);
EXPECT_EQ(payloads.at("a"), "1");
EXPECT_EQ(payloads.at("b"), "2");
EXPECT_EQ(payloads.at("c"), "3");
TSL_DeleteStatus(tsl_status);
}
}
} | 2,240 |
#ifndef XLA_TSL_CONCURRENCY_ASYNC_VALUE_H_
#define XLA_TSL_CONCURRENCY_ASYNC_VALUE_H_
#include <algorithm>
#include <atomic>
#include <cassert>
#include <cstddef>
#include <cstdint>
#include <iostream>
#include <memory>
#include <type_traits>
#include <utility>
#include "absl/functional/any_invocable.h"
#include "absl/status/status.h"
#include "absl/types/span.h"
#include "xla/tsl/concurrency/concurrent_vector.h"
#include "xla/tsl/concurrency/ref_count.h"
#include "tsl/platform/mem.h"
namespace tsl {
class NotifierListNode;
namespace internal {
template <typename T>
class ConcreteAsyncValue;
template <typename T>
constexpr bool kMaybeBase = std::is_class<T>::value && !std::is_final<T>::value;
}
class AsyncValue {
public:
class Executor;
~AsyncValue();
bool IsUnconstructed() const;
bool IsConstructed() const;
bool IsConcrete() const;
bool IsError() const;
bool IsAvailable() const;
bool IsUnavailable() const { return !IsAvailable(); }
bool IsUnresolvedIndirect() const;
bool IsIndirect() const;
uint32_t NumRef() const { return refcount_.load(std::memory_order_acquire); }
bool IsUnique() const;
AsyncValue* AddRef() { return AddRef(1); }
AsyncValue* AddRef(uint32_t count);
void DropRef() { DropRef(1); }
void DropRef(uint32_t count);
template <typename T>
const T& get() const;
template <typename T>
T& get();
const absl::Status& GetError() const;
const absl::Status* GetErrorIfPresent() const;
template <typename T>
bool IsType() const {
return GetTypeId<T>() == type_id_;
}
void SetStateConcrete();
template <typename T, typename... Args>
void emplace(Args&&... args);
void SetError(absl::Status status);
template <typename Waiter>
void AndThen(Waiter&& waiter);
template <typename Waiter>
void AndThen(Executor& executor, Waiter&& waiter);
static size_t GetNumAsyncValueInstances() {
assert(AsyncValueAllocationTrackingEnabled() &&
"AsyncValue instance tracking disabled!");
return total_allocated_async_values_.load(std::memory_order_relaxed);
}
static bool AsyncValueAllocationTrackingEnabled() {
#ifdef NDEBUG
return false;
#else
return true;
#endif
}
enum class Kind : uint8_t {
kConcrete = 0,
kIndirect = 1,
};
Kind kind() const { return kind_; }
class State {
public:
enum StateEnum : int8_t {
kUnconstructed = 0,
kConstructed = 1,
kConcrete = 2,
kError = 3,
};
State(StateEnum s) : state_(s) {}
operator StateEnum() { return state_; }
bool IsUnconstructed() const { return state_ == kUnconstructed; }
bool IsConstructed() const { return state_ == kConstructed; }
bool IsConcrete() const { return state_ == kConcrete; }
bool IsError() const { return state_ == kError; }
bool IsAvailable() const { return state_ == kConcrete || state_ == kError; }
bool IsUnavailable() const { return !IsAvailable(); }
const char* DebugString() const {
switch (state_) {
case kUnconstructed:
return "kUnconstructed";
case kConstructed:
return "kConstructed";
case kConcrete:
return "kConcrete";
case kError:
return "kError";
}
}
private:
StateEnum state_;
};
State state() const {
return waiters_and_state_.load(std::memory_order_acquire).state();
}
class Executor {
public:
using Task = absl::AnyInvocable<void()>;
virtual ~Executor() = default;
virtual void Execute(Task task) = 0;
};
protected:
friend class IndirectAsyncValue;
static constexpr uint16_t kUnknownTypeId = 0;
template <typename T>
struct TypeTag {};
template <typename T>
AsyncValue(Kind kind, State state, bool is_refcounted, TypeTag<T>)
: refcount_(1),
kind_(kind),
has_vtable_(std::is_polymorphic<T>()),
is_refcounted_(is_refcounted),
type_id_(GetTypeId<T>()),
waiters_and_state_(WaitersAndState(nullptr, state)) {
if (AsyncValueAllocationTrackingEnabled() && is_refcounted)
total_allocated_async_values_.fetch_add(1, std::memory_order_relaxed);
}
AsyncValue(Kind kind, State state, bool is_refcounted)
: refcount_(1),
kind_(kind),
has_vtable_(false),
is_refcounted_(is_refcounted),
type_id_(kUnknownTypeId),
waiters_and_state_(WaitersAndState(nullptr, state)) {
if (AsyncValueAllocationTrackingEnabled() && is_refcounted)
total_allocated_async_values_.fetch_add(1, std::memory_order_relaxed);
}
AsyncValue(const AsyncValue&) = delete;
AsyncValue& operator=(const AsyncValue&) = delete;
void NotifyAvailable(State available_state);
void Destroy();
void RunWaiters(NotifierListNode* list);
template <typename T, std::enable_if_t<internal::kMaybeBase<T>>* = nullptr>
bool IsTypeIdCompatible() const {
return true;
}
template <typename T, std::enable_if_t<!internal::kMaybeBase<T>>* = nullptr>
bool IsTypeIdCompatible() const {
return GetTypeId<T>() == type_id_;
}
template <typename T>
static uint16_t GetTypeId() {
return internal::ConcreteAsyncValue<T>::concrete_type_id_;
}
template <typename T>
static uint16_t CreateTypeInfoAndReturnTypeId() {
return CreateTypeInfoAndReturnTypeIdImpl(
MakeTypeInfo<internal::ConcreteAsyncValue<T>>());
}
std::atomic<uint32_t> refcount_{1};
Kind kind_ : 2;
const bool has_vtable_ : 1;
const bool is_refcounted_ : 1;
uint16_t type_id_ = 0;
struct WaitersAndState {
static_assert(alignof(std::max_align_t) >= 8 &&
sizeof(NotifierListNode*) == 8);
static constexpr uint64_t kStateMask = (1ull << 2) - 1;
static constexpr uint64_t kPointerMask = ~kStateMask;
WaitersAndState(NotifierListNode* ptr, State state) {
value = (reinterpret_cast<uintptr_t>(ptr) & kPointerMask) |
(state & kStateMask);
}
State state() const {
return State(static_cast<State::StateEnum>(value & kStateMask));
}
NotifierListNode* waiter() const {
return reinterpret_cast<NotifierListNode*>(value & kPointerMask);
}
uintptr_t value;
};
std::atomic<WaitersAndState> waiters_and_state_;
static constexpr int kDataOffset = 64;
private:
struct TypeInfo {
using DestructorFn = size_t (*)(AsyncValue*);
using GetErrorFn = const absl::Status& (*)(const AsyncValue*);
using SetErrorFn = void (*)(AsyncValue*, absl::Status);
using HasDataFn = bool (*)(const AsyncValue*);
DestructorFn destructor;
GetErrorFn get_error;
SetErrorFn set_error;
HasDataFn has_data;
};
template <typename Derived>
static TypeInfo MakeTypeInfo() {
return TypeInfo{
[](AsyncValue* v) {
static_cast<Derived*>(v)->~Derived();
return sizeof(Derived);
},
[](const AsyncValue* v) -> const absl::Status& {
return static_cast<const Derived*>(v)->GetError();
},
[](AsyncValue* v, absl::Status status) {
static_cast<Derived*>(v)->SetError(std::move(status));
},
[](const AsyncValue* v) {
return static_cast<const Derived*>(v)->HasData();
},
};
}
static uint16_t CreateTypeInfoAndReturnTypeIdImpl(const TypeInfo& type_info);
template <typename T>
const T& GetConcreteValue() const;
const TypeInfo& GetTypeInfo() const;
using TypeInfoTable = internal::ConcurrentVector<TypeInfo>;
static TypeInfoTable* GetTypeInfoTableSingleton();
void EnqueueWaiter(absl::AnyInvocable<void()> waiter,
WaitersAndState old_value);
static std::atomic<size_t> total_allocated_async_values_;
};
static_assert(sizeof(AsyncValue) == 16 || sizeof(void*) != 8,
"Unexpected size for AsyncValue");
void BlockUntilReady(AsyncValue* async_value);
void RunWhenReady(absl::Span<AsyncValue* const> values,
absl::AnyInvocable<void()> callee);
void RunWhenReady(absl::Span<RCReference<AsyncValue> const> values,
absl::AnyInvocable<void()> callee);
struct AsyncPayload {
struct KeepOnError {};
};
namespace internal {
template <typename T>
class ConcreteAsyncValue : public AsyncValue {
public:
struct UnconstructedPayload {
bool is_refcounted = true;
};
struct ConstructedPayload {
bool is_refcounted = true;
};
struct ConcretePayload {
bool is_refcounted = true;
};
explicit ConcreteAsyncValue(UnconstructedPayload payload)
: AsyncValue(Kind::kConcrete, State::kUnconstructed,
payload.is_refcounted, TypeTag<T>()) {
VerifyOffsets();
}
explicit ConcreteAsyncValue(absl::Status status)
: AsyncValue(Kind::kConcrete, State::kError,
true, TypeTag<T>()),
data_store_{std::move(status)} {
VerifyOffsets();
}
template <typename... Args>
explicit ConcreteAsyncValue(ConstructedPayload payload, Args&&... args)
: AsyncValue(Kind::kConcrete, State::kConstructed, payload.is_refcounted,
TypeTag<T>()),
data_store_{TypeTag<T>(), std::forward<Args>(args)...} {
VerifyOffsets();
}
template <typename... Args>
explicit ConcreteAsyncValue(ConcretePayload payload, Args&&... args)
: AsyncValue(Kind::kConcrete, State::kConcrete, payload.is_refcounted,
TypeTag<T>()),
data_store_{TypeTag<T>(), std::forward<Args>(args)...} {
VerifyOffsets();
}
~ConcreteAsyncValue() { Destroy(); }
const absl::Status& GetError() const {
assert(IsError());
return data_store_.error();
}
void SetError(absl::Status status) {
data_store_.SetError(state(), std::move(status));
NotifyAvailable(State::kError);
}
const T& get() const {
assert(HasData());
return data_store_.data();
}
T& get() {
assert(HasData());
return data_store_.data();
}
template <typename... Args>
void emplace(Args&&... args) {
data_store_.EmplaceData(std::forward<Args>(args)...);
NotifyAvailable(State::kConcrete);
}
static bool classof(const AsyncValue* v) {
return v->kind() == AsyncValue::Kind::kConcrete;
}
private:
friend class AsyncValue;
class DataOrError {
public:
DataOrError() {}
explicit DataOrError(absl::Status status)
: error_{new absl::Status(std::move(status))} {}
template <typename... Args>
explicit DataOrError(TypeTag<T>, Args&&... args)
: data_{std::forward<Args>(args)...} {}
~DataOrError() {}
void Destroy(State s) {
if (s == State::kError) {
delete error_;
} else if (s == State::kConstructed || s == State::kConcrete) {
data_.~T();
}
}
void SetError(State s, absl::Status status) {
assert(s == State::kUnconstructed || s == State::kConstructed);
if (s == State::kConstructed) {
data_.~T();
}
error_ = new absl::Status(std::move(status));
}
template <typename... Args>
void EmplaceData(Args&&... args) {
new (&data_) T(std::forward<Args>(args)...);
}
bool HasData(State s) const {
return s == State::kConstructed || s == State::kConcrete;
}
absl::Status& error() { return *error_; }
T& data() { return data_; }
const absl::Status& error() const { return *error_; }
const T& data() const { return data_; }
private:
friend class ConcreteAsyncValue;
union {
absl::Status* error_;
T data_;
};
};
class DataAndError {
public:
explicit DataAndError(absl::Status status) { SetError(std::move(status)); }
template <typename... Args>
explicit DataAndError(TypeTag<T>, Args&&... args) {
EmplaceData(std::forward<Args>(args)...);
}
void Destroy(State s) {
if (HasData()) data().~T();
error_.reset();
has_data_ = false;
}
void SetError(State s, absl::Status status) {
assert(!error_);
error_ = std::make_unique<absl::Status>(std::move(status));
}
template <typename... Args>
void EmplaceData(Args&&... args) {
assert(!HasData());
new (&data_) T(std::forward<Args>(args)...);
has_data_ = true;
}
T& data() { return *reinterpret_cast<T*>(&data_); }
const T& data() const { return *reinterpret_cast<const T*>(&data_); }
bool HasData(State s) const { return has_data_; }
bool HasData() const { return has_data_; }
const absl::Status& error() const { return *error_; }
absl::Status& error() { return *error_; }
private:
friend class ConcreteAsyncValue;
using StorageT = typename std::aligned_storage<sizeof(T), alignof(T)>::type;
StorageT data_;
bool has_data_ = false;
std::unique_ptr<absl::Status> error_;
};
using DataStoreT =
std::conditional_t<std::is_base_of_v<AsyncPayload::KeepOnError, T>,
DataAndError, DataOrError>;
alignas(AsyncValue::kDataOffset) DataStoreT data_store_;
void Destroy() { data_store_.Destroy(state()); }
bool HasData() const { return data_store_.HasData(state()); }
static void VerifyOffsets() {
static_assert(offsetof(ConcreteAsyncValue<T>, data_store_.data_) ==
AsyncValue::kDataOffset,
"Offset of ConcreteAsyncValue data payload is assumed to be "
"AsyncValue::kDataOffset == 64");
}
static const uint16_t concrete_type_id_;
};
template <typename T>
const uint16_t ConcreteAsyncValue<T>::concrete_type_id_ =
AsyncValue::CreateTypeInfoAndReturnTypeId<T>();
}
struct DummyValueForErrorAsyncValue {};
class ErrorAsyncValue
: public internal::ConcreteAsyncValue<DummyValueForErrorAsyncValue> {
public:
ErrorAsyncValue(absl::Status status)
: internal::ConcreteAsyncValue<DummyValueForErrorAsyncValue>(
std::move(status)) {}
};
class IndirectAsyncValue : public AsyncValue {
friend class AsyncValue;
public:
IndirectAsyncValue()
: AsyncValue(Kind::kIndirect, State::kUnconstructed,
true) {}
IndirectAsyncValue* AddRef() { return AddRef(1); }
IndirectAsyncValue* AddRef(uint32_t count) {
return static_cast<IndirectAsyncValue*>(AsyncValue::AddRef(count));
}
void ForwardTo(RCReference<AsyncValue> value);
static bool classof(const AsyncValue* v) {
return v->kind() == AsyncValue::Kind::kIndirect;
}
bool IsUnique() const {
return (refcount_.load(std::memory_order_acquire) == 1) && IsAvailable() &&
value_->IsUnique();
}
protected:
template <typename T>
explicit IndirectAsyncValue(TypeTag<T>)
: AsyncValue(Kind::kIndirect, State::kUnconstructed,
true, TypeTag<T>()) {}
~IndirectAsyncValue() { Destroy(); }
private:
void Destroy() {
if (value_) {
value_->DropRef();
value_ = nullptr;
}
}
AsyncValue* value_ = nullptr;
};
template <typename T>
class TypedIndirectAsyncValue : public IndirectAsyncValue {
public:
TypedIndirectAsyncValue() : IndirectAsyncValue(TypeTag<T>()) {
static_assert(sizeof(TypedIndirectAsyncValue) ==
sizeof(IndirectAsyncValue));
}
};
inline AsyncValue::~AsyncValue() {
assert(waiters_and_state_.load().waiter() == nullptr &&
"An async value with waiters should never have refcount of zero");
if (AsyncValueAllocationTrackingEnabled() && is_refcounted_)
total_allocated_async_values_.fetch_sub(1, std::memory_order_relaxed);
type_id_ = ~0;
}
inline bool AsyncValue::IsAvailable() const {
auto s = state();
return s == State::kConcrete || s == State::kError;
}
inline bool AsyncValue::IsError() const { return state() == State::kError; }
inline bool AsyncValue::IsUnconstructed() const {
return state() == State::kUnconstructed;
}
inline bool AsyncValue::IsConstructed() const {
return state() == State::kConstructed;
}
inline bool AsyncValue::IsConcrete() const {
return state() == State::kConcrete;
}
inline bool AsyncValue::IsUnresolvedIndirect() const {
return IsUnavailable() && (kind() == Kind::kIndirect);
}
inline bool AsyncValue::IsIndirect() const { return kind() == Kind::kIndirect; }
inline AsyncValue* AsyncValue::AddRef(uint32_t count) {
#if defined(NDEBUG)
if (!is_refcounted_) return this;
#endif
if (count > 0) {
assert(refcount_.load(std::memory_order_relaxed) > 0);
refcount_.fetch_add(count, std::memory_order_relaxed);
}
return this;
}
inline void AsyncValue::DropRef(uint32_t count) {
#if defined(NDEBUG)
if (!is_refcounted_) return;
#endif
assert(refcount_.load(std::memory_order_relaxed) > 0);
auto is_last_ref = refcount_.load(std::memory_order_acquire) == count;
if (!is_last_ref) {
is_last_ref =
refcount_.fetch_sub(count, std::memory_order_acq_rel) == count;
}
if (is_last_ref) {
Destroy();
}
}
template <typename T>
const T& AsyncValue::GetConcreteValue() const {
assert(std::is_polymorphic<T>::value == has_vtable_);
assert(IsTypeIdCompatible<T>() && "Incorrect accessor");
const char* this_ptr = reinterpret_cast<const char*>(this);
return *reinterpret_cast<const T*>(this_ptr + AsyncValue::kDataOffset);
}
template <typename T>
const T& AsyncValue::get() const {
auto s = state();
(void)s;
switch (kind()) {
case Kind::kConcrete:
#ifndef NDEBUG
if (!GetTypeInfo().has_data(this)) {
std::cerr << "Cannot call get() when ConcreteAsyncValue"
<< " isn't constructed; state: " << s.DebugString() << ","
<< " error message: "
<< (IsError() ? GetError().message() : "None");
std::abort();
}
#endif
return GetConcreteValue<T>();
case K | #include "xla/tsl/concurrency/async_value.h"
#include <cstdint>
#include <memory>
#include <utility>
#include "absl/status/status.h"
#include "xla/tsl/concurrency/async_value_ref.h"
#include "tsl/platform/test.h"
namespace tsl {
TEST(AsyncValueTest, ConstructedToError) {
AsyncValue* value = MakeConstructedAsyncValueRef<int32_t>(123).release();
bool callback_triggered = false;
EXPECT_TRUE(value->IsConstructed());
EXPECT_FALSE(value->IsConcrete());
EXPECT_FALSE(value->IsAvailable());
value->AndThen([&] { callback_triggered = true; });
EXPECT_FALSE(callback_triggered);
value->SetError(absl::InternalError("test error"));
EXPECT_TRUE(callback_triggered);
EXPECT_TRUE(value->IsAvailable());
EXPECT_FALSE(value->IsConcrete());
EXPECT_TRUE(value->IsError());
value->DropRef();
}
TEST(AsyncValueTest, ConstructedToConcrete) {
AsyncValue* value = MakeConstructedAsyncValueRef<int32_t>(123).release();
EXPECT_TRUE(value->IsConstructed());
EXPECT_FALSE(value->IsConcrete());
EXPECT_FALSE(value->IsAvailable());
value->AndThen([] {});
value->SetStateConcrete();
EXPECT_TRUE(value->IsAvailable());
EXPECT_TRUE(value->IsConcrete());
EXPECT_FALSE(value->IsError());
EXPECT_EQ(123, value->get<int32_t>());
value->DropRef();
}
TEST(AsyncValueTest, UnconstructedEmplace) {
AsyncValue* value = MakeUnconstructedAsyncValueRef<int32_t>().release();
EXPECT_FALSE(value->IsConstructed());
EXPECT_FALSE(value->IsConcrete());
EXPECT_FALSE(value->IsAvailable());
value->AndThen([] {});
value->emplace<int32_t>(123);
EXPECT_FALSE(value->IsConstructed());
EXPECT_TRUE(value->IsAvailable());
EXPECT_TRUE(value->IsConcrete());
EXPECT_EQ(123, value->get<int32_t>());
value->DropRef();
}
TEST(AsyncValueTest, AddAndDropRef) {
AsyncValue* value = MakeConstructedAsyncValueRef<int32_t>(123).release();
value->AndThen([] {});
value->SetStateConcrete();
EXPECT_TRUE(value->IsConcrete());
EXPECT_TRUE(value->IsUnique());
value->AddRef();
EXPECT_FALSE(value->IsUnique());
EXPECT_EQ(123, value->get<int32_t>());
value->DropRef();
EXPECT_TRUE(value->IsUnique());
value->DropRef();
}
TEST(AsyncValueTest, KeepPayloadOnError) {
int payload_value = 0;
struct Payload : AsyncPayload::KeepOnError {
explicit Payload(int* value) : value{value} { *value = 1; }
~Payload() { *value = 2; }
int* value;
};
{
AsyncValueRef<Payload> value =
MakeConstructedAsyncValueRef<Payload>(&payload_value);
EXPECT_EQ(1, *value->value);
value.SetStateConcrete();
EXPECT_EQ(1, *value->value);
EXPECT_TRUE(!value.IsError());
}
EXPECT_EQ(2, payload_value);
{
AsyncValueRef<Payload> value =
MakeConstructedAsyncValueRef<Payload>(&payload_value);
EXPECT_TRUE(!value.IsError());
value.SetError("error");
EXPECT_EQ(1, *value->value);
EXPECT_TRUE(value.IsError());
EXPECT_EQ("error", value.GetError().message());
}
EXPECT_EQ(2, payload_value);
}
TEST(AsyncValueTest, StackAllocatedAsyncValue) {
int32_t counter = 0;
class Payload {
public:
explicit Payload(int32_t& counter) : counter_{counter} { counter_++; }
~Payload() { counter_++; }
int32_t count() const { return counter_; }
private:
int32_t& counter_;
};
internal::AsyncValueStorage<Payload> storage;
AsyncValueOwningRef<Payload> owner =
MakeConstructedAsyncValueRef<Payload>(storage, counter);
AsyncValuePtr<Payload> ptr = owner.AsPtr();
AsyncValue* value = ptr.value();
EXPECT_TRUE(value->IsConstructed());
EXPECT_FALSE(value->IsAvailable());
EXPECT_EQ(1, counter);
EXPECT_EQ(1, ptr->count());
ptr.SetStateConcrete();
EXPECT_TRUE(ptr.IsAvailable());
std::make_unique<AsyncValueOwningRef<Payload>>(std::move(owner));
EXPECT_EQ(2, counter);
}
} | 2,241 |
#ifndef XLA_TSL_CONCURRENCY_ASYNC_VALUE_REF_H_
#define XLA_TSL_CONCURRENCY_ASYNC_VALUE_REF_H_
#include <algorithm>
#include <cstddef>
#include <string_view>
#include <type_traits>
#include <utility>
#include "absl/base/attributes.h"
#include "absl/base/optimization.h"
#include "absl/container/inlined_vector.h"
#include "absl/functional/any_invocable.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/types/span.h"
#include "xla/tsl/concurrency/async_value.h"
#include "xla/tsl/concurrency/ref_count.h"
#include "tsl/platform/logging.h"
#include "tsl/platform/mem.h"
namespace tsl {
template <typename T>
class AsyncValueRef;
template <typename T>
class AsyncValuePtr;
RCReference<ErrorAsyncValue> MakeErrorAsyncValueRef(absl::Status status);
ABSL_DEPRECATED("Use the error async value constructor that takes absl::Status")
RCReference<ErrorAsyncValue> MakeErrorAsyncValueRef(std::string_view message);
RCReference<IndirectAsyncValue> MakeIndirectAsyncValue();
template <typename T>
RCReference<IndirectAsyncValue> MakeIndirectAsyncValue();
template <typename T>
AsyncValueRef<T> MakeUnconstructedAsyncValueRef();
template <typename T, typename... Args>
AsyncValueRef<T> MakeConstructedAsyncValueRef(Args&&... args);
template <typename T, typename... Args>
AsyncValueRef<T> MakeAvailableAsyncValueRef(Args&&... args);
template <typename T>
class AsyncValueRef {
public:
using value_type = T;
AsyncValueRef() = default;
AsyncValueRef(const AsyncValueRef&) = default;
AsyncValueRef& operator=(const AsyncValueRef&) = default;
AsyncValueRef(AsyncValueRef&&) = default;
AsyncValueRef& operator=(AsyncValueRef&&) = default;
explicit AsyncValueRef(RCReference<AsyncValue> value)
: value_(std::move(value)) {}
template <typename Derived,
internal::DerivedFrom<Derived, AsyncValue>* = nullptr>
explicit AsyncValueRef(RCReference<Derived> value)
: AsyncValueRef(RCReference<AsyncValue>(std::move(value))) {}
AsyncValueRef(std::nullptr_t) {}
AsyncValueRef(T value)
: AsyncValueRef(MakeAvailableAsyncValueRef<T>(std::move(value))) {}
template <typename Status,
std::enable_if_t<std::is_convertible_v<Status, absl::Status> &&
!std::is_same_v<T, absl::Status>>* = nullptr>
AsyncValueRef(Status&& status)
: AsyncValueRef(MakeErrorAsyncValueRef(std::forward<Status>(status))) {}
template <typename Derived, internal::DerivedFrom<Derived, T>* = nullptr>
AsyncValueRef(AsyncValueRef<Derived> derived)
: value_(derived.ReleaseRCRef()) {}
AsyncValueRef(RCReference<ErrorAsyncValue> value)
: value_(std::move(value)) {}
AsyncValueRef& operator=(RCReference<ErrorAsyncValue> new_value) {
value_ = std::move(new_value);
return *this;
}
operator RCReference<AsyncValue>() && { return std::move(value_); }
bool IsAvailable() const { return value_->IsAvailable(); }
bool IsUnavailable() const { return value_->IsUnavailable(); }
bool IsConcrete() const { return value_->IsConcrete(); }
bool IsUnconstructed() const { return value_->IsUnconstructed(); }
T& get() const { return value_->get<T>(); }
template <typename Derived, internal::DerivedFrom<Derived, T>* = nullptr>
Derived& get() const {
return value_->get<Derived>();
}
template <typename Derived, internal::DerivedFrom<Derived, T>* = nullptr>
bool Isa() const {
return value_ && (std::is_same_v<Derived, T> ||
value_->IsType<Derived>() ||
value_->IsType<DummyValueForErrorAsyncValue>());
}
template <typename Derived, internal::DerivedFrom<Derived, T>* = nullptr>
AsyncValueRef<Derived> Cast() const {
DCHECK(DynCast<Derived>()) << "Illegal async value cast";
return AsyncValueRef<Derived>(value_);
}
template <typename Derived, internal::DerivedFrom<Derived, T>* = nullptr>
AsyncValueRef<Derived> DynCast() const {
DCHECK(value_) << "Async value must be not null";
return Isa<Derived>() ? AsyncValueRef<Derived>(value_)
: AsyncValueRef<Derived>(nullptr);
}
template <typename Derived, internal::DerivedFrom<Derived, T>* = nullptr>
AsyncValueRef<Derived> DynCastOrNull() const {
return value_ ? DynCast<Derived>(value_) : AsyncValueRef<Derived>(nullptr);
}
T* operator->() const { return &get(); }
T& operator*() const { return get(); }
template <typename Waiter>
void AndThen(Waiter&& waiter) const {
AsPtr().AndThen(std::forward<Waiter>(waiter));
}
template <typename Waiter>
void AndThen(AsyncValue::Executor& executor, Waiter&& waiter) const {
AsPtr().AndThen(executor, std::forward<Waiter>(waiter));
}
template <typename R, typename F>
AsyncValueRef<R> Map(F&& f) {
return AsPtr().template Map<R>(std::forward<F>(f));
}
template <typename R, typename F>
AsyncValueRef<R> Map(AsyncValue::Executor& executor, F&& f) {
return AsPtr().template Map<R>(executor, std::forward<F>(f));
}
template <typename F>
auto Map(F&& f) {
return AsPtr().template Map<F>(std::forward<F>(f));
}
template <typename F>
auto Map(AsyncValue::Executor& executor, F&& f) {
return AsPtr().template Map<F>(executor, std::forward<F>(f));
}
template <typename R, typename F>
AsyncValueRef<R> TryMap(F&& f) {
return AsPtr().template TryMap<R>(std::forward<F>(f));
}
template <typename R, typename F>
AsyncValueRef<R> TryMap(AsyncValue::Executor& executor, F&& f) {
return AsPtr().template TryMap<R>(executor, std::forward<F>(f));
}
template <typename F>
auto TryMap(F&& f) {
return AsPtr().TryMap(std::forward<F>(f));
}
template <typename F>
auto TryMap(AsyncValue::Executor& executor, F&& f) {
return AsPtr().TryMap(executor, std::forward<F>(f));
}
template <typename F>
auto FlatMap(F&& f) {
return AsPtr().FlatMap(std::forward<F>(f));
}
template <typename F>
auto FlatMap(AsyncValue::Executor& executor, F&& f) {
return AsPtr().FlatMap(executor, std::forward<F>(f));
}
void SetStateConcrete() const { value_->SetStateConcrete(); }
template <typename... Args>
void emplace(Args&&... args) const {
value_->emplace<T>(std::forward<Args>(args)...);
}
void emplace(absl::StatusOr<T> v) const {
if (v.ok()) {
emplace(std::move(*v));
} else {
SetError(std::move(v.status()));
}
}
bool IsError() const { return value_->IsError(); }
const absl::Status& GetError() const { return value_->GetError(); }
const absl::Status* GetErrorIfPresent() const {
return value_->GetErrorIfPresent();
}
void SetError(absl::Status status) const {
DCHECK(!status.ok()) << "expected non-ok status";
return value_->SetError(std::move(status));
}
void SetError(std::string_view message) const {
SetError(absl::InternalError(message));
}
explicit operator bool() const { return value_.get() != nullptr; }
bool operator==(const AsyncValueRef& r) const { return value_ == r.value_; }
bool operator!=(const AsyncValueRef& r) const { return value_ != r.value_; }
AsyncValue* GetAsyncValue() const { return value_.get(); }
AsyncValuePtr<T> AsPtr() const { return AsyncValuePtr<T>(GetAsyncValue()); }
bool IsUnique() const { return value_->IsUnique(); }
AsyncValueRef<T> CopyRef() const { return AsyncValueRef(CopyRCRef()); }
RCReference<AsyncValue> CopyRCRef() const { return value_; }
AsyncValue* release() { return value_.release(); }
void reset() { value_.reset(); }
RCReference<AsyncValue> ReleaseRCRef() { return std::move(value_); }
private:
RCReference<AsyncValue> value_;
};
template <typename T>
struct IsAsyncValueRef : std::false_type {};
template <typename T>
struct IsAsyncValueRef<AsyncValueRef<T>> : std::true_type {};
template <typename T>
inline constexpr bool is_async_value_ref_v = IsAsyncValueRef<T>::value;
template <typename T>
class AsyncValuePtr {
template <typename R>
struct IsStatusOr : std::false_type {};
template <typename R>
struct IsStatusOr<absl::StatusOr<R>> : std::true_type {};
template <class R>
static constexpr bool is_status_v = std::is_same_v<R, absl::Status>;
template <class R>
static constexpr bool is_status_or_v = IsStatusOr<R>::value;
template <class R>
static constexpr bool is_status_like_v = is_status_v<R> || is_status_or_v<R>;
template <typename Waiter>
using SimpleWaiter = std::enable_if_t<std::is_invocable_v<Waiter>>;
template <typename Waiter>
using StatusOrWaiter =
std::enable_if_t<std::is_invocable_v<Waiter, absl::StatusOr<T*>>>;
template <typename Waiter>
using StatusWaiter =
std::enable_if_t<(std::is_invocable_v<Waiter, absl::Status> &&
!std::is_invocable_v<Waiter, absl::StatusOr<T*>> &&
!is_status_v<T>)>;
template <typename R, typename U>
using MapFunctor = std::enable_if_t<std::is_constructible_v<R, U>>;
template <typename R, typename U>
using TryMapFunctor =
std::enable_if_t<!is_status_like_v<R> && is_status_or_v<U> &&
std::is_constructible_v<R, typename U::value_type> &&
!std::is_constructible_v<R, U>>;
public:
using value_type = T;
AsyncValuePtr() : value_(nullptr) {}
explicit AsyncValuePtr(AsyncValue* value) : value_(value) {}
explicit AsyncValuePtr(const AsyncValueRef<T>& ref)
: value_(ref.GetAsyncValue()) {}
AsyncValue* value() const { return value_; }
AsyncValueRef<T> CopyRef() const { return AsyncValueRef<T>(FormRef(value_)); }
T& get() const { return value_->template get<T>(); }
T* operator->() const { return &get(); }
T& operator*() const { return get(); }
explicit operator bool() const { return value_ != nullptr; }
bool operator!=(std::nullptr_t) const { return value_ != nullptr; }
AsyncValuePtr& operator=(std::nullptr_t) {
value_ = nullptr;
return *this;
}
template <typename Derived, internal::DerivedFrom<Derived, T>* = nullptr>
bool Isa() const {
return value_ && (std::is_same_v<Derived, T> ||
value_->IsType<Derived>() ||
value_->IsType<DummyValueForErrorAsyncValue>());
}
template <typename Derived, internal::DerivedFrom<Derived, T>* = nullptr>
AsyncValuePtr<Derived> Cast() const {
DCHECK(DynCast<Derived>()) << "Illegal async value cast";
return AsyncValuePtr<Derived>(value_);
}
template <typename Derived, internal::DerivedFrom<Derived, T>* = nullptr>
AsyncValuePtr<Derived> DynCast() const {
DCHECK(value_) << "Async value must be not null";
return Isa<Derived>() ? AsyncValuePtr<Derived>(value_)
: AsyncValuePtr<Derived>(nullptr);
}
template <typename Derived, internal::DerivedFrom<Derived, T>* = nullptr>
AsyncValuePtr<Derived> DynCastOrNull() const {
return value_ ? DynCast<Derived>(value_) : AsyncValuePtr<Derived>(nullptr);
}
bool IsAvailable() const { return value_->IsAvailable(); }
bool IsUnavailable() const { return value_->IsUnavailable(); }
bool IsConcrete() const { return value_->IsConcrete(); }
void SetStateConcrete() const { value_->SetStateConcrete(); }
template <typename... Args>
void emplace(Args&&... args) const {
value_->emplace<T>(std::forward<Args>(args)...);
}
bool IsError() const { return value_->IsError(); }
const absl::Status& GetError() const { return value_->GetError(); }
void SetError(absl::Status status) const {
DCHECK(!status.ok()) << "expected non-ok status";
return value_->SetError(std::move(status));
}
template <typename Waiter, SimpleWaiter<Waiter>* = nullptr>
void AndThen(Waiter&& waiter) const {
value_->AndThen(std::forward<Waiter>(waiter));
}
template <typename Waiter, SimpleWaiter<Waiter>* = nullptr>
void AndThen(AsyncValue::Executor& executor, Waiter&& waiter) const {
value_->AndThen(executor, std::forward<Waiter>(waiter));
}
template <typename Waiter, StatusOrWaiter<Waiter>* = nullptr>
void AndThen(Waiter&& waiter) const {
AndThen([waiter = std::forward<Waiter>(waiter), ptr = *this]() mutable {
if (ABSL_PREDICT_FALSE(ptr.IsError())) {
return waiter(ptr.GetError());
} else {
return waiter(&ptr.get());
}
});
}
template <typename Waiter, StatusOrWaiter<Waiter>* = nullptr>
void AndThen(AsyncValue::Executor& executor, Waiter&& waiter) const {
AndThen(executor,
[waiter = std::forward<Waiter>(waiter), ref = CopyRef()]() mutable {
if (ABSL_PREDICT_FALSE(ref.IsError())) {
return waiter(ref.GetError());
} else {
return waiter(&ref.get());
}
});
}
template <typename Waiter, StatusWaiter<Waiter>* = nullptr>
void AndThen(Waiter&& waiter) const {
AndThen([waiter = std::forward<Waiter>(waiter), ptr = *this]() mutable {
if (ABSL_PREDICT_FALSE(ptr.IsError())) {
return waiter(ptr.GetError());
} else {
return waiter(absl::OkStatus());
}
});
}
template <typename Waiter, StatusWaiter<Waiter>* = nullptr>
void AndThen(AsyncValue::Executor& executor, Waiter&& waiter) const {
AndThen(executor,
[waiter = std::forward<Waiter>(waiter), ref = CopyRef()]() mutable {
if (ABSL_PREDICT_FALSE(ref.IsError())) {
return waiter(ref.GetError());
} else {
return waiter(absl::OkStatus());
}
});
}
template <typename R, typename F, typename U = std::invoke_result_t<F, T&>,
MapFunctor<R, U>* = nullptr>
AsyncValueRef<R> Map(F&& f) {
auto result = MakeUnconstructedAsyncValueRef<R>();
AndThen([f = std::forward<F>(f), result, ptr = *this]() mutable {
if (ABSL_PREDICT_FALSE(ptr.IsError())) {
result.SetError(ptr.GetError());
} else {
result.emplace(f(*ptr));
}
});
return result;
}
template <typename R, typename F, typename U = std::invoke_result_t<F, T&>,
MapFunctor<R, U>* = nullptr>
AsyncValueRef<R> Map(AsyncValue::Executor& executor, F&& f) {
auto result = MakeUnconstructedAsyncValueRef<R>();
AndThen(executor,
[f = std::forward<F>(f), result, ref = CopyRef()]() mutable {
if (ABSL_PREDICT_FALSE(ref.IsError())) {
result.SetError(ref.GetError());
} else {
result.emplace(f(*ref));
}
});
return result;
}
template <typename R, typename F, typename U = std::invoke_result_t<F, T&>,
TryMapFunctor<R, U>* = nullptr>
AsyncValueRef<R> TryMap(F&& f) {
auto result = MakeUnconstructedAsyncValueRef<R>();
AndThen([f = std::forward<F>(f), result, ptr = *this]() mutable {
if (ABSL_PREDICT_FALSE(ptr.IsError())) {
result.SetError(ptr.GetError());
} else {
auto status_or = f(*ptr);
if (status_or.ok()) {
result.emplace(std::move(status_or.value()));
} else {
result.SetError(status_or.status());
}
}
});
return result;
}
template <typename R, typename F, typename U = std::invoke_result_t<F, T&>,
TryMapFunctor<R, U>* = nullptr>
AsyncValueRef<R> TryMap(AsyncValue::Executor& executor, F&& f) {
auto result = MakeUnconstructedAsyncValueRef<R>();
AndThen(executor,
[f = std::forward<F>(f), result, ref = CopyRef()]() mutable {
if (ABSL_PREDICT_FALSE(ref.IsError())) {
result.SetError(ref.GetError());
} else {
auto status_or = f(*ref);
if (status_or.ok()) {
result.emplace(std::move(status_or.value()));
} else {
result.SetError(status_or.status());
}
}
});
return result;
}
template <typename F, typename R = std::invoke_result_t<F, T&>>
auto Map(F&& f) {
return Map<R>(std::forward<F>(f));
}
template <typename F, typename R = std::invoke_result_t<F, T&>>
auto Map(AsyncValue::Executor& executor, F&& f) {
return Map<R>(executor, std::forward<F>(f));
}
template <typename F, typename R = std::invoke_result_t<F, T&>,
std::enable_if_t<is_status_or_v<R>>* = nullptr>
auto TryMap(F&& f) {
return TryMap<typename R::value_type>(std::forward<F>(f));
}
template <typename F, typename R = std::invoke_result_t<F, T&>,
std::enable_if_t<is_status_or_v<R>>* = nullptr>
auto TryMap(AsyncValue::Executor& executor, F&& f) {
return TryMap<typename R::value_type>(executor, std::forward<F>(f));
}
template <typename F, typename R = std::invoke_result_t<F, T&>,
std::enable_if_t<is_async_value_ref_v<R>>* = nullptr>
AsyncValueRef<typename R::value_type> FlatMap(F&& f) {
auto promise = MakePromise<R>();
AndThen([f = std::forward<F>(f), promise, ptr = *this]() mutable {
if (ABSL_PREDICT_FALSE(ptr.IsError())) {
promise->SetError(ptr.GetError());
} else {
promise->ForwardTo(f(*ptr));
}
});
return AsyncValueRef<typename R::value_type>(promise);
}
template <typename F, typename R = std::invoke_result_t<F, T&>,
std::enable_if_t<is_async_value_ref_v<R>>* = nullptr>
AsyncValueRef<typename R::value_type> FlatMap(AsyncValue::Executor& executor,
F&& f) {
auto promise = MakePromise<R>();
AndThen(executor,
[f = std::forward<F>(f), promise, ref = CopyRef()]() mutable {
if (ABSL_PREDICT_FALSE(ref.IsError())) {
promise->SetError(ref.GetError());
} else {
promise->ForwardTo(f(*ref));
}
});
return AsyncValueRef<typename R::value_type>(promise);
}
private:
template <typename R>
RCReference<IndirectAsyncValue> MakePromise() {
if constexpr (std::is_final_v<typename R::value_type>) {
return MakeIndirectAsyncValue<typename R::value_type>();
} else {
return MakeIndirectAsyncValue();
};
}
AsyncValue* value_;
};
template <typename T>
void BlockUntilReady(const AsyncValueRef<T>& ref) {
BlockUntilReady(ref.GetAsyncValue());
}
template <typename T>
void BlockUntilReady(const AsyncValuePtr<T>& ptr) {
BlockUntilReady(ptr.value());
}
template <typename T>
void RunWhenReady(absl::Span<const AsyncValueRef<T>> refs,
absl::AnyInvocable<void()> callee) {
absl::InlinedVector<AsyncValue*, 8> values(refs.size());
for (size_t i = 0; i < refs.size(); ++i) {
values[i] = refs[i].GetAsyncValue();
}
RunWhenReady(values, std::move(callee));
}
template <typename T>
void RunWhenReady(absl::Span<const AsyncValuePtr<T>> ptrs,
absl::AnyInvocable<void()> callee) {
absl::InlinedVector<AsyncValue*, 8> values(ptrs.size());
for (size_t i = 0; i < ptrs.size(); ++i) {
values[i] = ptrs[i].value();
}
RunWhenReady(values, std::move(callee));
}
template <typename Derived, typename T,
internal::DerivedFrom<Derived, T>* = nullptr>
bool Isa(const AsyncValueRef<T>& ref) {
return ref.template Isa<Derived>();
}
template <typename Derived, typename T,
internal::DerivedFrom<Derived, T>* = nullptr>
AsyncValueRef<Derived> Cast(const AsyncValueRef<T>& ref) {
return ref.template Cast<Derived>();
}
template <typename Derived, typename T,
internal::DerivedFrom<Derived, T>* = nullptr>
AsyncValueRef<Derived> DynCast(const AsyncValueRef<T>& ref) {
return ref.template DynCast<Derived>();
}
template <typename Derived, typename T,
internal::DerivedFrom<Derived, T>* = nullptr>
AsyncValueRef<Derived> DynCastOrNull(const AsyncValueRef<T>& ref) {
return ref.template DynCastOrNull<Derived>();
}
template <typename Derived, typename T,
internal::DerivedFrom<Derived, T>* = nullptr>
bool Isa(AsyncValuePtr<T> ptr) {
return ptr.template Isa<Derived>();
}
template <typename Derived, typename T,
internal::DerivedFrom<Derived, T>* = nullptr>
AsyncValuePtr<Derived> Cast(AsyncValuePtr<T> ptr) {
return ptr.template Cast<Derived>();
}
template <typename Derived, typename T,
internal::DerivedFrom<Derived, T>* = nullptr>
AsyncValuePtr<Derived> DynCast(AsyncValuePtr<T> ptr) {
return ptr.template DynCast<Derived>();
}
template <typename Derived, typename T,
internal::DerivedFrom<Derived, T>* = nullptr>
AsyncValuePtr<Derived> DynCastOrNull(AsyncValuePtr<T> ptr) {
return ptr.template DynCastOrNull<Derived>();
}
namespace internal {
template <typename T, typename... Args>
T* PlacementCons | #include "xla/tsl/concurrency/async_value_ref.h"
#include <any>
#include <atomic>
#include <cstddef>
#include <cstdint>
#include <utility>
#include <vector>
#include "absl/functional/any_invocable.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/types/span.h"
#include "xla/tsl/concurrency/async_value.h"
#include "xla/tsl/concurrency/ref_count.h"
#include "tsl/platform/test.h"
namespace tsl {
class WrappedInt32 {
public:
explicit WrappedInt32(int32_t value) : value_(value) {}
int32_t value() const { return value_; }
private:
int32_t value_;
};
constexpr int32_t kTestValue = 42;
TEST(AsyncValueRefTest, MakeUnconstructedStatusOrOfAny) {
auto value = MakeUnconstructedAsyncValueRef<absl::StatusOr<std::any>>();
EXPECT_TRUE(value.IsUnavailable());
}
TEST(AsyncValueRefTest, MakeUnconstructedStatusOr) {
auto value = MakeUnconstructedAsyncValueRef<absl::StatusOr<int32_t>>();
EXPECT_TRUE(value.IsUnavailable());
}
TEST(AsyncValueRefTest, MakeConstructedStatusOr) {
auto value = MakeConstructedAsyncValueRef<absl::StatusOr<int32_t>>(42);
EXPECT_TRUE(value.IsUnavailable());
}
TEST(AsyncValueRefTest, MakeAvailableStatusOr) {
auto value = MakeAvailableAsyncValueRef<absl::StatusOr<int32_t>>(42);
EXPECT_TRUE(value.IsAvailable());
EXPECT_EQ(**value, 42);
}
TEST(AsyncValueRefTest, ImplicitValueConversion) {
auto payload = []() -> AsyncValueRef<WrappedInt32> {
return WrappedInt32{42};
}();
EXPECT_TRUE(payload.IsConcrete());
EXPECT_EQ(payload->value(), 42);
}
TEST(AsyncValueRefTest, ImplicitStatusConversion) {
auto error = []() -> AsyncValueRef<WrappedInt32> {
return absl::InternalError("Error");
}();
EXPECT_TRUE(error.IsAvailable());
EXPECT_TRUE(error.IsError());
EXPECT_EQ(error.GetError(), absl::InternalError("Error"));
}
TEST(AsyncValueRefTest, ImplicitStatusConversionWithStatusPayload) {
auto status = []() -> absl::StatusOr<absl::Status> {
return absl::InternalError("Error");
}();
auto error = []() -> AsyncValueRef<absl::Status> {
return absl::InternalError("Error");
}();
ASSERT_TRUE(status.ok());
ASSERT_EQ(*status, absl::InternalError("Error"));
EXPECT_TRUE(error.IsConcrete());
EXPECT_EQ(error.get(), absl::InternalError("Error"));
}
TEST(AsyncValueRefTest, ImplicitStatusConversionWithStatusOrPayload) {
auto status = []() -> absl::StatusOr<absl::StatusOr<int32_t>> {
return absl::StatusOr<int32_t>(absl::InternalError("Error"));
}();
auto error = []() -> AsyncValueRef<absl::StatusOr<int32_t>> {
return absl::StatusOr<int32_t>(absl::InternalError("Error"));
}();
ASSERT_TRUE(status.ok());
ASSERT_EQ(status->status(), absl::InternalError("Error"));
EXPECT_TRUE(error.IsConcrete());
EXPECT_EQ(error->status(), absl::InternalError("Error"));
}
TEST(AsyncValueRefTest, ImplicitStatusConversionWithStatusOrPayloadAndStatus) {
auto status = []() -> absl::StatusOr<absl::StatusOr<int32_t>> {
return absl::InternalError("Error");
}();
auto error = []() -> AsyncValueRef<absl::StatusOr<int32_t>> {
return absl::InternalError("Error");
}();
ASSERT_FALSE(status.ok());
ASSERT_EQ(status.status(), absl::InternalError("Error"));
EXPECT_TRUE(error.IsError());
EXPECT_EQ(error.GetError(), absl::InternalError("Error"));
}
TEST(AsyncValueRefTest, ValueCheck) {
auto wrapped_int_value = MakeAvailableAsyncValueRef<WrappedInt32>(kTestValue);
EXPECT_EQ(wrapped_int_value.get().value(), kTestValue);
EXPECT_EQ(wrapped_int_value->value(), kTestValue);
EXPECT_EQ((*wrapped_int_value).value(), kTestValue);
}
TEST(AsyncValueRefTest, ValueCheckFromRCReference) {
auto wrapped_int_value = MakeAvailableAsyncValueRef<WrappedInt32>(kTestValue);
RCReference<AsyncValue> generic_value = std::move(wrapped_int_value);
EXPECT_EQ(generic_value->get<WrappedInt32>().value(), kTestValue);
}
TEST(AsyncValueRefTest, ValueCheckFromAliasedRCReference) {
auto wrapped_int_value = MakeAvailableAsyncValueRef<WrappedInt32>(kTestValue);
RCReference<AsyncValue> generic_value = std::move(wrapped_int_value);
AsyncValueRef<WrappedInt32> aliased_int_value(std::move(generic_value));
EXPECT_EQ(aliased_int_value.get().value(), kTestValue);
EXPECT_EQ(aliased_int_value->value(), kTestValue);
EXPECT_EQ((*aliased_int_value).value(), kTestValue);
}
TEST(AsyncValueRefTest, ConstructedToError) {
auto value = MakeConstructedAsyncValueRef<int32_t>(kTestValue);
EXPECT_FALSE(value.IsConcrete());
EXPECT_FALSE(value.IsAvailable());
value.AndThen([] {});
value.SetError(absl::InternalError("test error"));
EXPECT_TRUE(value.IsAvailable());
EXPECT_FALSE(value.IsConcrete());
EXPECT_TRUE(value.IsError());
}
TEST(AsyncValueRefTest, ConstructedToConcrete) {
auto value = MakeConstructedAsyncValueRef<int32_t>(kTestValue);
EXPECT_FALSE(value.IsConcrete());
EXPECT_FALSE(value.IsAvailable());
value.AndThen([] {});
value.SetStateConcrete();
EXPECT_TRUE(value.IsAvailable());
EXPECT_TRUE(value.IsConcrete());
EXPECT_FALSE(value.IsError());
EXPECT_EQ(kTestValue, value.get());
}
TEST(AsyncValueRefTest, UnconstructedEmplace) {
auto value = MakeUnconstructedAsyncValueRef<int32_t>();
EXPECT_FALSE(value.IsConcrete());
EXPECT_FALSE(value.IsAvailable());
value.AndThen([] {});
value.emplace(kTestValue);
EXPECT_TRUE(value.IsAvailable());
EXPECT_TRUE(value.IsConcrete());
EXPECT_EQ(kTestValue, value.get());
}
TEST(AsyncValueRefTest, CopyRef) {
auto value = MakeAvailableAsyncValueRef<int32_t>(kTestValue);
EXPECT_TRUE(value.IsConcrete());
EXPECT_TRUE(value.IsUnique());
auto copied_value = value.CopyRef();
EXPECT_FALSE(value.IsUnique());
EXPECT_EQ(value.GetAsyncValue(), copied_value.GetAsyncValue());
}
TEST(AsyncValueRefTest, AndThen) {
AsyncValueRef<int32_t> ref = MakeUnconstructedAsyncValueRef<int32_t>();
EXPECT_FALSE(ref.IsConcrete());
EXPECT_FALSE(ref.IsAvailable());
bool executed = false;
ref.AndThen([&]() { executed = true; });
ref.emplace(42);
EXPECT_TRUE(executed);
}
TEST(AsyncValueRefTest, AndThenError) {
AsyncValueRef<int32_t> ref = MakeConstructedAsyncValueRef<int32_t>(42);
auto error = absl::InternalError("test error");
ref.SetError(error);
ref.AndThen([&](absl::Status status) { EXPECT_EQ(status, error); });
}
TEST(AsyncValueRefTest, AndThenNoError) {
AsyncValueRef<int32_t> ref = MakeAvailableAsyncValueRef<int32_t>(42);
ref.AndThen([](absl::Status status) { EXPECT_TRUE(status.ok()); });
}
TEST(AsyncValueRefTest, AndThenStatusOrError) {
AsyncValueRef<int32_t> ref = MakeConstructedAsyncValueRef<int32_t>(42);
auto error = absl::InternalError("test error");
ref.SetError(error);
ref.AndThen([&](absl::StatusOr<int32_t*> v) {
EXPECT_FALSE(v.ok());
EXPECT_EQ(v.status(), error);
});
}
TEST(AsyncValueRefTest, AndThenStatusOrNoError) {
AsyncValueRef<int32_t> ref = MakeAvailableAsyncValueRef<int32_t>(42);
ref.AndThen([&](absl::StatusOr<int32_t*> v) { EXPECT_EQ(**v, 42); });
}
TEST(AsyncValueRefTest, Nullptr) {
AsyncValueRef<int> av_int = nullptr;
EXPECT_FALSE(av_int);
AsyncValueRef<int> av_int2 = MakeConstructedAsyncValueRef<int>(kTestValue);
EXPECT_TRUE(av_int2);
av_int2 = nullptr;
EXPECT_FALSE(av_int2);
}
TEST(AsyncValueRefTest, MapAvailable) {
AsyncValueRef<int32_t> ref = MakeAvailableAsyncValueRef<int32_t>(42);
AsyncValueRef<float> mapped_to_float =
ref.Map([](int32_t value) -> float { return value; });
EXPECT_TRUE(mapped_to_float.IsAvailable());
EXPECT_EQ(mapped_to_float.get(), 42.0f);
}
TEST(AsyncValueRefTest, MapUnvailable) {
AsyncValueRef<int32_t> ref = MakeConstructedAsyncValueRef<int32_t>(42);
AsyncValueRef<float> mapped_to_float =
ref.Map([](int32_t value) -> float { return value; });
EXPECT_FALSE(mapped_to_float.IsAvailable());
ref.SetStateConcrete();
EXPECT_TRUE(mapped_to_float.IsAvailable());
EXPECT_EQ(mapped_to_float.get(), 42.0f);
}
TEST(AsyncValueRefTest, MapToNonMoveable) {
AsyncValueRef<int32_t> ref = MakeAvailableAsyncValueRef<int32_t>(42);
AsyncValueRef<std::atomic<int32_t>> mapped_to_atomic =
ref.Map<std::atomic<int32_t>>([](int32_t value) { return value; });
EXPECT_TRUE(mapped_to_atomic.IsAvailable());
EXPECT_EQ(mapped_to_atomic->load(), 42);
}
TEST(AsyncValueRefTest, MapError) {
AsyncValueRef<int32_t> ref =
MakeErrorAsyncValueRef(absl::InternalError("error"));
AsyncValueRef<float> mapped_to_float =
ref.Map([](int32_t value) -> float { return value; });
EXPECT_TRUE(mapped_to_float.IsError());
EXPECT_EQ(mapped_to_float.GetError(), absl::InternalError("error"));
}
TEST(AsyncValueRefTest, MapUnvailableError) {
AsyncValueRef<int32_t> ref = MakeConstructedAsyncValueRef<int32_t>(42);
AsyncValueRef<float> mapped_to_float =
ref.Map([](int32_t value) -> float { return value; });
EXPECT_FALSE(mapped_to_float.IsAvailable());
ref.SetError(absl::InternalError("error"));
EXPECT_TRUE(mapped_to_float.IsError());
EXPECT_EQ(mapped_to_float.GetError(), absl::InternalError("error"));
}
TEST(AsyncValueRefTest, MapMultipleTimes) {
AsyncValueRef<int32_t> ref = MakeAvailableAsyncValueRef<int32_t>(42);
auto plus_one = [](int32_t value) { return value + 1; };
AsyncValueRef<int32_t> mapped = ref.Map(plus_one)
.Map(plus_one)
.Map(plus_one)
.Map(plus_one)
.Map(plus_one)
.Map(plus_one);
EXPECT_TRUE(mapped.IsAvailable());
EXPECT_EQ(mapped.get(), 42 + 6);
}
TEST(AsyncValuePtrTest, MapToStatus) {
AsyncValueRef<int32_t> ref = MakeAvailableAsyncValueRef<int32_t>(42);
AsyncValueRef<absl::Status> mapped_to_status =
ref.Map([](int32_t value) -> absl::Status { return absl::OkStatus(); });
EXPECT_TRUE(mapped_to_status.IsAvailable());
EXPECT_EQ(mapped_to_status.get(), absl::OkStatus());
}
TEST(AsyncValueRefTest, MapToStatusOr) {
AsyncValueRef<int32_t> ref = MakeAvailableAsyncValueRef<int32_t>(42);
AsyncValueRef<absl::StatusOr<float>> mapped_to_float =
ref.Map([](int32_t value) -> absl::StatusOr<float> { return value; });
EXPECT_TRUE(mapped_to_float.IsAvailable());
EXPECT_EQ(*mapped_to_float.get(), 42.0f);
}
TEST(AsyncValueRefTest, TryMap) {
AsyncValueRef<int32_t> ref = MakeAvailableAsyncValueRef<int32_t>(42);
AsyncValueRef<float> mapped_to_float =
ref.TryMap([](int32_t value) -> absl::StatusOr<float> { return value; });
EXPECT_TRUE(mapped_to_float.IsAvailable());
EXPECT_EQ(mapped_to_float.get(), 42.0f);
}
TEST(AsyncValueRefTest, TryMapError) {
AsyncValueRef<int32_t> ref = MakeAvailableAsyncValueRef<int32_t>(42);
AsyncValueRef<float> mapped_to_float =
ref.TryMap([](int32_t value) -> absl::StatusOr<float> {
return absl::InternalError("error");
});
EXPECT_TRUE(mapped_to_float.IsError());
EXPECT_EQ(mapped_to_float.GetError(), absl::InternalError("error"));
}
TEST(AsyncValueRefTest, TryMapConstructible) {
AsyncValueRef<int32_t> ref = MakeAvailableAsyncValueRef<int32_t>(42);
struct X {
explicit X(float value) : value(value) {}
float value;
};
AsyncValueRef<X> mapped_to_x = ref.TryMap<X>(
[](int32_t value) -> absl::StatusOr<float> { return value; });
EXPECT_TRUE(mapped_to_x.IsAvailable());
EXPECT_EQ(mapped_to_x->value, 42.0f);
}
TEST(AsyncValueRefTest, FlatMapAvailable) {
AsyncValueRef<int32_t> ref = MakeAvailableAsyncValueRef<int32_t>(42);
AsyncValueRef<float> fmapped_to_float = ref.FlatMap([](int32_t value) {
return MakeAvailableAsyncValueRef<float>(1.0f * value);
});
EXPECT_TRUE(fmapped_to_float.IsAvailable());
EXPECT_EQ(fmapped_to_float.get(), 42.0f);
}
TEST(AsyncValueRefTest, FlatMapUnavailable) {
AsyncValueRef<int32_t> ref = MakeConstructedAsyncValueRef<int32_t>(42);
AsyncValueRef<float> fmapped_to_float = ref.FlatMap([](int32_t value) {
return MakeAvailableAsyncValueRef<float>(1.0f * value);
});
EXPECT_FALSE(fmapped_to_float.IsAvailable());
ref.SetStateConcrete();
EXPECT_TRUE(fmapped_to_float.IsAvailable());
EXPECT_EQ(fmapped_to_float.get(), 42.0f);
}
struct DeferredExecutor : public AsyncValue::Executor {
void Execute(Task task) final { tasks.push_back(std::move(task)); }
size_t Quiesce() {
size_t n = 0;
while (!tasks.empty()) {
Task task = std::move(tasks.back());
tasks.pop_back();
task();
++n;
}
return n;
}
std::vector<Task> tasks;
};
TEST(AsyncValueRefTest, MapAvailableOnExecutor) {
AsyncValueRef<int32_t> ref = MakeAvailableAsyncValueRef<int32_t>(42);
DeferredExecutor executor;
AsyncValueRef<float> mapped_to_float =
ref.Map(executor, [](int32_t value) -> float { return value; });
EXPECT_FALSE(mapped_to_float.IsAvailable());
EXPECT_EQ(executor.Quiesce(), 1);
EXPECT_TRUE(mapped_to_float.IsAvailable());
EXPECT_EQ(mapped_to_float.get(), 42.0f);
}
TEST(AsyncValueRefTest, MapErrorOnExecutor) {
AsyncValueRef<int32_t> ref =
MakeErrorAsyncValueRef(absl::InternalError("error"));
DeferredExecutor executor;
AsyncValueRef<float> mapped_to_float =
ref.Map(executor, [](int32_t value) -> float { return value; });
EXPECT_FALSE(mapped_to_float.IsAvailable());
EXPECT_EQ(executor.Quiesce(), 1);
EXPECT_TRUE(mapped_to_float.IsError());
EXPECT_EQ(mapped_to_float.GetError(), absl::InternalError("error"));
}
TEST(AsyncValueRefTest, MapUnavailableOnExecutor) {
AsyncValueRef<int32_t> ref = MakeConstructedAsyncValueRef<int32_t>(42);
DeferredExecutor executor;
AsyncValueRef<float> mapped_to_float =
ref.Map(executor, [](int32_t value) -> float { return value; });
ref.SetStateConcrete();
ref.release()->DropRef();
EXPECT_FALSE(mapped_to_float.IsAvailable());
EXPECT_EQ(executor.Quiesce(), 1);
EXPECT_TRUE(mapped_to_float.IsAvailable());
EXPECT_EQ(mapped_to_float.get(), 42.0f);
}
TEST(AsyncValueRefTest, TryMapOnExecutor) {
AsyncValueRef<int32_t> ref = MakeConstructedAsyncValueRef<int32_t>(42);
DeferredExecutor executor;
AsyncValueRef<float> mapped_to_float = ref.TryMap(
executor, [](int32_t value) -> absl::StatusOr<float> { return value; });
ref.SetStateConcrete();
ref.release()->DropRef();
EXPECT_FALSE(mapped_to_float.IsAvailable());
EXPECT_EQ(executor.Quiesce(), 1);
EXPECT_TRUE(mapped_to_float.IsAvailable());
EXPECT_EQ(mapped_to_float.get(), 42.0f);
}
TEST(AsyncValueRefTest, TryMapErrorOnExecutor) {
AsyncValueRef<int32_t> ref = MakeConstructedAsyncValueRef<int32_t>(42);
DeferredExecutor executor;
AsyncValueRef<float> mapped_to_float =
ref.TryMap(executor, [](int32_t value) -> absl::StatusOr<float> {
return absl::InternalError("error");
});
ref.SetStateConcrete();
ref.release()->DropRef();
EXPECT_FALSE(mapped_to_float.IsAvailable());
EXPECT_EQ(executor.Quiesce(), 1);
EXPECT_TRUE(mapped_to_float.IsError());
EXPECT_EQ(mapped_to_float.GetError(), absl::InternalError("error"));
}
TEST(AsyncValueRefTest, FlatMapAvailableOnExecutor) {
AsyncValueRef<int32_t> ref = MakeConstructedAsyncValueRef<int32_t>(42);
DeferredExecutor executor;
AsyncValueRef<float> fmapped_to_float =
ref.FlatMap(executor, [](int32_t value) {
return MakeAvailableAsyncValueRef<float>(1.0f * value);
});
ref.SetStateConcrete();
ref.release()->DropRef();
EXPECT_FALSE(fmapped_to_float.IsAvailable());
EXPECT_EQ(executor.Quiesce(), 1);
EXPECT_TRUE(fmapped_to_float.IsAvailable());
EXPECT_EQ(fmapped_to_float.get(), 42.0f);
}
TEST(AsyncValueRefTest, BlockUntilReady) {
AsyncValueRef<int32_t> ref = MakeAvailableAsyncValueRef<int32_t>(42);
BlockUntilReady(ref);
}
TEST(AsyncValueRefTest, RunWhenReady) {
AsyncValueRef<int32_t> ref = MakeAvailableAsyncValueRef<int32_t>(42);
bool executed = false;
RunWhenReady(absl::MakeConstSpan({ref}), [&] { executed = true; });
EXPECT_TRUE(executed);
}
namespace {
struct A {
alignas(16) int32_t a;
};
struct B : public A {
alignas(32) int32_t b;
};
struct C : public B {
alignas(64) int32_t c;
};
struct D : public B {
alignas(64) int32_t d;
};
}
TEST(AsyncValueRefTest, AlignedPayload) {
AsyncValueRef<D> d_ref = MakeAvailableAsyncValueRef<D>();
d_ref->a = 1;
d_ref->b = 2;
d_ref->d = 3;
EXPECT_EQ(d_ref->a, 1);
EXPECT_EQ(d_ref->b, 2);
EXPECT_EQ(d_ref->d, 3);
AsyncValueRef<B> b_ref = d_ref.CopyRef();
EXPECT_EQ(b_ref->a, 1);
EXPECT_EQ(b_ref->b, 2);
AsyncValueRef<A> a_ref = d_ref.CopyRef();
EXPECT_EQ(a_ref->a, 1);
}
TEST(AsyncValueRefTest, Isa) {
AsyncValueRef<A> null_ref;
EXPECT_FALSE(Isa<A>(null_ref));
AsyncValueRef<A> a_ref = MakeAvailableAsyncValueRef<A>();
AsyncValueRef<A> b_ref = MakeAvailableAsyncValueRef<B>();
AsyncValueRef<A> c_ref = MakeAvailableAsyncValueRef<C>();
AsyncValueRef<A> d_ref = MakeAvailableAsyncValueRef<D>();
EXPECT_TRUE(Isa<A>(a_ref));
EXPECT_TRUE(Isa<B>(b_ref));
EXPECT_TRUE(Isa<C>(c_ref));
EXPECT_TRUE(Isa<D>(d_ref));
AsyncValueRef<A> err = MakeErrorAsyncValueRef(absl::InternalError("error"));
EXPECT_TRUE(Isa<A>(err));
EXPECT_TRUE(Isa<B>(err));
EXPECT_TRUE(Isa<C>(err));
EXPECT_TRUE(Isa<D>(err));
AsyncValueRef<A> a_err = MakeConstructedAsyncValueRef<A>();
AsyncValueRef<B> b_err = MakeConstructedAsyncValueRef<B>();
a_err.SetError(absl::InternalError("error"));
b_err.SetError(absl::InternalError("error"));
EXPECT_TRUE(Isa<A>(a_err));
EXPECT_TRUE(Isa<B>(b_err));
auto indirect = MakeIndirectAsyncValue();
AsyncValueRef<A> c_indirect(indirect);
EXPECT_TRUE(Isa<A>(c_indirect));
EXPECT_FALSE(Isa<C>(c_indirect));
indirect->ForwardTo(c_ref.CopyRCRef());
EXPECT_TRUE(Isa<A>(c_indirect));
EXPECT_TRUE(Isa<C>(c_indirect));
auto typed_indirect = MakeIndirectAsyncValue<C>();
AsyncValueRef<A> c_typed_indirect(indirect);
EXPECT_TRUE(Isa<A>(c_typed_indirect));
EXPECT_TRUE(Isa<C>(c_typed_indirect));
typed_indirect->ForwardTo(c_ref.CopyRCRef());
EXPECT_TRUE(Isa<A>(c_typed_indirect));
EXPECT_TRUE(Isa<C>(c_typed_indirect));
auto typed_indirect_err = MakeIndirectAsyncValue<C>();
AsyncValueRef<A> c_typed_indirect_err(typed_indirect_err);
EXPECT_TRUE(Isa<A>(c_typed_indirect.AsPtr()));
EXPECT_TRUE(Isa<C>(c_typed_indirect.AsPtr()));
typed_indirect_err->SetError(absl::InternalError("error"));
EXPECT_TRUE(Isa<A>(c_typed_indirect_err.AsPtr()));
EXPECT_TRUE(Isa<C>(c_typed_indirect_err.AsPtr()));
}
TEST(AsyncValueRefTest, DynCast) {
AsyncValueRef<A> a_ref = MakeAvailableAsyncValueRef<A>();
AsyncValueRef<A> b_ref = MakeAvailableAsyncValueRef<B>();
AsyncValueRef<A> c_ref = MakeAvailableAsyncValueRef<C>();
AsyncValueRef<A> d_ref = MakeAvailableAsyncValueRef<D>();
EXPECT_TRUE(DynCast<A>(a_ref));
EXPECT_TRUE(DynCast<B>(b_ref));
EXPECT_TRUE(DynCast<C>(c_ref));
EXPECT_TRUE(DynCast<D>(d_ref));
EXPECT_TRUE(DynCast<A>(c_ref));
EXPECT_FALSE(DynCast<B>(c_ref));
EXPECT_FALSE(DynCast<C>(d_ref));
AsyncValueRef<A> err = MakeErrorAsyncValueRef(absl::InternalError("error"));
EXPECT_TRUE(DynCast<A>(err));
EXPECT_TRUE(DynCast<B>(err));
EXPECT_TRUE(DynCast<C>(err));
EXPECT_TRUE(DynCast<D>(err));
AsyncValueRef<A> a_err = MakeConstructedAsyncValueRef<A>();
AsyncValueRef<B> b_err = MakeConstructedAsyncValueRef<B>();
a_err.SetError(absl::InternalError("error"));
b_err.SetError(absl::InternalError("error"));
EXPECT_TRUE(DynCast<A>(a_err));
EXPECT_TRUE(DynCast<B>(b_err));
EXPECT_FALSE(DynCast<C>(a_err));
auto indirect = MakeIndirectAsyncValue();
AsyncValueRef<A> c_indirect(indirect);
EXPECT_TRUE(DynCast<A>(c_indirect));
EXPECT_FALSE(DynCast<C>(c_indirect));
indirect->ForwardTo(c_ref.CopyRCRef());
EXPECT_TRUE(DynCast<A>(c_indirect));
EXPECT_TRUE(DynCast<C>(c_indirect));
auto typed_indirect = MakeIndirectAsyncValue<C>();
AsyncValueRef<A> c_typed_indirect(indirect);
EXPECT_TRUE(DynCast<A>(c_typed_indirect));
EXPECT_TRUE(DynCast<C>(c_typed_indirect));
typed_indirect->ForwardTo(c_ref.CopyRCRef());
EXPECT_TRUE(DynCast<A>(c_typed_indirect));
EXPECT_TRUE(DynCast<C>(c_typed_indirect));
}
TEST(AsyncValueRefTest, Cast) {
AsyncValueRef<A> a_ref = MakeAvailableAsyncValueRef<A>();
AsyncValueRef<A> b_ref = MakeAvailableAsyncValueRef<B>();
AsyncValueRef<A> c_ref = MakeAvailableAsyncValueRef<C>();
AsyncValueRef<A> d_ref = MakeAvailableAsyncValueRef<D>();
EXPECT_TRUE(Cast<A>(a_ref));
EXPECT_TRUE(Cast<B>(b_ref));
EXPECT_TRUE(Cast<C>(c_ref));
EXPECT_TRUE(Cast<D>(d_ref));
EXPECT_TRUE(Cast<A>(c_ref));
AsyncValueRef<A> err = MakeErrorAsyncValueRef(absl::InternalError("error"));
EXPECT_TRUE(Cast<A>(err));
EXPECT_TRUE(Cast<B>(err));
EXPECT_TRUE(Cast<C>(err));
EXPECT_TRUE(Cast<D>(err));
AsyncValueRef<A> a_err = MakeConstructedAsyncValueRef<A>();
AsyncValueRef<B> b_err = MakeConstructedAsyncValueRef<B>();
a_err.SetError(absl::InternalError("error"));
b_err.SetError(absl::InternalError("error"));
EXPECT_TRUE(Cast<A>(a_err));
EXPECT_TRUE(Cast<B>(b_err));
auto indirect = MakeIndirectAsyncValue();
AsyncValueRef<A> c_indirect(indirect);
EXPECT_TRUE(Cast<A>(c_indirect));
indirect->ForwardTo(c_ref.CopyRCRef());
EXPECT_TRUE(Cast<A>(c_indirect));
EXPECT_TRUE(Cast<C>(c_indirect));
auto typed_indirect = MakeIndirectAsyncValue<C>();
AsyncValueRef<A> c_typed_indirect(indirect);
EXPECT_TRUE(Cast<A>(c_typed_indirect));
EXPECT_TRUE(Cast<C>(c_typed_indirect));
typed_indirect->ForwardTo(c_ref.CopyRCRef());
EXPECT_TRUE(Cast<A>(c_typed_indirect));
EXPECT_TRUE(Cast<C>(c_typed_indirect));
}
} | 2,242 |
#ifndef XLA_TSL_FRAMEWORK_DEVICE_ID_MANAGER_H_
#define XLA_TSL_FRAMEWORK_DEVICE_ID_MANAGER_H_
#include <vector>
#include "xla/tsl/framework/device_id.h"
#include "xla/tsl/framework/device_type.h"
#include "tsl/platform/status.h"
#include "tsl/platform/statusor.h"
namespace tsl {
class DeviceIdManager {
public:
static absl::Status InsertTfPlatformDeviceIdPair(
const DeviceType& type, TfDeviceId tf_device_id,
PlatformDeviceId platform_device_id);
static absl::Status TfToPlatformDeviceId(
const DeviceType& type, TfDeviceId tf_device_id,
PlatformDeviceId* platform_device_id);
static absl::StatusOr<std::vector<TfDeviceId>> GetTfDevicesOnPlatform(
const DeviceType& type, PlatformDeviceId platform_device_id);
static void TestOnlyReset();
};
}
#endif
#include "xla/tsl/framework/device_id_manager.h"
#include <unordered_map>
#include <vector>
#include "absl/status/status.h"
#include "absl/strings/str_cat.h"
#include "xla/tsl/framework/device_id.h"
#include "tsl/platform/errors.h"
#include "tsl/platform/logging.h"
#include "tsl/platform/macros.h"
#include "tsl/platform/mutex.h"
#include "tsl/platform/status.h"
#include "tsl/platform/statusor.h"
namespace tsl {
namespace {
class TfToPlatformDeviceIdMap {
public:
static TfToPlatformDeviceIdMap* singleton() {
static auto* id_map = new TfToPlatformDeviceIdMap;
return id_map;
}
absl::Status Insert(const DeviceType& type, TfDeviceId tf_device_id,
PlatformDeviceId platform_device_id)
TF_LOCKS_EXCLUDED(mu_) {
std::pair<IdMapType::iterator, bool> result;
{
mutex_lock lock(mu_);
TypeIdMapType::iterator device_id_map_iter =
id_map_.insert({type.type_string(), IdMapType()}).first;
result = device_id_map_iter->second.insert(
{tf_device_id.value(), platform_device_id.value()});
}
if (!result.second && platform_device_id.value() != result.first->second) {
return errors::AlreadyExists(
"TensorFlow device (", type, ":", tf_device_id.value(),
") is being mapped to multiple devices (", platform_device_id.value(),
" now, and ", result.first->second,
" previously), which is not supported. "
"This may be the result of providing different ",
type, " configurations (ConfigProto.gpu_options, for example ",
"different visible_device_list) when creating multiple Sessions in ",
"the same process. This is not currently supported, see ",
"https:
}
return absl::OkStatus();
}
bool Find(const DeviceType& type, TfDeviceId tf_device_id,
PlatformDeviceId* platform_device_id) const TF_LOCKS_EXCLUDED(mu_) {
tf_shared_lock lock(mu_);
auto type_id_map_iter = id_map_.find(type.type_string());
if (type_id_map_iter == id_map_.end()) return false;
auto id_map_iter = type_id_map_iter->second.find(tf_device_id.value());
if (id_map_iter == type_id_map_iter->second.end()) return false;
*platform_device_id = id_map_iter->second;
return true;
}
absl::StatusOr<std::vector<TfDeviceId>> GetTfDevicesOnPlatform(
const DeviceType& type, PlatformDeviceId platform_device_id) const
TF_LOCKS_EXCLUDED(mu_) {
tf_shared_lock lock(mu_);
auto type_id_map_iter = id_map_.find(type.type_string());
if (type_id_map_iter == id_map_.end()) {
return absl::NotFoundError(
absl::StrCat("TensorFlow device type: ", type.type_string(),
" was not registered"));
}
std::vector<TfDeviceId> tf_device_ids;
for (const auto& [tf_device, platform_device] : type_id_map_iter->second) {
if (platform_device == platform_device_id.value()) {
tf_device_ids.push_back(TfDeviceId(tf_device));
}
}
return tf_device_ids;
}
private:
TfToPlatformDeviceIdMap() = default;
void TestOnlyReset() TF_LOCKS_EXCLUDED(mu_) {
mutex_lock lock(mu_);
id_map_.clear();
}
using IdMapType = std::unordered_map<int32, int32>;
using TypeIdMapType = std::unordered_map<std::string, IdMapType>;
mutable mutex mu_;
TypeIdMapType id_map_ TF_GUARDED_BY(mu_);
friend class ::tsl::DeviceIdManager;
TfToPlatformDeviceIdMap(const TfToPlatformDeviceIdMap&) = delete;
void operator=(const TfToPlatformDeviceIdMap&) = delete;
};
}
absl::Status DeviceIdManager::InsertTfPlatformDeviceIdPair(
const DeviceType& type, TfDeviceId tf_device_id,
PlatformDeviceId platform_device_id) {
return TfToPlatformDeviceIdMap::singleton()->Insert(type, tf_device_id,
platform_device_id);
}
absl::Status DeviceIdManager::TfToPlatformDeviceId(
const DeviceType& type, TfDeviceId tf_device_id,
PlatformDeviceId* platform_device_id) {
if (TfToPlatformDeviceIdMap::singleton()->Find(type, tf_device_id,
platform_device_id)) {
return absl::OkStatus();
}
return errors::NotFound("TensorFlow device ", type, ":", tf_device_id.value(),
" was not registered");
}
absl::StatusOr<std::vector<TfDeviceId>> DeviceIdManager::GetTfDevicesOnPlatform(
const DeviceType& type, PlatformDeviceId platform_device_id) {
return TfToPlatformDeviceIdMap::singleton()->GetTfDevicesOnPlatform(
type, platform_device_id);
}
void DeviceIdManager::TestOnlyReset() {
TfToPlatformDeviceIdMap::singleton()->TestOnlyReset();
}
} | #include "tensorflow/core/common_runtime/device/device_id_manager.h"
#include <vector>
#include <gmock/gmock.h>
#include "tensorflow/core/common_runtime/device/device_id.h"
#include "tensorflow/core/framework/types.h"
#include "tensorflow/core/lib/core/status_test_util.h"
#include "tensorflow/core/platform/test.h"
#include "tsl/platform/statusor.h"
namespace tensorflow {
namespace {
using ::testing::IsEmpty;
using ::testing::UnorderedElementsAre;
PlatformDeviceId TfToPlatformDeviceId(const DeviceType& type, TfDeviceId tf) {
PlatformDeviceId platform_device_id;
TF_CHECK_OK(
DeviceIdManager::TfToPlatformDeviceId(type, tf, &platform_device_id));
return platform_device_id;
}
TEST(DeviceIdManagerTest, Basics) {
DeviceType device_type("GPU");
TfDeviceId key_0(0);
PlatformDeviceId value_0(0);
TF_ASSERT_OK(DeviceIdManager::InsertTfPlatformDeviceIdPair(device_type, key_0,
value_0));
EXPECT_EQ(value_0, TfToPlatformDeviceId(device_type, key_0));
TF_ASSERT_OK(DeviceIdManager::InsertTfPlatformDeviceIdPair(device_type, key_0,
value_0));
EXPECT_EQ(value_0, TfToPlatformDeviceId(device_type, key_0));
TfDeviceId key_1(3);
PlatformDeviceId value_1(2);
TF_ASSERT_OK(DeviceIdManager::InsertTfPlatformDeviceIdPair(device_type, key_1,
value_1));
EXPECT_EQ(value_1, TfToPlatformDeviceId(device_type, key_1));
TfDeviceId key_2(10);
TF_ASSERT_OK(DeviceIdManager::InsertTfPlatformDeviceIdPair(device_type, key_2,
value_1));
EXPECT_EQ(value_1, TfToPlatformDeviceId(device_type, key_2));
ASSERT_FALSE(
DeviceIdManager::InsertTfPlatformDeviceIdPair(device_type, key_2, value_0)
.ok());
ASSERT_FALSE(DeviceIdManager::TfToPlatformDeviceId(device_type,
TfDeviceId(100), &value_0)
.ok());
}
TEST(DeviceIdManagerTest, TwoDevices) {
DeviceType device_type0("GPU");
TfDeviceId key_0(0);
PlatformDeviceId value_0(0);
TF_ASSERT_OK(DeviceIdManager::InsertTfPlatformDeviceIdPair(device_type0,
key_0, value_0));
DeviceType device_type1("XPU");
TfDeviceId key_1(2);
PlatformDeviceId value_1(3);
TF_ASSERT_OK(DeviceIdManager::InsertTfPlatformDeviceIdPair(device_type1,
key_1, value_1));
EXPECT_EQ(value_0, TfToPlatformDeviceId(device_type0, key_0));
EXPECT_EQ(value_1, TfToPlatformDeviceId(device_type1, key_1));
ASSERT_FALSE(
DeviceIdManager::TfToPlatformDeviceId(device_type0, key_1, &value_0)
.ok());
ASSERT_FALSE(
DeviceIdManager::TfToPlatformDeviceId(device_type1, key_0, &value_1)
.ok());
ASSERT_FALSE(
DeviceIdManager::TfToPlatformDeviceId("FOO", key_0, &value_0).ok());
}
TEST(DeviceIdManagerTest, GetTfDevicesOnSamePlatform) {
DeviceType device_gpu("GPU");
TfDeviceId tf_device_0(0);
PlatformDeviceId platform_0(0);
TF_ASSERT_OK(DeviceIdManager::InsertTfPlatformDeviceIdPair(
device_gpu, tf_device_0, platform_0));
TfDeviceId tf_device_1(1);
TF_ASSERT_OK(DeviceIdManager::InsertTfPlatformDeviceIdPair(
device_gpu, tf_device_1, platform_0));
DeviceType device_xpu("XPU");
TfDeviceId tf_device_2(2);
PlatformDeviceId platform_1(3);
TF_ASSERT_OK(DeviceIdManager::InsertTfPlatformDeviceIdPair(
device_xpu, tf_device_2, platform_1));
TF_ASSERT_OK_AND_ASSIGN(
std::vector<TfDeviceId> tf_device_ids_gpu,
DeviceIdManager::GetTfDevicesOnPlatform(device_gpu, platform_0));
EXPECT_THAT(tf_device_ids_gpu,
UnorderedElementsAre(tf_device_0, tf_device_1));
TF_ASSERT_OK_AND_ASSIGN(
tf_device_ids_gpu,
DeviceIdManager::GetTfDevicesOnPlatform(device_gpu, platform_1));
EXPECT_THAT(tf_device_ids_gpu, IsEmpty());
TF_ASSERT_OK_AND_ASSIGN(
std::vector<TfDeviceId> tf_device_ids_xpu,
DeviceIdManager::GetTfDevicesOnPlatform(device_xpu, platform_1));
EXPECT_THAT(tf_device_ids_xpu, UnorderedElementsAre(tf_device_2));
}
}
} | 2,243 |
#ifndef XLA_TSL_FRAMEWORK_TRACKING_ALLOCATOR_H_
#define XLA_TSL_FRAMEWORK_TRACKING_ALLOCATOR_H_
#include <unordered_map>
#include "xla/tsl/framework/allocator.h"
#include "tsl/lib/gtl/inlined_vector.h"
#include "tsl/platform/mutex.h"
#include "tsl/platform/thread_annotations.h"
#include "tsl/platform/types.h"
namespace tsl {
struct AllocRecord {
AllocRecord(int64_t a_btyes, int64_t a_micros)
: alloc_bytes(a_btyes), alloc_micros(a_micros) {}
AllocRecord() : AllocRecord(0, 0) {}
int64_t alloc_bytes;
int64_t alloc_micros;
};
class TrackingAllocator : public Allocator {
public:
explicit TrackingAllocator(Allocator* allocator, bool track_ids);
std::string Name() override { return allocator_->Name(); }
void* AllocateRaw(size_t alignment, size_t num_bytes) override {
return AllocateRaw(alignment, num_bytes, AllocationAttributes());
}
void* AllocateRaw(size_t alignment, size_t num_bytes,
const AllocationAttributes& allocation_attr) override;
void DeallocateRaw(void* ptr) override;
bool TracksAllocationSizes() const override;
size_t RequestedSize(const void* ptr) const override;
size_t AllocatedSize(const void* ptr) const override;
int64_t AllocationId(const void* ptr) const override;
absl::optional<AllocatorStats> GetStats() override;
bool ClearStats() override;
AllocatorMemoryType GetMemoryType() const override {
return allocator_->GetMemoryType();
}
std::tuple<size_t, size_t, size_t> GetSizes();
absl::InlinedVector<AllocRecord, 4UL> GetRecordsAndUnRef();
absl::InlinedVector<AllocRecord, 4UL> GetCurrentRecords();
protected:
~TrackingAllocator() override {}
private:
bool UnRef() TF_EXCLUSIVE_LOCKS_REQUIRED(mu_);
Allocator* allocator_;
mutable mutex mu_;
int ref_ TF_GUARDED_BY(mu_);
size_t allocated_ TF_GUARDED_BY(mu_);
size_t high_watermark_ TF_GUARDED_BY(mu_);
size_t total_bytes_ TF_GUARDED_BY(mu_);
absl::InlinedVector<AllocRecord, 4UL> allocations_ TF_GUARDED_BY(mu_);
const bool track_sizes_locally_;
struct Chunk {
size_t requested_size;
size_t allocated_size;
int64_t allocation_id;
};
std::unordered_map<const void*, Chunk> in_use_ TF_GUARDED_BY(mu_);
int64_t next_allocation_id_ TF_GUARDED_BY(mu_);
};
}
#endif
#include "xla/tsl/framework/tracking_allocator.h"
#include "tsl/platform/env.h"
#include "tsl/platform/logging.h"
namespace tsl {
TrackingAllocator::TrackingAllocator(Allocator* allocator, bool track_sizes)
: allocator_(allocator),
ref_(1),
allocated_(0),
high_watermark_(0),
total_bytes_(0),
track_sizes_locally_(track_sizes && !allocator_->TracksAllocationSizes()),
next_allocation_id_(0) {}
void* TrackingAllocator::AllocateRaw(
size_t alignment, size_t num_bytes,
const AllocationAttributes& allocation_attr) {
void* ptr = allocator_->AllocateRaw(alignment, num_bytes, allocation_attr);
if (nullptr == ptr) {
return ptr;
}
if (allocator_->TracksAllocationSizes()) {
size_t allocated_bytes = allocator_->AllocatedSize(ptr);
{
mutex_lock lock(mu_);
allocated_ += allocated_bytes;
high_watermark_ = std::max(high_watermark_, allocated_);
total_bytes_ += allocated_bytes;
allocations_.emplace_back(allocated_bytes, Env::Default()->NowMicros());
++ref_;
}
} else if (track_sizes_locally_) {
size_t allocated_bytes = allocator_->AllocatedSizeSlow(ptr);
allocated_bytes = std::max(num_bytes, allocated_bytes);
mutex_lock lock(mu_);
next_allocation_id_ += 1;
Chunk chunk = {num_bytes, allocated_bytes, next_allocation_id_};
in_use_.emplace(std::make_pair(ptr, chunk));
allocated_ += allocated_bytes;
high_watermark_ = std::max(high_watermark_, allocated_);
total_bytes_ += allocated_bytes;
allocations_.emplace_back(allocated_bytes, Env::Default()->NowMicros());
++ref_;
} else {
mutex_lock lock(mu_);
total_bytes_ += num_bytes;
allocations_.emplace_back(num_bytes, Env::Default()->NowMicros());
++ref_;
}
return ptr;
}
void TrackingAllocator::DeallocateRaw(void* ptr) {
if (nullptr == ptr) {
return;
}
bool should_delete;
bool tracks_allocation_sizes = allocator_->TracksAllocationSizes();
size_t allocated_bytes = 0;
if (tracks_allocation_sizes) {
allocated_bytes = allocator_->AllocatedSize(ptr);
} else if (track_sizes_locally_) {
mutex_lock lock(mu_);
auto itr = in_use_.find(ptr);
if (itr != in_use_.end()) {
tracks_allocation_sizes = true;
allocated_bytes = (*itr).second.allocated_size;
in_use_.erase(itr);
}
}
Allocator* allocator = allocator_;
{
mutex_lock lock(mu_);
if (tracks_allocation_sizes) {
CHECK_GE(allocated_, allocated_bytes);
allocated_ -= allocated_bytes;
allocations_.emplace_back(-allocated_bytes, Env::Default()->NowMicros());
}
should_delete = UnRef();
}
allocator->DeallocateRaw(ptr);
if (should_delete) {
delete this;
}
}
bool TrackingAllocator::TracksAllocationSizes() const {
return track_sizes_locally_ || allocator_->TracksAllocationSizes();
}
size_t TrackingAllocator::RequestedSize(const void* ptr) const {
if (track_sizes_locally_) {
mutex_lock lock(mu_);
auto it = in_use_.find(ptr);
if (it != in_use_.end()) {
return (*it).second.requested_size;
}
return 0;
} else {
return allocator_->RequestedSize(ptr);
}
}
size_t TrackingAllocator::AllocatedSize(const void* ptr) const {
if (track_sizes_locally_) {
mutex_lock lock(mu_);
auto it = in_use_.find(ptr);
if (it != in_use_.end()) {
return (*it).second.allocated_size;
}
return 0;
} else {
return allocator_->AllocatedSize(ptr);
}
}
int64_t TrackingAllocator::AllocationId(const void* ptr) const {
if (track_sizes_locally_) {
mutex_lock lock(mu_);
auto it = in_use_.find(ptr);
if (it != in_use_.end()) {
return (*it).second.allocation_id;
}
return 0;
} else {
return allocator_->AllocationId(ptr);
}
}
absl::optional<AllocatorStats> TrackingAllocator::GetStats() {
return allocator_->GetStats();
}
bool TrackingAllocator::ClearStats() { return allocator_->ClearStats(); }
std::tuple<size_t, size_t, size_t> TrackingAllocator::GetSizes() {
size_t high_watermark;
size_t total_bytes;
size_t still_live_bytes;
{
mutex_lock lock(mu_);
high_watermark = high_watermark_;
total_bytes = total_bytes_;
still_live_bytes = allocated_;
}
return std::make_tuple(total_bytes, high_watermark, still_live_bytes);
}
absl::InlinedVector<AllocRecord, 4UL> TrackingAllocator::GetRecordsAndUnRef() {
bool should_delete;
absl::InlinedVector<AllocRecord, 4UL> allocations;
{
mutex_lock lock(mu_);
allocations.swap(allocations_);
should_delete = UnRef();
}
if (should_delete) {
delete this;
}
return allocations;
}
absl::InlinedVector<AllocRecord, 4UL> TrackingAllocator::GetCurrentRecords() {
absl::InlinedVector<AllocRecord, 4UL> allocations;
{
mutex_lock lock(mu_);
for (const AllocRecord& alloc : allocations_) {
allocations.push_back(alloc);
}
}
return allocations;
}
bool TrackingAllocator::UnRef() {
CHECK_GE(ref_, 1);
--ref_;
return (ref_ == 0);
}
} | #include "tensorflow/core/framework/tracking_allocator.h"
#include <unordered_map>
#include "tensorflow/core/framework/allocator.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/mem.h"
#include "tensorflow/core/platform/test.h"
namespace tensorflow {
class TestableSizeTrackingAllocator : public Allocator {
public:
string Name() override { return "test"; }
void* AllocateRaw(size_t , size_t num_bytes) override {
void* ptr = port::Malloc(num_bytes);
size_map_[ptr] = num_bytes;
return ptr;
}
void DeallocateRaw(void* ptr) override {
const auto& iter = size_map_.find(ptr);
EXPECT_NE(size_map_.end(), iter);
size_map_.erase(iter);
port::Free(ptr);
}
bool TracksAllocationSizes() const override { return true; }
size_t RequestedSize(const void* ptr) const override {
const auto& iter = size_map_.find(ptr);
EXPECT_NE(size_map_.end(), iter);
return iter->second;
}
absl::optional<AllocatorStats> GetStats() override { return absl::nullopt; }
private:
std::unordered_map<const void*, size_t> size_map_;
};
class NoMemoryAllocator : public Allocator {
public:
string Name() override { return "test"; }
void* AllocateRaw(size_t , size_t num_bytes) override {
return nullptr;
}
void DeallocateRaw(void* ptr) override {}
bool TracksAllocationSizes() const override { return true; }
absl::optional<AllocatorStats> GetStats() override { return absl::nullopt; }
};
TEST(TrackingAllocatorTest, SimpleNoTracking) {
Allocator* a = cpu_allocator();
EXPECT_FALSE(a->TracksAllocationSizes());
TrackingAllocator* ta = new TrackingAllocator(a, false);
void* p1 = ta->AllocateRaw(4, 4);
ta->DeallocateRaw(p1);
void* p2 = ta->AllocateRaw(4, 12);
std::tuple<size_t, size_t, size_t> sizes = ta->GetSizes();
EXPECT_EQ(16, std::get<0>(sizes));
EXPECT_EQ(0, std::get<1>(sizes));
EXPECT_EQ(0, std::get<2>(sizes));
ta->DeallocateRaw(p2);
auto records = ta->GetRecordsAndUnRef();
EXPECT_EQ(4, records[0].alloc_bytes);
EXPECT_EQ(12, records[1].alloc_bytes);
ta = new TrackingAllocator(a, true);
p1 = ta->AllocateRaw(4, 4);
EXPECT_EQ(4, ta->RequestedSize(p1));
EXPECT_LE(4, ta->AllocatedSize(p1));
EXPECT_EQ(1, ta->AllocationId(p1));
ta->DeallocateRaw(p1);
p2 = ta->AllocateRaw(4, 12);
EXPECT_EQ(12, ta->RequestedSize(p2));
EXPECT_LE(12, ta->AllocatedSize(p2));
EXPECT_EQ(2, ta->AllocationId(p2));
sizes = ta->GetSizes();
EXPECT_LE(16, std::get<0>(sizes));
EXPECT_LE(12, std::get<1>(sizes));
EXPECT_LE(12, std::get<2>(sizes));
ta->DeallocateRaw(p2);
records = ta->GetRecordsAndUnRef();
EXPECT_LE(4, records[0].alloc_bytes);
EXPECT_GE(-4, records[1].alloc_bytes);
EXPECT_LE(12, records[2].alloc_bytes);
EXPECT_GE(-12, records[3].alloc_bytes);
}
TEST(TrackingAllocatorTest, SimpleTracking) {
TestableSizeTrackingAllocator a = TestableSizeTrackingAllocator();
EXPECT_TRUE(a.TracksAllocationSizes());
TrackingAllocator* ta = new TrackingAllocator(&a, false);
void* p1 = ta->AllocateRaw(4, 12);
ta->DeallocateRaw(p1);
void* p2 = ta->AllocateRaw(4, 4);
std::tuple<size_t, size_t, size_t> sizes = ta->GetSizes();
EXPECT_EQ(16, std::get<0>(sizes));
EXPECT_EQ(12, std::get<1>(sizes));
EXPECT_EQ(4, std::get<2>(sizes));
ta->DeallocateRaw(p2);
auto records = ta->GetRecordsAndUnRef();
EXPECT_EQ(12, records[0].alloc_bytes);
EXPECT_EQ(-12, records[1].alloc_bytes);
EXPECT_EQ(4, records[2].alloc_bytes);
EXPECT_EQ(-4, records[3].alloc_bytes);
}
TEST(TrackingAllocatorTest, OutOfMemory) {
NoMemoryAllocator a;
EXPECT_TRUE(a.TracksAllocationSizes());
TrackingAllocator* ta = new TrackingAllocator(&a, false);
void* p1 = ta->AllocateRaw(4, 12);
EXPECT_EQ(nullptr, p1);
std::tuple<size_t, size_t, size_t> sizes = ta->GetSizes();
EXPECT_EQ(0, std::get<0>(sizes));
EXPECT_EQ(0, std::get<1>(sizes));
EXPECT_EQ(0, std::get<2>(sizes));
EXPECT_EQ(0, ta->GetRecordsAndUnRef().size());
}
TEST(TrackingAllocatorTest, FreeNullPtr) {
NoMemoryAllocator a;
EXPECT_TRUE(a.TracksAllocationSizes());
TrackingAllocator* ta = new TrackingAllocator(&a, false);
ta->DeallocateRaw(nullptr);
std::tuple<size_t, size_t, size_t> sizes = ta->GetSizes();
EXPECT_EQ(0, std::get<0>(sizes));
EXPECT_EQ(0, std::get<1>(sizes));
EXPECT_EQ(0, std::get<2>(sizes));
EXPECT_EQ(0, ta->GetRecordsAndUnRef().size());
}
} | 2,244 |
#ifndef XLA_TSL_FRAMEWORK_CANCELLATION_H_
#define XLA_TSL_FRAMEWORK_CANCELLATION_H_
#include <atomic>
#include <functional>
#include "tsl/lib/gtl/flatmap.h"
#include "tsl/platform/hash.h"
#include "tsl/platform/mutex.h"
#include "tsl/platform/notification.h"
#include "tsl/platform/status.h"
#include "tsl/platform/stringpiece.h"
#include "tsl/platform/thread_annotations.h"
#include "tsl/platform/types.h"
namespace tsl {
typedef int64_t CancellationToken;
typedef std::function<void()> CancelCallback;
class CancellationManager {
public:
static const CancellationToken kInvalidToken;
CancellationManager();
explicit CancellationManager(CancellationManager* parent);
~CancellationManager();
void StartCancel();
void StartCancelWithStatus(const absl::Status& status);
bool IsCancelled() { return is_cancelled_.load(std::memory_order_acquire); }
CancellationToken get_cancellation_token() {
return next_cancellation_token_.fetch_add(1);
}
bool RegisterCallback(CancellationToken token, CancelCallback callback);
bool RegisterCallbackWithErrorLogging(CancellationToken token,
CancelCallback callback,
tsl::StringPiece callback_name);
bool DeregisterCallback(CancellationToken token);
bool TryDeregisterCallback(CancellationToken token);
bool IsCancelling();
private:
struct CallbackConfiguration {
CancelCallback callback;
std::string name;
bool log_error = false;
};
struct State {
Notification cancelled_notification;
gtl::FlatMap<CancellationToken, CallbackConfiguration> callbacks;
CancellationManager* first_child = nullptr;
};
bool RegisterCallbackConfig(CancellationToken token,
CallbackConfiguration config);
bool RegisterChild(CancellationManager* child);
void DeregisterChild(CancellationManager* child);
bool is_cancelling_;
std::atomic_bool is_cancelled_;
std::atomic<CancellationToken> next_cancellation_token_;
CancellationManager* const parent_ = nullptr;
bool is_removed_from_parent_ TF_GUARDED_BY(parent_->mu_) = false;
CancellationManager* prev_sibling_ TF_GUARDED_BY(parent_->mu_) =
nullptr;
CancellationManager* next_sibling_ TF_GUARDED_BY(parent_->mu_) =
nullptr;
mutex mu_;
std::unique_ptr<State> state_ TF_GUARDED_BY(mu_);
};
absl::Status RegisterCancellationCallback(
CancellationManager* cancellation_manager, std::function<void()> callback,
std::function<void()>* deregister_fn);
}
#endif
#include "xla/tsl/framework/cancellation.h"
#include <forward_list>
#include "absl/memory/memory.h"
#include "tsl/platform/errors.h"
#include "tsl/platform/logging.h"
#include "tsl/platform/status.h"
namespace tsl {
const CancellationToken CancellationManager::kInvalidToken = -1;
CancellationManager::CancellationManager()
: is_cancelling_(false),
is_cancelled_(false),
next_cancellation_token_(0) {}
CancellationManager::CancellationManager(CancellationManager* parent)
: is_cancelling_(false), next_cancellation_token_(0), parent_(parent) {
is_cancelled_ = parent->RegisterChild(this);
}
void CancellationManager::StartCancel() {
StartCancelWithStatus(absl::OkStatus());
}
void CancellationManager::StartCancelWithStatus(const absl::Status& status) {
gtl::FlatMap<CancellationToken, CallbackConfiguration> callbacks_to_run;
std::forward_list<CancellationManager*> children_to_cancel;
Notification* cancelled_notification = nullptr;
{
mutex_lock l(mu_);
if (is_cancelled_.load(std::memory_order_relaxed) || is_cancelling_) {
return;
}
is_cancelling_ = true;
if (state_) {
std::swap(state_->callbacks, callbacks_to_run);
CancellationManager* child = state_->first_child;
while (child != nullptr) {
children_to_cancel.push_front(child);
child->is_removed_from_parent_ = true;
child = child->next_sibling_;
}
state_->first_child = nullptr;
cancelled_notification = &state_->cancelled_notification;
}
}
for (auto key_and_value : callbacks_to_run) {
CallbackConfiguration& config = key_and_value.second;
if (!status.ok() && config.log_error) {
LOG(WARNING) << "Cancellation callback \"" << config.name
<< "\" is triggered due to a "
<< (StatusGroup::IsDerived(status) ? "derived" : "root")
<< " error: " << status.ToString();
}
config.callback();
}
for (CancellationManager* child : children_to_cancel) {
child->StartCancelWithStatus(status);
}
{
mutex_lock l(mu_);
is_cancelling_ = false;
is_cancelled_.store(true, std::memory_order_release);
}
if (cancelled_notification) {
cancelled_notification->Notify();
}
}
bool CancellationManager::RegisterCallback(CancellationToken token,
CancelCallback callback) {
return RegisterCallbackConfig(
token, CallbackConfiguration{callback, "", false});
}
bool CancellationManager::RegisterCallbackWithErrorLogging(
CancellationToken token, CancelCallback callback,
tsl::StringPiece callback_name) {
return RegisterCallbackConfig(
token, CallbackConfiguration{callback, std::string(callback_name), true});
}
bool CancellationManager::RegisterCallbackConfig(CancellationToken token,
CallbackConfiguration config) {
DCHECK_LT(token, next_cancellation_token_) << "Invalid cancellation token";
mutex_lock l(mu_);
bool should_register = !is_cancelled_ && !is_cancelling_;
if (should_register) {
if (!state_) {
state_ = absl::make_unique<State>();
}
std::swap(state_->callbacks[token], config);
}
return should_register;
}
bool CancellationManager::DeregisterCallback(CancellationToken token) {
mu_.lock();
if (is_cancelled_) {
mu_.unlock();
return false;
} else if (is_cancelling_) {
Notification* cancelled_notification =
state_ ? &state_->cancelled_notification : nullptr;
mu_.unlock();
if (cancelled_notification) {
cancelled_notification->WaitForNotification();
}
return false;
} else {
if (state_) {
state_->callbacks.erase(token);
}
mu_.unlock();
return true;
}
}
bool CancellationManager::RegisterChild(CancellationManager* child) {
mutex_lock l(mu_);
if (is_cancelled_.load(std::memory_order_relaxed) || is_cancelling_) {
child->is_removed_from_parent_ = true;
return true;
}
if (!state_) {
state_ = absl::make_unique<State>();
}
CancellationManager* current_head = state_->first_child;
state_->first_child = child;
child->prev_sibling_ = nullptr;
child->next_sibling_ = current_head;
if (current_head) {
current_head->prev_sibling_ = child;
}
return false;
}
void CancellationManager::DeregisterChild(CancellationManager* child) {
DCHECK_EQ(child->parent_, this);
Notification* cancelled_notification = nullptr;
{
mutex_lock l(mu_);
if (!child->is_removed_from_parent_) {
DCHECK(state_);
if (child->prev_sibling_ == nullptr) {
DCHECK_EQ(state_->first_child, child);
state_->first_child = child->next_sibling_;
} else {
child->prev_sibling_->next_sibling_ = child->next_sibling_;
}
if (child->next_sibling_ != nullptr) {
child->next_sibling_->prev_sibling_ = child->prev_sibling_;
}
child->is_removed_from_parent_ = true;
}
if (is_cancelling_) {
cancelled_notification = &state_->cancelled_notification;
}
}
if (cancelled_notification) {
cancelled_notification->WaitForNotification();
}
}
bool CancellationManager::TryDeregisterCallback(CancellationToken token) {
mutex_lock lock(mu_);
if (is_cancelled_ || is_cancelling_) {
return false;
} else {
if (state_) {
state_->callbacks.erase(token);
}
return true;
}
}
CancellationManager::~CancellationManager() {
if (parent_) {
parent_->DeregisterChild(this);
}
if (state_) {
StartCancel();
}
}
bool CancellationManager::IsCancelling() {
mutex_lock lock(mu_);
return is_cancelling_;
}
absl::Status RegisterCancellationCallback(
CancellationManager* cancellation_manager, CancelCallback callback,
std::function<void()>* deregister_fn) {
if (cancellation_manager) {
CancellationToken token = cancellation_manager->get_cancellation_token();
if (!cancellation_manager->RegisterCallback(token, std::move(callback))) {
return errors::Cancelled("Operation was cancelled");
}
*deregister_fn = [cancellation_manager, token]() {
cancellation_manager->DeregisterCallback(token);
};
} else {
VLOG(1) << "Cancellation manager is not set. Cancellation callback will "
"not be registered.";
*deregister_fn = []() {};
}
return absl::OkStatus();
}
} | #include "xla/tsl/framework/cancellation.h"
#include <algorithm>
#include <memory>
#include <numeric>
#include <random>
#include <vector>
#include "tsl/platform/notification.h"
#include "tsl/platform/status.h"
#include "tsl/platform/test.h"
#include "tsl/platform/threadpool.h"
namespace tsl {
TEST(Cancellation, SimpleNoCancel) {
bool is_cancelled = false;
CancellationManager* manager = new CancellationManager();
auto token = manager->get_cancellation_token();
bool registered = manager->RegisterCallback(
token, [&is_cancelled]() { is_cancelled = true; });
EXPECT_TRUE(registered);
bool deregistered = manager->DeregisterCallback(token);
EXPECT_TRUE(deregistered);
delete manager;
EXPECT_FALSE(is_cancelled);
}
TEST(Cancellation, SimpleCancel) {
bool is_cancelled = false;
CancellationManager* manager = new CancellationManager();
auto token = manager->get_cancellation_token();
bool registered = manager->RegisterCallback(
token, [&is_cancelled]() { is_cancelled = true; });
EXPECT_TRUE(registered);
manager->StartCancel();
EXPECT_TRUE(is_cancelled);
delete manager;
}
TEST(Cancellation, StartCancelTriggersAllCallbacks) {
bool is_cancelled_1 = false;
bool is_cancelled_2 = false;
auto manager = std::make_unique<CancellationManager>();
auto token_1 = manager->get_cancellation_token();
EXPECT_TRUE(manager->RegisterCallbackWithErrorLogging(
token_1, [&is_cancelled_1]() { is_cancelled_1 = true; }, "TestCallback"));
auto token_2 = manager->get_cancellation_token();
EXPECT_TRUE(manager->RegisterCallback(
token_2, [&is_cancelled_2]() { is_cancelled_2 = true; }));
manager->StartCancel();
EXPECT_TRUE(is_cancelled_1);
EXPECT_TRUE(is_cancelled_2);
}
TEST(Cancellation, StartCancelWithStatusTriggersAllCallbacks) {
bool is_cancelled_1 = false;
bool is_cancelled_2 = false;
auto manager = std::make_unique<CancellationManager>();
auto token_1 = manager->get_cancellation_token();
EXPECT_TRUE(manager->RegisterCallbackWithErrorLogging(
token_1, [&is_cancelled_1]() { is_cancelled_1 = true; }, "TestCallback"));
auto token_2 = manager->get_cancellation_token();
EXPECT_TRUE(manager->RegisterCallback(
token_2, [&is_cancelled_2]() { is_cancelled_2 = true; }));
manager->StartCancelWithStatus(absl::OkStatus());
EXPECT_TRUE(is_cancelled_1);
EXPECT_TRUE(is_cancelled_2);
}
TEST(Cancellation, CancelBeforeRegister) {
auto manager = std::make_unique<CancellationManager>();
auto token = manager->get_cancellation_token();
manager->StartCancel();
bool registered = manager->RegisterCallback(token, nullptr);
EXPECT_FALSE(registered);
}
TEST(Cancellation, DeregisterAfterCancel) {
bool is_cancelled = false;
auto manager = std::make_unique<CancellationManager>();
auto token = manager->get_cancellation_token();
bool registered = manager->RegisterCallback(
token, [&is_cancelled]() { is_cancelled = true; });
EXPECT_TRUE(registered);
manager->StartCancel();
EXPECT_TRUE(is_cancelled);
bool deregistered = manager->DeregisterCallback(token);
EXPECT_FALSE(deregistered);
}
TEST(Cancellation, CancelMultiple) {
bool is_cancelled_1 = false, is_cancelled_2 = false, is_cancelled_3 = false;
auto manager = std::make_unique<CancellationManager>();
auto token_1 = manager->get_cancellation_token();
bool registered_1 = manager->RegisterCallback(
token_1, [&is_cancelled_1]() { is_cancelled_1 = true; });
EXPECT_TRUE(registered_1);
auto token_2 = manager->get_cancellation_token();
bool registered_2 = manager->RegisterCallback(
token_2, [&is_cancelled_2]() { is_cancelled_2 = true; });
EXPECT_TRUE(registered_2);
EXPECT_FALSE(is_cancelled_1);
EXPECT_FALSE(is_cancelled_2);
manager->StartCancel();
EXPECT_TRUE(is_cancelled_1);
EXPECT_TRUE(is_cancelled_2);
EXPECT_FALSE(is_cancelled_3);
auto token_3 = manager->get_cancellation_token();
bool registered_3 = manager->RegisterCallback(
token_3, [&is_cancelled_3]() { is_cancelled_3 = true; });
EXPECT_FALSE(registered_3);
EXPECT_FALSE(is_cancelled_3);
}
TEST(Cancellation, IsCancelled) {
auto cm = std::make_unique<CancellationManager>();
thread::ThreadPool w(Env::Default(), "test", 4);
std::vector<Notification> done(8);
for (size_t i = 0; i < done.size(); ++i) {
Notification* n = &done[i];
w.Schedule([n, &cm]() {
while (!cm->IsCancelled()) {
}
ASSERT_FALSE(cm->IsCancelling());
n->Notify();
});
}
Env::Default()->SleepForMicroseconds(1000000 );
cm->StartCancel();
for (size_t i = 0; i < done.size(); ++i) {
done[i].WaitForNotification();
}
}
TEST(Cancellation, IsCancelling) {
CancellationManager cm;
Notification started_cancelling;
Notification can_finish_cancel;
Notification cancel_done;
thread::ThreadPool w(Env::Default(), "test", 1);
auto token = cm.get_cancellation_token();
ASSERT_TRUE(
cm.RegisterCallback(token, [&started_cancelling, &can_finish_cancel]() {
started_cancelling.Notify();
can_finish_cancel.WaitForNotification();
}));
w.Schedule([&cm, &cancel_done]() {
cm.StartCancel();
cancel_done.Notify();
});
started_cancelling.WaitForNotification();
ASSERT_TRUE(cm.IsCancelling());
can_finish_cancel.Notify();
cancel_done.WaitForNotification();
ASSERT_FALSE(cm.IsCancelling());
ASSERT_TRUE(cm.IsCancelled());
}
TEST(Cancellation, TryDeregisterWithoutCancel) {
bool is_cancelled = false;
auto manager = std::make_unique<CancellationManager>();
auto token = manager->get_cancellation_token();
bool registered = manager->RegisterCallback(
token, [&is_cancelled]() { is_cancelled = true; });
EXPECT_TRUE(registered);
bool deregistered = manager->TryDeregisterCallback(token);
EXPECT_TRUE(deregistered);
EXPECT_FALSE(is_cancelled);
}
TEST(Cancellation, TryDeregisterAfterCancel) {
bool is_cancelled = false;
auto manager = std::make_unique<CancellationManager>();
auto token = manager->get_cancellation_token();
bool registered = manager->RegisterCallback(
token, [&is_cancelled]() { is_cancelled = true; });
EXPECT_TRUE(registered);
manager->StartCancel();
EXPECT_TRUE(is_cancelled);
bool deregistered = manager->TryDeregisterCallback(token);
EXPECT_FALSE(deregistered);
}
TEST(Cancellation, TryDeregisterDuringCancel) {
Notification cancel_started, finish_callback, cancel_complete;
auto manager = std::make_unique<CancellationManager>();
auto token = manager->get_cancellation_token();
bool registered = manager->RegisterCallback(token, [&]() {
cancel_started.Notify();
finish_callback.WaitForNotification();
});
EXPECT_TRUE(registered);
thread::ThreadPool w(Env::Default(), "test", 1);
w.Schedule([&]() {
manager->StartCancel();
cancel_complete.Notify();
});
cancel_started.WaitForNotification();
bool deregistered = manager->TryDeregisterCallback(token);
EXPECT_FALSE(deregistered);
finish_callback.Notify();
cancel_complete.WaitForNotification();
}
TEST(Cancellation, Parent_CancelManyChildren) {
CancellationManager parent;
std::vector<std::unique_ptr<CancellationManager>> children;
for (size_t i = 0; i < 5; ++i) {
children.push_back(absl::make_unique<CancellationManager>(&parent));
EXPECT_FALSE(children.back()->IsCancelled());
}
parent.StartCancel();
for (auto& child : children) {
EXPECT_TRUE(child->IsCancelled());
}
}
TEST(Cancellation, Parent_NotCancelled) {
CancellationManager parent;
{
CancellationManager child(&parent);
child.StartCancel();
EXPECT_TRUE(child.IsCancelled());
}
EXPECT_FALSE(parent.IsCancelled());
}
TEST(Cancellation, Parent_AlreadyCancelled) {
CancellationManager parent;
parent.StartCancel();
EXPECT_TRUE(parent.IsCancelled());
CancellationManager child(&parent);
EXPECT_TRUE(child.IsCancelled());
}
TEST(Cancellation, Parent_RandomDestructionOrder) {
CancellationManager parent;
std::random_device rd;
std::mt19937 g(rd());
for (int rounds = 0; rounds < 100; ++rounds) {
std::vector<std::unique_ptr<CancellationManager>> children;
std::uniform_int_distribution<int> dist(1, 9);
const size_t round_size = dist(rd);
for (size_t i = 0; i < round_size; ++i) {
children.push_back(absl::make_unique<CancellationManager>(&parent));
EXPECT_FALSE(children.back()->IsCancelled());
}
std::vector<size_t> destruction_order(round_size);
std::iota(destruction_order.begin(), destruction_order.end(), 0);
std::shuffle(destruction_order.begin(), destruction_order.end(), g);
for (size_t index : destruction_order) {
children[index].reset();
}
}
}
} | 2,245 |
#ifndef XLA_TSL_FRAMEWORK_DEVICE_ID_UTILS_H_
#define XLA_TSL_FRAMEWORK_DEVICE_ID_UTILS_H_
#include <string>
#include <vector>
#include "absl/container/flat_hash_map.h"
#include "xla/tsl/framework/device_id.h"
#include "xla/tsl/framework/device_type.h"
#include "xla/tsl/util/device_name_utils.h"
#include "tsl/platform/status.h"
#include "tsl/platform/statusor.h"
namespace tsl {
void CheckValidTfDeviceId(const DeviceType& type, int visible_device_count,
TfDeviceId tf_device_id);
absl::Status ParseVisibleDeviceList(
const std::string& visible_device_list, int visible_device_count,
std::vector<PlatformDeviceId>* visible_device_order);
absl::StatusOr<size_t> GetNumberTfDevicesAndConfigurePlatformDeviceId(
const absl::flat_hash_map<std::string, int64_t>&
session_option_device_counts,
absl::string_view device_type, absl::string_view visible_device_list,
int visible_device_count);
absl::StatusOr<int> GetPlatformDeviceIdFromDeviceParsedName(
const DeviceNameUtils::ParsedName& device_name,
const DeviceType& device_type);
absl::StatusOr<int> GetDeviceIdFromDeviceParsedName(
const DeviceNameUtils::ParsedName& device_name,
const DeviceType& device_type);
}
#endif
#include "xla/tsl/framework/device_id_utils.h"
#include <numeric>
#include <set>
#include <string>
#include <vector>
#include "absl/container/flat_hash_map.h"
#include "absl/status/status.h"
#include "absl/strings/numbers.h"
#include "xla/tsl/framework/device_id.h"
#include "xla/tsl/framework/device_id_manager.h"
#include "tsl/platform/errors.h"
#include "tsl/platform/str_util.h"
namespace tsl {
namespace {
int GetTfDeviceIdFromDeviceParsedName(
const DeviceNameUtils::ParsedName& device_name) {
return device_name.id;
}
}
void CheckValidTfDeviceId(const DeviceType& type,
const int visible_device_count,
const TfDeviceId tf_device_id) {
PlatformDeviceId platform_device_id;
TF_CHECK_OK(DeviceIdManager::TfToPlatformDeviceId(type, tf_device_id,
&platform_device_id));
CHECK_LT(platform_device_id.value(), visible_device_count)
<< "platform_device_id is outside discovered device range."
<< " TF " << type << " id: " << tf_device_id << ", platform " << type
<< " id: " << platform_device_id
<< ", visible device count: " << visible_device_count;
}
absl::Status ParseVisibleDeviceList(
const std::string& visible_device_list, const int visible_device_count,
std::vector<PlatformDeviceId>* visible_device_order) {
visible_device_order->clear();
if (visible_device_list.empty()) {
visible_device_order->resize(visible_device_count);
std::iota(visible_device_order->begin(), visible_device_order->end(), 0);
} else {
const std::vector<std::string> order_str =
tsl::str_util::Split(visible_device_list, ',');
for (const std::string& platform_device_id_str : order_str) {
int32_t platform_device_id;
if (!absl::SimpleAtoi(platform_device_id_str, &platform_device_id)) {
return tsl::errors::InvalidArgument(
"Could not parse entry in 'visible_device_list': '",
platform_device_id_str,
"'. visible_device_list = ", visible_device_list);
}
if (platform_device_id < 0 ||
platform_device_id >= visible_device_count) {
return tsl::errors::InvalidArgument(
"'visible_device_list' listed an invalid Device id '",
platform_device_id, "' but visible device count is ",
visible_device_count);
}
visible_device_order->push_back(
tsl::PlatformDeviceId(platform_device_id));
}
}
std::set<PlatformDeviceId> visible_device_set(visible_device_order->begin(),
visible_device_order->end());
if (visible_device_set.size() != visible_device_order->size()) {
return tsl::errors::InvalidArgument(
"visible_device_list contained a duplicate entry: ",
visible_device_list);
}
return absl::OkStatus();
}
absl::StatusOr<size_t> GetNumberTfDevicesAndConfigurePlatformDeviceId(
const absl::flat_hash_map<std::string, int64_t>&
session_option_device_counts,
absl::string_view device_type, absl::string_view visible_device_list,
const int visible_device_count) {
size_t num_tf_devices = INT_MAX;
const auto iter = session_option_device_counts.find(device_type);
if (iter != session_option_device_counts.end()) {
num_tf_devices = iter->second;
}
if (num_tf_devices == 0) {
return 0;
}
std::vector<PlatformDeviceId> visible_device_order;
TF_RETURN_IF_ERROR(ParseVisibleDeviceList(std::string(visible_device_list),
visible_device_count,
&visible_device_order));
if (num_tf_devices > visible_device_order.size()) {
num_tf_devices = visible_device_order.size();
}
for (int i = 0; i < num_tf_devices; ++i) {
const PlatformDeviceId platform_device_id = visible_device_order[i];
const TfDeviceId tf_device_id(i);
TF_RETURN_IF_ERROR(tsl::DeviceIdManager::InsertTfPlatformDeviceIdPair(
DeviceType(device_type), tf_device_id, platform_device_id));
}
return num_tf_devices;
}
absl::StatusOr<int> GetPlatformDeviceIdFromDeviceParsedName(
const DeviceNameUtils::ParsedName& device_name,
const DeviceType& device_type) {
const TfDeviceId tf_device_id(GetTfDeviceIdFromDeviceParsedName(device_name));
PlatformDeviceId platform_device_id;
absl::Status platform_id_status = DeviceIdManager::TfToPlatformDeviceId(
device_type, tf_device_id, &platform_device_id);
if (platform_id_status.ok()) {
return platform_device_id.value();
}
return platform_id_status;
}
absl::StatusOr<int> GetDeviceIdFromDeviceParsedName(
const DeviceNameUtils::ParsedName& device_name,
const DeviceType& device_type) {
auto platform_id =
GetPlatformDeviceIdFromDeviceParsedName(device_name, device_type);
if (platform_id.ok()) {
return *platform_id;
}
return GetTfDeviceIdFromDeviceParsedName(device_name);
}
} | #include "xla/tsl/framework/device_id_utils.h"
#include <string_view>
#include <vector>
#include "xla/tsl/framework/device_id_manager.h"
#include "xla/tsl/util/device_name_utils.h"
#include "tsl/lib/core/status_test_util.h"
#include "tsl/platform/status_matchers.h"
namespace tsl {
namespace {
using ::testing::HasSubstr;
using ::tsl::testing::StatusIs;
constexpr std::string_view kTestDeviceType = "CPU";
PlatformDeviceId TfToPlatformDeviceId(TfDeviceId tf_device_id) {
PlatformDeviceId platform_device_id;
TF_CHECK_OK(DeviceIdManager::TfToPlatformDeviceId(
DeviceType(kTestDeviceType), tf_device_id, &platform_device_id));
return platform_device_id;
}
TEST(DeviceIdUtilsTest, CheckValidTfDeviceIdPass) {
TfDeviceId tf_device_id(0);
PlatformDeviceId platform_device_id(1);
TF_EXPECT_OK(DeviceIdManager::InsertTfPlatformDeviceIdPair(
DeviceType(kTestDeviceType), tf_device_id, platform_device_id));
tsl::CheckValidTfDeviceId("CPU", 2, tf_device_id);
DeviceIdManager::TestOnlyReset();
}
TEST(DeviceIdUtilsTest, CheckValidTfDeviceIdNotFound) {
TfDeviceId tf_device_id(0);
EXPECT_DEATH(
tsl::CheckValidTfDeviceId(DeviceType(kTestDeviceType),
2, tf_device_id),
"NOT_FOUND: TensorFlow device CPU:0 was not registered");
}
TEST(DeviceIdUtilsTest, CheckValidTfDeviceIdOutsideVisibleDeviceRange) {
TfDeviceId tf_device_id(0);
PlatformDeviceId platform_device_id(1);
TF_EXPECT_OK(DeviceIdManager::InsertTfPlatformDeviceIdPair(
DeviceType(kTestDeviceType), tf_device_id, platform_device_id));
EXPECT_DEATH(tsl::CheckValidTfDeviceId("CPU", 1,
tf_device_id),
"platform_device_id is outside discovered device range.");
DeviceIdManager::TestOnlyReset();
}
TEST(DeviceIdUtilsTest, ParseEmptyVisibleDeviceList) {
std::vector<PlatformDeviceId> visible_device_order;
TF_EXPECT_OK(ParseVisibleDeviceList("", 2, &visible_device_order));
PlatformDeviceId platform_device_id0(0), platform_device_id1(1);
std::vector<PlatformDeviceId> expected = {platform_device_id0,
platform_device_id1};
EXPECT_EQ(visible_device_order, expected);
}
TEST(DeviceIdUtilsTest, ParseVisibleDeviceList) {
std::vector<PlatformDeviceId> visible_device_order;
TF_EXPECT_OK(ParseVisibleDeviceList("2,1", 3, &visible_device_order));
PlatformDeviceId platform_device_id2(2), platform_device_id1(1);
std::vector<PlatformDeviceId> expected = {platform_device_id2,
platform_device_id1};
EXPECT_EQ(visible_device_order, expected);
}
TEST(DeviceIdUtilsTest, ParseInvalidVisibleDeviceList) {
std::vector<PlatformDeviceId> visible_device_order;
EXPECT_THAT(
ParseVisibleDeviceList("3,1", 3, &visible_device_order),
StatusIs(tensorflow::error::INVALID_ARGUMENT,
HasSubstr("'visible_device_list' listed an invalid Device id "
"'3' but visible device count is 3")));
}
TEST(DeviceIdUtilsTest, ParseDuplicateVisibleDeviceList) {
std::vector<PlatformDeviceId> visible_device_order;
EXPECT_THAT(
ParseVisibleDeviceList("1,1", 3, &visible_device_order),
StatusIs(
tensorflow::error::INVALID_ARGUMENT,
HasSubstr("visible_device_list contained a duplicate entry: 1,1")));
}
TEST(DeviceIdUtilsTest, GetNumberTfDevicesDefault) {
TF_ASSERT_OK_AND_ASSIGN(size_t num_tf_device,
GetNumberTfDevicesAndConfigurePlatformDeviceId(
{}, kTestDeviceType, "", 2));
EXPECT_EQ(num_tf_device, 2);
TfDeviceId tf_device_id_0(0);
PlatformDeviceId expected_0(0);
EXPECT_EQ(expected_0, TfToPlatformDeviceId(tf_device_id_0));
TfDeviceId tf_device_id_1(1);
PlatformDeviceId expected_1(1);
EXPECT_EQ(expected_1, TfToPlatformDeviceId(tf_device_id_1));
DeviceIdManager::TestOnlyReset();
}
TEST(DeviceIdUtilsTest, GetNumberTfDevicesWithVisibleDeviceList) {
TF_ASSERT_OK_AND_ASSIGN(size_t num_tf_device,
GetNumberTfDevicesAndConfigurePlatformDeviceId(
{}, kTestDeviceType, "2,0", 3));
EXPECT_EQ(num_tf_device, 2);
TfDeviceId tf_device_id_0(0);
PlatformDeviceId expected_2(2);
EXPECT_EQ(expected_2, TfToPlatformDeviceId(tf_device_id_0));
TfDeviceId tf_device_id_1(1);
PlatformDeviceId expected_0(0);
EXPECT_EQ(expected_0, TfToPlatformDeviceId(tf_device_id_1));
DeviceIdManager::TestOnlyReset();
}
TEST(DeviceIdUtilsTest, GetNumberTfDevicesWithSessionOptionDeviceCount) {
TF_ASSERT_OK_AND_ASSIGN(
size_t num_tf_device,
GetNumberTfDevicesAndConfigurePlatformDeviceId(
{{std::string(kTestDeviceType), 2}}, kTestDeviceType, "1,0,2", 3));
EXPECT_EQ(num_tf_device, 2);
TfDeviceId tf_device_id_0(0);
PlatformDeviceId expected_1(1);
EXPECT_EQ(expected_1, TfToPlatformDeviceId(tf_device_id_0));
TfDeviceId tf_device_id_1(1);
PlatformDeviceId expected_0(0);
EXPECT_EQ(expected_0, TfToPlatformDeviceId(tf_device_id_1));
DeviceIdManager::TestOnlyReset();
}
TEST(DeviceIdUtilsTest, GetPlatformDeviceId) {
TfDeviceId tf_device_id(0);
PlatformDeviceId platform_device_id(1);
TF_EXPECT_OK(DeviceIdManager::InsertTfPlatformDeviceIdPair(
DeviceType(kTestDeviceType), tf_device_id, platform_device_id));
DeviceNameUtils::ParsedName device_name;
device_name.id = 0;
TF_ASSERT_OK_AND_ASSIGN(int device_id,
GetPlatformDeviceIdFromDeviceParsedName(
device_name, DeviceType(kTestDeviceType)));
EXPECT_EQ(device_id, 1);
DeviceIdManager::TestOnlyReset();
}
TEST(DeviceIdUtilsTest, GetPlatformDeviceIdNotFound) {
DeviceNameUtils::ParsedName device_name;
device_name.id = 0;
EXPECT_THAT(
GetPlatformDeviceIdFromDeviceParsedName(device_name,
DeviceType(kTestDeviceType)),
StatusIs(tensorflow::error::NOT_FOUND,
HasSubstr("TensorFlow device CPU:0 was not registered")));
}
TEST(DeviceIdUtilsTest, GetDeviceIdWithPlatformDeviceId) {
TfDeviceId tf_device_id(0);
PlatformDeviceId platform_device_id(1);
TF_EXPECT_OK(DeviceIdManager::InsertTfPlatformDeviceIdPair(
DeviceType(kTestDeviceType), tf_device_id, platform_device_id));
DeviceNameUtils::ParsedName device_name;
device_name.id = 0;
TF_ASSERT_OK_AND_ASSIGN(int device_id,
GetDeviceIdFromDeviceParsedName(
device_name, DeviceType(kTestDeviceType)));
EXPECT_EQ(device_id, 1);
DeviceIdManager::TestOnlyReset();
}
TEST(DeviceIdUtilsTest, GetDeviceIdWithoutPlatformDeviceId) {
DeviceNameUtils::ParsedName device_name;
device_name.id = 0;
TF_ASSERT_OK_AND_ASSIGN(int device_id,
GetDeviceIdFromDeviceParsedName(
device_name, DeviceType(kTestDeviceType)));
EXPECT_EQ(device_id, 0);
}
}
} | 2,246 |
#ifndef XLA_TSL_FRAMEWORK_ALLOCATOR_H_
#define XLA_TSL_FRAMEWORK_ALLOCATOR_H_
#include <stdlib.h>
#include <functional>
#include <limits>
#include <optional>
#include "absl/strings/string_view.h"
#include "absl/types/optional.h"
#include "xla/tsl/framework/numeric_types.h"
#include "xla/tsl/framework/type_traits.h"
#include "tsl/platform/logging.h"
#include "tsl/platform/macros.h"
#include "tsl/platform/numa.h"
#include "tsl/platform/types.h"
namespace tsl {
struct AllocationAttributes {
AllocationAttributes() = default;
AllocationAttributes(bool retry_on_failure, bool allocation_will_be_logged,
std::function<uint64()>* freed_by_func)
: retry_on_failure(retry_on_failure),
allocation_will_be_logged(allocation_will_be_logged),
freed_by_func(freed_by_func) {}
bool retry_on_failure = true;
bool allocation_will_be_logged = false;
std::function<uint64()>* freed_by_func = nullptr;
AllocationAttributes(const AllocationAttributes&) = delete;
void operator=(const AllocationAttributes&) = delete;
};
struct AllocatorStats {
int64_t num_allocs;
int64_t bytes_in_use;
int64_t peak_bytes_in_use;
int64_t largest_alloc_size;
std::optional<int64_t> bytes_limit;
int64_t bytes_reserved;
int64_t peak_bytes_reserved;
std::optional<int64_t> bytes_reservable_limit;
int64_t largest_free_block_bytes;
std::optional<int64_t> pool_bytes;
std::optional<int64_t> peak_pool_bytes;
AllocatorStats()
: num_allocs(0),
bytes_in_use(0),
peak_bytes_in_use(0),
largest_alloc_size(0),
bytes_reserved(0),
peak_bytes_reserved(0),
largest_free_block_bytes(0) {}
std::string DebugString() const;
};
enum class AllocatorMemoryType {
kUnknown = 0,
kDevice = 1,
kHostPageable = 2,
kHostPinned = 3,
};
class Allocator {
public:
static constexpr size_t kAllocatorAlignment = 64;
virtual ~Allocator();
virtual std::string Name() = 0;
virtual void* AllocateRaw(size_t alignment, size_t num_bytes) = 0;
virtual void* AllocateRaw(size_t alignment, size_t num_bytes,
const AllocationAttributes& allocation_attr) {
return AllocateRaw(alignment, num_bytes);
}
virtual void DeallocateRaw(void* ptr) = 0;
virtual bool TracksAllocationSizes() const { return false; }
virtual bool AllocatesOpaqueHandle() const { return false; }
virtual size_t RequestedSize(const void* ptr) const {
CHECK(false) << "allocator doesn't track sizes";
return size_t(0);
}
virtual size_t AllocatedSize(const void* ptr) const {
return RequestedSize(ptr);
}
virtual int64_t AllocationId(const void* ptr) const { return 0; }
virtual size_t AllocatedSizeSlow(const void* ptr) const {
if (TracksAllocationSizes()) {
return AllocatedSize(ptr);
}
return 0;
}
virtual absl::optional<AllocatorStats> GetStats() { return absl::nullopt; }
virtual bool ClearStats() TF_MUST_USE_RESULT { return false; }
virtual void SetSafeFrontier(uint64 count) {}
virtual void SetStreamAndPreallocateMemory(void* stream) {}
virtual AllocatorMemoryType GetMemoryType() const {
return AllocatorMemoryType::kUnknown;
}
};
class AllocatorWrapper : public Allocator {
public:
explicit AllocatorWrapper(Allocator* wrapped) : wrapped_(wrapped) {}
~AllocatorWrapper() override {}
Allocator* wrapped() const { return wrapped_; }
std::string Name() override { return wrapped_->Name(); }
void* AllocateRaw(size_t alignment, size_t num_bytes) override {
return wrapped_->AllocateRaw(alignment, num_bytes);
}
void* AllocateRaw(size_t alignment, size_t num_bytes,
const AllocationAttributes& allocation_attr) override {
return wrapped_->AllocateRaw(alignment, num_bytes, allocation_attr);
}
void DeallocateRaw(void* ptr) override { wrapped_->DeallocateRaw(ptr); }
bool TracksAllocationSizes() const override {
return wrapped_->TracksAllocationSizes();
}
bool AllocatesOpaqueHandle() const override {
return wrapped_->AllocatesOpaqueHandle();
}
size_t RequestedSize(const void* ptr) const override {
return wrapped_->RequestedSize(ptr);
}
size_t AllocatedSize(const void* ptr) const override {
return wrapped_->AllocatedSize(ptr);
}
int64_t AllocationId(const void* ptr) const override {
return wrapped_->AllocationId(ptr);
}
size_t AllocatedSizeSlow(const void* ptr) const override {
return wrapped_->AllocatedSizeSlow(ptr);
}
AllocatorMemoryType GetMemoryType() const override {
return wrapped_->GetMemoryType();
}
private:
Allocator* const wrapped_;
};
struct AllocatorAttributes {
void set_on_host(bool v) { value |= (static_cast<int>(v)); }
bool on_host() const { return value & 0x1; }
void set_nic_compatible(bool v) { value |= (static_cast<int>(v) << 1); }
bool nic_compatible() const { return value & (0x1 << 1); }
void set_gpu_compatible(bool v) { value |= (static_cast<int>(v) << 2); }
bool gpu_compatible() const { return value & (0x1 << 2); }
void set_use_pjrt_allocator(bool v) { value |= (static_cast<int>(v) << 3); }
bool use_pjrt_allocator() const { return value & (0x1 << 3); }
void Merge(AllocatorAttributes other) {
value |= other.value;
if (scope_id != other.scope_id) {
CHECK(scope_id == 0 || other.scope_id == 0)
<< "At least one scope_id should be zero to merge "
"AllocatorAttributes but found this.scope_id="
<< scope_id << " and other.scope_id=" << other.scope_id;
scope_id = scope_id == 0 ? other.scope_id : scope_id;
}
}
bool IsEqualOrLessRestrictiveThan(const AllocatorAttributes& other) const {
return (value | other.value) == other.value;
}
uint32 value = 0;
int32 scope_id = 0;
std::string DebugString() const;
};
Allocator* cpu_allocator_base();
Allocator* cpu_allocator(int numa_node = port::kNUMANoAffinity);
void EnableCPUAllocatorStats();
void DisableCPUAllocatorStats();
bool CPUAllocatorStatsEnabled();
void EnableCPUAllocatorFullStats();
bool CPUAllocatorFullStatsEnabled();
class SubAllocator {
public:
typedef std::function<void(void*, int index, size_t)> Visitor;
SubAllocator(const std::vector<Visitor>& alloc_visitors,
const std::vector<Visitor>& free_visitors);
virtual ~SubAllocator() {}
virtual void* Alloc(size_t alignment, size_t num_bytes,
size_t* bytes_received) = 0;
virtual void Free(void* ptr, size_t num_bytes) = 0;
virtual bool SupportsCoalescing() const = 0;
virtual AllocatorMemoryType GetMemoryType() const {
return AllocatorMemoryType::kUnknown;
}
protected:
void VisitAlloc(void* ptr, int index, size_t num_bytes);
void VisitFree(void* ptr, int index, size_t num_bytes);
const std::vector<Visitor> alloc_visitors_;
const std::vector<Visitor> free_visitors_;
};
}
#endif
#include "xla/tsl/framework/allocator.h"
#include <atomic>
#include "xla/tsl/framework/allocator_registry.h"
#include "xla/tsl/framework/tracking_allocator.h"
#include "tsl/platform/mem.h"
#include "tsl/platform/mutex.h"
#include "tsl/platform/strcat.h"
#include "tsl/platform/stringprintf.h"
#include "tsl/platform/types.h"
namespace tsl {
string AllocatorStats::DebugString() const {
return strings::Printf(
"Limit: %20lld\n"
"InUse: %20lld\n"
"MaxInUse: %20lld\n"
"NumAllocs: %20lld\n"
"MaxAllocSize: %20lld\n"
"Reserved: %20lld\n"
"PeakReserved: %20lld\n"
"LargestFreeBlock: %20lld\n",
static_cast<long long>(this->bytes_limit ? *this->bytes_limit : 0),
static_cast<long long>(this->bytes_in_use),
static_cast<long long>(this->peak_bytes_in_use),
static_cast<long long>(this->num_allocs),
static_cast<long long>(this->largest_alloc_size),
static_cast<long long>(this->bytes_reserved),
static_cast<long long>(this->peak_bytes_reserved),
static_cast<long long>(this->largest_free_block_bytes));
}
constexpr size_t Allocator::kAllocatorAlignment;
Allocator::~Allocator() {}
static bool cpu_allocator_collect_full_stats = false;
void EnableCPUAllocatorFullStats() { cpu_allocator_collect_full_stats = true; }
bool CPUAllocatorFullStatsEnabled() { return cpu_allocator_collect_full_stats; }
string AllocatorAttributes::DebugString() const {
return strings::StrCat("AllocatorAttributes(on_host=", on_host(),
" nic_compatible=", nic_compatible(),
" gpu_compatible=", gpu_compatible(), ")");
}
Allocator* cpu_allocator_base() {
static Allocator* cpu_alloc =
AllocatorFactoryRegistry::singleton()->GetAllocator();
if (cpu_allocator_collect_full_stats && !cpu_alloc->TracksAllocationSizes()) {
cpu_alloc = new TrackingAllocator(cpu_alloc, true);
}
return cpu_alloc;
}
Allocator* cpu_allocator(int numa_node) {
static ProcessStateInterface* ps =
AllocatorFactoryRegistry::singleton()->process_state();
if (ps) {
return ps->GetCPUAllocator(numa_node);
} else {
return cpu_allocator_base();
}
}
SubAllocator::SubAllocator(const std::vector<Visitor>& alloc_visitors,
const std::vector<Visitor>& free_visitors)
: alloc_visitors_(alloc_visitors), free_visitors_(free_visitors) {}
void SubAllocator::VisitAlloc(void* ptr, int index, size_t num_bytes) {
for (const auto& v : alloc_visitors_) {
v(ptr, index, num_bytes);
}
}
void SubAllocator::VisitFree(void* ptr, int index, size_t num_bytes) {
for (int i = free_visitors_.size() - 1; i >= 0; --i) {
free_visitors_[i](ptr, index, num_bytes);
}
}
} | #include "tensorflow/core/framework/allocator.h"
#include <algorithm>
#include <vector>
#include "tensorflow/core/framework/typed_allocator.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/mem.h"
#include "tensorflow/core/platform/test.h"
#include "tensorflow/core/platform/test_benchmark.h"
#include "tensorflow/core/profiler/lib/profiler_session.h"
#include "tensorflow/core/profiler/protobuf/memory_profile.pb.h"
#include "tensorflow/core/profiler/protobuf/xplane.pb.h"
#include "tensorflow/core/profiler/utils/xplane_schema.h"
#include "tensorflow/core/profiler/utils/xplane_visitor.h"
#include "tsl/profiler/utils/xplane_utils.h"
namespace tensorflow {
static void CheckStats(Allocator* a, int64_t num_allocs, int64_t bytes_in_use,
int64_t peak_bytes_in_use, int64_t largest_alloc_size) {
absl::optional<AllocatorStats> stats = a->GetStats();
EXPECT_TRUE(stats);
if (!stats) {
return;
}
LOG(INFO) << "Alloc stats: \n" << stats->DebugString();
#if defined(PLATFORM_GOOGLE) && defined(NDEBUG)
static const int64 kSlop = 5 * 1024;
EXPECT_GT(stats->bytes_in_use, bytes_in_use - kSlop);
EXPECT_LT(stats->bytes_in_use, bytes_in_use + kSlop);
EXPECT_GT(stats->peak_bytes_in_use, peak_bytes_in_use - kSlop);
EXPECT_LT(stats->peak_bytes_in_use, peak_bytes_in_use + kSlop);
EXPECT_EQ(stats->num_allocs, num_allocs);
EXPECT_EQ(stats->largest_alloc_size, largest_alloc_size);
#endif
}
TEST(AllocatorAttributesTest, AllCombos) {
for (bool on_host : {false, true}) {
for (bool nic_compatible : {false, true}) {
for (bool gpu_compatible : {false, true}) {
AllocatorAttributes aa;
aa.set_on_host(on_host);
aa.set_nic_compatible(nic_compatible);
aa.set_gpu_compatible(gpu_compatible);
EXPECT_EQ(on_host, aa.on_host());
EXPECT_EQ(nic_compatible, aa.nic_compatible());
EXPECT_EQ(gpu_compatible, aa.gpu_compatible());
}
}
}
}
TEST(AllocatorAttributesTest, IsEqualOrLessRestrictiveThan) {
AllocatorAttributes a, b;
EXPECT_TRUE(a.IsEqualOrLessRestrictiveThan(b));
EXPECT_TRUE(a.IsEqualOrLessRestrictiveThan(a));
EXPECT_TRUE(b.IsEqualOrLessRestrictiveThan(b));
b.set_gpu_compatible(true);
EXPECT_TRUE(a.IsEqualOrLessRestrictiveThan(b));
EXPECT_FALSE(b.IsEqualOrLessRestrictiveThan(a));
EXPECT_TRUE(a.IsEqualOrLessRestrictiveThan(a));
EXPECT_TRUE(b.IsEqualOrLessRestrictiveThan(b));
a.set_nic_compatible(true);
EXPECT_FALSE(a.IsEqualOrLessRestrictiveThan(b));
EXPECT_FALSE(b.IsEqualOrLessRestrictiveThan(a));
a.set_gpu_compatible(true);
EXPECT_TRUE(b.IsEqualOrLessRestrictiveThan(a));
EXPECT_FALSE(a.IsEqualOrLessRestrictiveThan(b));
}
TEST(AllocatorAttributesTest, Merge) {
AllocatorAttributes a, b;
EXPECT_EQ(a.value, 0);
EXPECT_EQ(b.value, 0);
EXPECT_FALSE(a.nic_compatible());
EXPECT_FALSE(b.nic_compatible());
b.set_nic_compatible(true);
a.Merge(b);
EXPECT_TRUE(a.nic_compatible());
EXPECT_TRUE(b.nic_compatible());
EXPECT_EQ(a.scope_id, 0);
EXPECT_EQ(b.scope_id, 0);
a.scope_id = 1;
a.Merge(b);
EXPECT_EQ(a.scope_id, 1);
EXPECT_EQ(b.scope_id, 0);
a.scope_id = 1;
b.scope_id = 0;
b.Merge(a);
EXPECT_EQ(a.scope_id, 1);
EXPECT_EQ(b.scope_id, 1);
a.scope_id = 2;
b.scope_id = 2;
a.Merge(b);
EXPECT_EQ(a.scope_id, 2);
EXPECT_EQ(b.scope_id, 2);
}
TEST(AllocatorAttributesDeathTest, MergeDifferentScopeIds) {
AllocatorAttributes a, b;
a.scope_id = 3;
b.scope_id = 4;
EXPECT_DEATH({ a.Merge(b); }, "");
}
TEST(CPUAllocatorTest, Simple) {
EnableCPUAllocatorStats();
Allocator* a = cpu_allocator();
std::vector<void*> ptrs;
for (int s = 1; s < 1024; s++) {
void* raw = a->AllocateRaw(1, s);
ptrs.push_back(raw);
}
std::sort(ptrs.begin(), ptrs.end());
CheckStats(a, 1023, 552640, 552640, 1024);
for (size_t i = 0; i < ptrs.size(); i++) {
if (i > 0) {
CHECK_NE(ptrs[i], ptrs[i - 1]);
}
a->DeallocateRaw(ptrs[i]);
}
CheckStats(a, 1023, 0, 552640, 1024);
float* t1 = TypedAllocator::Allocate<float>(a, 1024, {});
double* t2 = TypedAllocator::Allocate<double>(a, 1048576, {});
CheckStats(a, 1025, 1048576 * sizeof(double) + 1024 * sizeof(float),
1048576 * sizeof(double) + 1024 * sizeof(float),
1048576 * sizeof(double));
TypedAllocator::Deallocate(a, t1, 1024);
TypedAllocator::Deallocate(a, t2, 1048576);
CheckStats(a, 1025, 0, 1048576 * sizeof(double) + 1024 * sizeof(float),
1048576 * sizeof(double));
CHECK(a->ClearStats());
CheckStats(a, 0, 0, 0, 0);
DisableCPUAllocatorStats();
}
struct TestStruct {
int x;
};
TEST(CPUAllocatorTest, CheckStructSize) { CHECK_GT(sizeof(TestStruct), 1); }
TEST(CPUAllocatorTest, AllocateOverflowMaxSizeT) {
Allocator* a = cpu_allocator();
size_t count_to_allocate = std::numeric_limits<size_t>::max();
TestStruct* const test_pointer =
TypedAllocator::Allocate<TestStruct>(a, count_to_allocate, {});
CHECK_EQ(test_pointer, reinterpret_cast<TestStruct*>(NULL));
}
TEST(CPUAllocatorTest, AllocateOverflowSmallest) {
Allocator* a = cpu_allocator();
const size_t count_to_allocate =
(std::numeric_limits<size_t>::max() / sizeof(TestStruct)) + 1;
TestStruct* const test_pointer =
TypedAllocator::Allocate<TestStruct>(a, count_to_allocate, {});
CHECK_EQ(test_pointer, reinterpret_cast<TestStruct*>(NULL));
}
TEST(CPUAllocatorTest, Sizes) {
Allocator* a = cpu_allocator();
EXPECT_EQ(false, a->TracksAllocationSizes());
}
TEST(CPUAllocatorTest, ProfilerReporting) {
void* p = port::AlignedMalloc(8, 1);
const std::size_t alloc_size = port::MallocExtension_GetAllocatedSize(p);
port::AlignedFree(p);
if (alloc_size == 0) {
LOG(WARNING) << "Skipping Memory Debugging test. It requires "
<< "port::MallocExtension_GetAllocatedSize to work.";
return;
}
EnableCPUAllocatorStats();
Allocator* a = cpu_allocator();
void* p1 = a->AllocateRaw(1, 16);
std::unique_ptr<ProfilerSession> profiler =
tensorflow::ProfilerSession::Create(
tensorflow::ProfilerSession::DefaultOptions());
void* p2 = a->AllocateRaw(1, 32);
a->DeallocateRaw(p1);
tensorflow::profiler::XSpace xspace;
EXPECT_EQ(OkStatus(), profiler->CollectData(&xspace));
const auto plane = ::tsl::profiler::FindPlaneWithName(
xspace, ::tensorflow::profiler::kHostThreadsPlaneName);
::tensorflow::profiler::XPlaneVisitor xplane(plane);
ASSERT_EQ(plane->name(), ::tensorflow::profiler::kHostThreadsPlaneName)
<< "XSpace: " << xspace.DebugString();
ASSERT_EQ(plane->event_metadata_size(), 2)
<< "XSpace: " << xspace.DebugString();
const auto& line = plane->lines(0);
ASSERT_EQ(line.events_size(), 2) << "XSpace: " << xspace.DebugString();
const auto& events = line.events();
::tensorflow::profiler::XEventVisitor e0(&xplane, &line, &events[0]);
EXPECT_EQ(e0.Name(), "MemoryAllocation")
<< "XSpace: " << xspace.DebugString();
{
absl::optional<std::string> bytes_allocated, peak_bytes_in_use,
requested_bytes, allocation_bytes;
e0.ForEachStat([&](const ::tensorflow::profiler::XStatVisitor& stat) {
LOG(ERROR) << "STAT " << stat.Name() << ": " << stat.ToString();
if (stat.Name() == "bytes_allocated") {
bytes_allocated = stat.ToString();
} else if (stat.Name() == "peak_bytes_in_use") {
peak_bytes_in_use = stat.ToString();
} else if (stat.Name() == "requested_bytes") {
requested_bytes = stat.ToString();
} else if (stat.Name() == "allocation_bytes") {
allocation_bytes = stat.ToString();
}
});
ASSERT_TRUE(bytes_allocated && peak_bytes_in_use && requested_bytes &&
allocation_bytes)
<< "XSpace: " << xspace.DebugString();
EXPECT_EQ(*bytes_allocated, "48") << "XSpace: " << xspace.DebugString();
EXPECT_EQ(*peak_bytes_in_use, "48") << "XSpace: " << xspace.DebugString();
EXPECT_EQ(*requested_bytes, "32") << "XSpace: " << xspace.DebugString();
EXPECT_EQ(*allocation_bytes, "32") << "XSpace: " << xspace.DebugString();
}
::tensorflow::profiler::XEventVisitor e1(&xplane, &line, &events[1]);
EXPECT_EQ(e1.Name(), "MemoryDeallocation")
<< "XSpace: " << xspace.DebugString();
{
absl::optional<std::string> bytes_allocated, peak_bytes_in_use,
allocation_bytes;
e1.ForEachStat([&](const ::tensorflow::profiler::XStatVisitor& stat) {
if (stat.Name() == "bytes_allocated") {
bytes_allocated = stat.ToString();
} else if (stat.Name() == "peak_bytes_in_use") {
peak_bytes_in_use = stat.ToString();
} else if (stat.Name() == "allocation_bytes") {
allocation_bytes = stat.ToString();
}
});
ASSERT_TRUE(bytes_allocated && peak_bytes_in_use && allocation_bytes)
<< "XSpace: " << xspace.DebugString();
EXPECT_EQ(*bytes_allocated, "32") << "XSpace: " << xspace.DebugString();
EXPECT_EQ(*peak_bytes_in_use, "48") << "XSpace: " << xspace.DebugString();
EXPECT_EQ(*allocation_bytes, "16") << "XSpace: " << xspace.DebugString();
}
a->DeallocateRaw(p2);
DisableCPUAllocatorStats();
}
namespace {
AllocatorAttributes DeviceAllocatorAttribute() {
AllocatorAttributes attr;
attr.value |= (0x1 << 24);
return attr;
}
bool HasDeviceAllocatorAttribute(const AllocatorAttributes& attr) {
return attr.value & (0x1 << 24);
}
}
TEST(CustomAllocatorAttributes, TestSetterAndGetter) {
AllocatorAttributes attr = DeviceAllocatorAttribute();
EXPECT_TRUE(HasDeviceAllocatorAttribute(attr));
EXPECT_FALSE(HasDeviceAllocatorAttribute(AllocatorAttributes()));
}
static void BM_Allocation(::testing::benchmark::State& state) {
const int arg = state.range(0);
Allocator* a = cpu_allocator();
std::vector<int> sizes = {256, 4096, 16384, 524288, 512, 1048576};
int size_index = 0;
if (arg) EnableCPUAllocatorStats();
for (auto s : state) {
int bytes = sizes[size_index++ % sizes.size()];
void* p = a->AllocateRaw(1, bytes);
a->DeallocateRaw(p);
}
if (arg) DisableCPUAllocatorStats();
}
BENCHMARK(BM_Allocation)->Arg(0)->Arg(1);
} | 2,247 |
#ifndef XLA_TSL_UTIL_REPORTER_H_
#define XLA_TSL_UTIL_REPORTER_H_
#include <cstdlib>
#include <memory>
#include <string>
#include <unordered_set>
#include "tsl/platform/env.h"
#include "tsl/platform/macros.h"
#include "tsl/platform/mutex.h"
#include "tsl/platform/types.h"
#include "tsl/protobuf/test_log.pb.h"
namespace tsl {
class TestReportFile {
public:
TestReportFile(const string& fname, const string& test_name);
absl::Status Initialize();
absl::Status Append(const string& content);
absl::Status Close();
bool IsClosed() const { return closed_; }
~TestReportFile() { Close().IgnoreError(); }
private:
bool closed_;
string fname_;
string test_name_;
std::unique_ptr<WritableFile> log_file_;
TestReportFile(const TestReportFile&) = delete;
void operator=(const TestReportFile&) = delete;
};
class TestReporter {
public:
static constexpr const char* kTestReporterEnv = "TEST_REPORT_FILE_PREFIX";
explicit TestReporter(const string& test_name)
: TestReporter(GetLogEnv(), test_name) {}
TestReporter(const string& fname, const string& test_name);
absl::Status Initialize();
absl::Status Close();
absl::Status Benchmark(int64_t iters, double cpu_time, double wall_time,
double throughput);
absl::Status SetProperty(const string& name, double value);
absl::Status SetProperty(const string& name, const string& value);
absl::Status AddMetric(const string& name, double value);
~TestReporter() { Close().IgnoreError(); }
private:
static string GetLogEnv() {
const char* fname_ptr = getenv(kTestReporterEnv);
return (fname_ptr != nullptr) ? fname_ptr : "";
}
TestReportFile report_file_;
tensorflow::BenchmarkEntry benchmark_entry_;
TestReporter(const TestReporter&) = delete;
void operator=(const TestReporter&) = delete;
};
}
#endif
#include "xla/tsl/util/reporter.h"
#include "tsl/platform/errors.h"
#include "tsl/platform/mutex.h"
#include "tsl/platform/str_util.h"
namespace tsl {
TestReportFile::TestReportFile(const string& fname, const string& test_name)
: closed_(true), fname_(fname), test_name_(test_name) {}
absl::Status TestReportFile::Append(const string& content) {
if (closed_) return absl::OkStatus();
return log_file_->Append(content);
}
absl::Status TestReportFile::Close() {
if (closed_) return absl::OkStatus();
closed_ = true;
return log_file_->Close();
}
absl::Status TestReportFile::Initialize() {
if (fname_.empty()) {
return absl::OkStatus();
}
string mangled_fname = strings::StrCat(
fname_, absl::StrJoin(str_util::Split(test_name_, '/'), "__"));
Env* env = Env::Default();
if (env->FileExists(mangled_fname).ok()) {
return errors::InvalidArgument(
"Cannot create TestReportFile, file exists: ", mangled_fname);
}
TF_RETURN_IF_ERROR(env->NewWritableFile(mangled_fname, &log_file_));
TF_RETURN_IF_ERROR(log_file_->Flush());
closed_ = false;
return absl::OkStatus();
}
TestReporter::TestReporter(const string& fname, const string& test_name)
: report_file_(fname, test_name) {
benchmark_entry_.set_name(test_name);
}
absl::Status TestReporter::Close() {
if (report_file_.IsClosed()) return absl::OkStatus();
tensorflow::BenchmarkEntries entries;
*entries.add_entry() = benchmark_entry_;
TF_RETURN_IF_ERROR(report_file_.Append(entries.SerializeAsString()));
benchmark_entry_.Clear();
return report_file_.Close();
}
absl::Status TestReporter::Benchmark(int64_t iters, double cpu_time,
double wall_time, double throughput) {
if (report_file_.IsClosed()) return absl::OkStatus();
benchmark_entry_.set_iters(iters);
benchmark_entry_.set_cpu_time(cpu_time / iters);
benchmark_entry_.set_wall_time(wall_time / iters);
benchmark_entry_.set_throughput(throughput);
return absl::OkStatus();
}
absl::Status TestReporter::SetProperty(const string& name,
const string& value) {
if (report_file_.IsClosed()) return absl::OkStatus();
(*benchmark_entry_.mutable_extras())[name].set_string_value(value);
return absl::OkStatus();
}
absl::Status TestReporter::SetProperty(const string& name, double value) {
if (report_file_.IsClosed()) return absl::OkStatus();
(*benchmark_entry_.mutable_extras())[name].set_double_value(value);
return absl::OkStatus();
}
absl::Status TestReporter::AddMetric(const string& name, double value) {
if (report_file_.IsClosed()) return absl::OkStatus();
auto* metric = benchmark_entry_.add_metrics();
metric->set_name(name);
metric->set_value(value);
return absl::OkStatus();
}
absl::Status TestReporter::Initialize() { return report_file_.Initialize(); }
} | #define _XOPEN_SOURCE
#include <cstdlib>
#include "tensorflow/core/util/reporter.h"
#include "tensorflow/core/lib/core/status_test_util.h"
#include "tensorflow/core/lib/strings/str_util.h"
#include "tensorflow/core/lib/strings/strcat.h"
#include "tensorflow/core/platform/protobuf.h"
#include "tensorflow/core/platform/test.h"
namespace tensorflow {
namespace {
static void ExpectHasSubstr(StringPiece s, StringPiece expected) {
EXPECT_TRUE(absl::StrContains(s, expected))
<< s << " does not contain " << expected;
}
TEST(TestReporter, NoLogging) {
TestReporter test_reporter("b1");
TF_EXPECT_OK(test_reporter.Initialize());
TF_EXPECT_OK(test_reporter.Close());
}
TEST(TestReporter, UsesEnv) {
const char* old_env = std::getenv(TestReporter::kTestReporterEnv);
setenv(TestReporter::kTestReporterEnv, "/cant/find/me:!", 1);
CHECK_EQ(string(std::getenv(TestReporter::kTestReporterEnv)),
string("/cant/find/me:!"));
TestReporter test_reporter("b1");
Status s = test_reporter.Initialize();
ExpectHasSubstr(s.ToString(), "/cant/find/me");
unsetenv(TestReporter::kTestReporterEnv);
CHECK_EQ(std::getenv(TestReporter::kTestReporterEnv), nullptr);
TestReporter test_reporter_empty("b1");
s = test_reporter_empty.Initialize();
TF_EXPECT_OK(s);
s = test_reporter_empty.Close();
TF_EXPECT_OK(s);
if (old_env == nullptr) {
unsetenv(TestReporter::kTestReporterEnv);
} else {
setenv(TestReporter::kTestReporterEnv, old_env, 1);
}
}
TEST(TestReporter, CreateTwiceFails) {
{
TestReporter test_reporter(
strings::StrCat(testing::TmpDir(), "/test_reporter_dupe"), "t1");
TF_EXPECT_OK(test_reporter.Initialize());
}
{
TestReporter test_reporter(
strings::StrCat(testing::TmpDir(), "/test_reporter_dupe"), "t1");
Status s = test_reporter.Initialize();
ExpectHasSubstr(s.ToString(), "file exists:");
}
}
TEST(TestReporter, CreateCloseCreateAgainSkipsSecond) {
TestReporter test_reporter(
strings::StrCat(testing::TmpDir(), "/test_reporter_create_close"), "t1");
TF_EXPECT_OK(test_reporter.Initialize());
TF_EXPECT_OK(test_reporter.Close());
TF_EXPECT_OK(test_reporter.Benchmark(1, 1.0, 2.0, 3.0));
TF_EXPECT_OK(test_reporter.Close());
Status s = test_reporter.Initialize();
ExpectHasSubstr(s.ToString(), "file exists:");
}
TEST(TestReporter, Benchmark) {
string fname =
strings::StrCat(testing::TmpDir(), "/test_reporter_benchmarks_");
TestReporter test_reporter(fname, "b1/2/3");
TF_EXPECT_OK(test_reporter.Initialize());
TF_EXPECT_OK(test_reporter.Benchmark(1, 1.0, 2.0, 3.0));
TF_EXPECT_OK(test_reporter.Close());
string expected_fname = strings::StrCat(fname, "b1__2__3");
string read;
TF_EXPECT_OK(ReadFileToString(Env::Default(), expected_fname, &read));
BenchmarkEntries benchmark_entries;
ASSERT_TRUE(benchmark_entries.ParseFromString(read));
ASSERT_EQ(1, benchmark_entries.entry_size());
const BenchmarkEntry& benchmark_entry = benchmark_entries.entry(0);
EXPECT_EQ(benchmark_entry.name(), "b1/2/3");
EXPECT_EQ(benchmark_entry.iters(), 1);
EXPECT_EQ(benchmark_entry.cpu_time(), 1.0);
EXPECT_EQ(benchmark_entry.wall_time(), 2.0);
EXPECT_EQ(benchmark_entry.throughput(), 3.0);
}
TEST(TestReporter, SetProperties) {
string fname =
strings::StrCat(testing::TmpDir(), "/test_reporter_benchmarks_");
TestReporter test_reporter(fname, "b2/3/4");
TF_EXPECT_OK(test_reporter.Initialize());
TF_EXPECT_OK(test_reporter.SetProperty("string_prop", "abc"));
TF_EXPECT_OK(test_reporter.SetProperty("double_prop", 4.0));
TF_EXPECT_OK(test_reporter.Close());
string expected_fname = strings::StrCat(fname, "b2__3__4");
string read;
TF_EXPECT_OK(ReadFileToString(Env::Default(), expected_fname, &read));
BenchmarkEntries benchmark_entries;
ASSERT_TRUE(benchmark_entries.ParseFromString(read));
ASSERT_EQ(1, benchmark_entries.entry_size());
const BenchmarkEntry& benchmark_entry = benchmark_entries.entry(0);
const auto& extras = benchmark_entry.extras();
ASSERT_EQ(2, extras.size());
EXPECT_EQ("abc", extras.at("string_prop").string_value());
EXPECT_EQ(4.0, extras.at("double_prop").double_value());
}
TEST(TestReporter, AddMetrics) {
string fname =
strings::StrCat(testing::TmpDir(), "/test_reporter_benchmarks_");
TestReporter test_reporter(fname, "b3/4/5");
TF_EXPECT_OK(test_reporter.Initialize());
TF_EXPECT_OK(test_reporter.AddMetric("metric1", 2.0));
TF_EXPECT_OK(test_reporter.AddMetric("metric2", 3.0));
TF_EXPECT_OK(test_reporter.Close());
string expected_fname = strings::StrCat(fname, "b3__4__5");
string read;
TF_EXPECT_OK(ReadFileToString(Env::Default(), expected_fname, &read));
BenchmarkEntries benchmark_entries;
ASSERT_TRUE(benchmark_entries.ParseFromString(read));
ASSERT_EQ(1, benchmark_entries.entry_size());
const BenchmarkEntry& benchmark_entry = benchmark_entries.entry(0);
const auto& metrics = benchmark_entry.metrics();
ASSERT_EQ(2, metrics.size());
EXPECT_EQ("metric1", metrics.at(0).name());
EXPECT_EQ(2.0, metrics.at(0).value());
EXPECT_EQ("metric2", metrics.at(1).name());
EXPECT_EQ(3.0, metrics.at(1).value());
}
}
} | 2,248 |
#ifndef XLA_TSL_UTIL_STATS_CALCULATOR_H_
#define XLA_TSL_UTIL_STATS_CALCULATOR_H_
#include <stdlib.h>
#include <algorithm>
#include <cmath>
#include <limits>
#include <map>
#include <sstream>
#include <string>
#include <vector>
#include "xla/tsl/util/stat_summarizer_options.h"
namespace tsl {
template <typename ValueType, typename HighPrecisionValueType = double>
class Stat {
public:
void UpdateStat(ValueType v) {
if (count_ == 0) {
first_ = v;
}
newest_ = v;
max_ = std::max(v, max_);
min_ = std::min(v, min_);
++count_;
sum_ += v;
squared_sum_ += static_cast<HighPrecisionValueType>(v) * v;
}
void Reset() { new (this) Stat<ValueType, HighPrecisionValueType>(); }
bool empty() const { return count_ == 0; }
ValueType first() const { return first_; }
ValueType newest() const { return newest_; }
ValueType max() const { return max_; }
ValueType min() const { return min_; }
int64_t count() const { return count_; }
ValueType sum() const { return sum_; }
HighPrecisionValueType squared_sum() const { return squared_sum_; }
bool all_same() const { return (count_ == 0 || min_ == max_); }
HighPrecisionValueType avg() const {
return empty() ? std::numeric_limits<ValueType>::quiet_NaN()
: static_cast<HighPrecisionValueType>(sum_) / count_;
}
ValueType sample_variance() const {
return all_same()
? 0
: (squared_sum_ - std::pow(sum_, 2.0) / count_) / (count_ - 1);
}
ValueType variance() const {
return all_same() ? 0 : (squared_sum_ / count_) - (avg() * avg());
}
ValueType std_deviation() const {
return all_same() ? 0 : std::sqrt(variance());
}
void OutputToStream(std::ostream* stream) const {
if (empty()) {
*stream << "count=0";
} else if (all_same()) {
*stream << "count=" << count_ << " curr=" << newest_;
if (count_ > 1) *stream << "(all same)";
} else {
*stream << "count=" << count_ << " first=" << first_
<< " curr=" << newest_ << " min=" << min_ << " max=" << max_
<< " avg=" << avg() << " std=" << std_deviation();
}
}
friend std::ostream& operator<<(std::ostream& stream,
const Stat<ValueType>& stat) {
stat.OutputToStream(&stream);
return stream;
}
private:
ValueType first_ = 0;
ValueType newest_ = 0;
ValueType max_ = std::numeric_limits<ValueType>::min();
ValueType min_ = std::numeric_limits<ValueType>::max();
int64_t count_ = 0;
ValueType sum_ = 0;
HighPrecisionValueType squared_sum_ = 0;
};
class StatsCalculator {
public:
enum SortingMetric {
BY_NAME,
BY_RUN_ORDER,
BY_TIME,
BY_MEMORY,
BY_TYPE,
};
explicit StatsCalculator(const StatSummarizerOptions& options);
std::string GetOutputString() const;
std::string GetShortSummary() const;
void ComputeStatsByType(
std::map<std::string, int64_t>* node_type_map_count,
std::map<std::string, int64_t>* node_type_map_time,
std::map<std::string, int64_t>* node_type_map_memory,
std::map<std::string, int64_t>* node_type_map_times_called,
int64_t* accumulated_us) const;
std::string GetStatsByNodeType() const;
std::string GetStatsByMetric(const std::string& title,
SortingMetric sorting_metric,
int num_stats) const;
int num_runs() const { return static_cast<int>(run_total_us_.count()); }
const Stat<int64_t>& run_total_us() const { return run_total_us_; }
void UpdateRunTotalUs(int64_t run_total_us) {
run_total_us_.UpdateStat(run_total_us);
}
void UpdateMemoryUsed(int64_t memory) { memory_.UpdateStat(memory); }
struct Detail {
std::string name;
std::string type;
int64_t run_order;
Stat<int64_t> elapsed_time;
Stat<int64_t> mem_used;
int64_t times_called;
};
const std::map<std::string, Detail>& GetDetails() const { return details_; }
void AddNodeStats(const std::string& name, const std::string& type,
int64_t run_order, int64_t rel_end_us, int64_t mem_used);
private:
void OrderNodesByMetric(SortingMetric sorting_metric,
std::vector<const Detail*>* details) const;
std::string HeaderString(const std::string& title) const;
std::string ColumnString(const Detail& detail,
const int64_t cumulative_stat_on_node,
const Stat<int64_t>& stat) const;
Stat<int64_t> run_total_us_;
Stat<int64_t> memory_;
std::map<std::string, Detail> details_;
StatSummarizerOptions options_;
};
}
#endif
#include "xla/tsl/util/stats_calculator.h"
#include <iomanip>
#include <map>
#include <queue>
#include <sstream>
#include <string>
namespace tsl {
constexpr int kNodeTypeWidth = 40;
StatsCalculator::StatsCalculator(const StatSummarizerOptions& options)
: options_(options) {}
std::string StatsCalculator::GetShortSummary() const {
std::stringstream stream;
stream << "Timings (microseconds): ";
run_total_us_.OutputToStream(&stream);
stream << std::endl;
stream << "Memory (bytes): ";
memory_.OutputToStream(&stream);
stream << std::endl;
stream << details_.size() << " nodes observed" << std::endl;
return stream.str();
}
std::ostream& InitField(std::ostream& stream, int width) {
stream << "\t" << std::right << std::setw(width) << std::fixed
<< std::setprecision(3);
return stream;
}
std::string StatsCalculator::HeaderString(const std::string& title) const {
std::stringstream stream;
stream << "============================== " << title
<< " ==============================" << std::endl;
if (options_.format_as_csv) {
stream << "node type, first, avg_ms, %, cdf%, mem KB, times called, "
"name";
} else {
InitField(stream, kNodeTypeWidth) << "[node type]";
InitField(stream, 9) << "[first]";
InitField(stream, 9) << "[avg ms]";
InitField(stream, 8) << "[%]";
InitField(stream, 8) << "[cdf%]";
InitField(stream, 10) << "[mem KB]";
InitField(stream, 9) << "[times called]";
stream << "\t"
<< "[Name]";
}
return stream.str();
}
std::string StatsCalculator::ColumnString(const Detail& detail,
const int64_t cumulative_stat_on_node,
const Stat<int64_t>& stat) const {
const double first_time_ms = detail.elapsed_time.first() / 1000.0;
const double avg_time_ms = detail.elapsed_time.avg() / 1000.0;
const double percentage = detail.elapsed_time.sum() * 100.0 / stat.sum();
const double cdf_percentage = (cumulative_stat_on_node * 100.0f) / stat.sum();
const int64_t times_called = detail.times_called / num_runs();
std::stringstream stream;
if (options_.format_as_csv) {
std::string name(detail.name);
std::replace(name.begin(), name.end(), ',', '\t');
stream << detail.type << ", " << first_time_ms << ", " << avg_time_ms
<< ", " << percentage << "%, " << cdf_percentage << "%, "
<< detail.mem_used.newest() / 1000.0 << ", " << times_called << ", "
<< name;
} else {
InitField(stream, kNodeTypeWidth) << detail.type;
InitField(stream, 9) << first_time_ms;
InitField(stream, 9) << avg_time_ms;
InitField(stream, 7) << percentage << "%";
InitField(stream, 7) << cdf_percentage << "%";
InitField(stream, 10) << detail.mem_used.newest() / 1000.0;
InitField(stream, 9) << times_called;
stream << "\t" << detail.name;
}
return stream.str();
}
void StatsCalculator::OrderNodesByMetric(
SortingMetric metric, std::vector<const Detail*>* details) const {
std::priority_queue<std::pair<std::string, const Detail*>> sorted_list;
const int num_nodes = details_.size();
for (const auto& det : details_) {
const Detail* detail = &(det.second);
std::stringstream stream;
stream << std::setw(20) << std::right << std::setprecision(10)
<< std::fixed;
switch (metric) {
case BY_NAME:
stream << detail->name;
break;
case BY_RUN_ORDER:
stream << num_nodes - detail->run_order;
break;
case BY_TIME:
stream << detail->elapsed_time.avg();
break;
case BY_MEMORY:
stream << detail->mem_used.avg();
break;
case BY_TYPE:
stream << detail->type;
break;
default:
stream << "";
break;
}
sorted_list.emplace(stream.str(), detail);
}
while (!sorted_list.empty()) {
auto entry = sorted_list.top();
sorted_list.pop();
details->push_back(entry.second);
}
}
void StatsCalculator::ComputeStatsByType(
std::map<std::string, int64_t>* node_type_map_count,
std::map<std::string, int64_t>* node_type_map_time,
std::map<std::string, int64_t>* node_type_map_memory,
std::map<std::string, int64_t>* node_type_map_times_called,
int64_t* accumulated_us) const {
int64_t run_count = run_total_us_.count();
for (const auto& det : details_) {
const std::string node_name = det.first;
const Detail& detail = det.second;
int64_t curr_time_val =
static_cast<int64_t>(detail.elapsed_time.sum() / run_count);
*accumulated_us += curr_time_val;
int64_t curr_memory_val = detail.mem_used.newest();
const std::string& node_type = detail.type;
(*node_type_map_count)[node_type] += 1;
(*node_type_map_time)[node_type] += curr_time_val;
(*node_type_map_memory)[node_type] += curr_memory_val;
(*node_type_map_times_called)[node_type] += detail.times_called / run_count;
}
}
std::string StatsCalculator::GetStatsByNodeType() const {
std::stringstream stream;
stream << "Number of nodes executed: " << details_.size() << std::endl;
stream << "============================== Summary by node type "
"=============================="
<< std::endl;
std::map<std::string, int64_t> node_type_map_count;
std::map<std::string, int64_t> node_type_map_time;
std::map<std::string, int64_t> node_type_map_memory;
std::map<std::string, int64_t> node_type_map_times_called;
int64_t accumulated_us = 0;
ComputeStatsByType(&node_type_map_count, &node_type_map_time,
&node_type_map_memory, &node_type_map_times_called,
&accumulated_us);
std::priority_queue<std::pair<int64_t, std::pair<std::string, int64_t>>>
timings;
for (const auto& node_type : node_type_map_time) {
const int64_t mem_used = node_type_map_memory[node_type.first];
timings.emplace(node_type.second,
std::pair<std::string, int64_t>(node_type.first, mem_used));
}
if (options_.format_as_csv) {
stream << "node type, count, avg_ms, avg %, cdf %, mem KB, times called\n";
} else {
InitField(stream, kNodeTypeWidth) << "[Node type]";
InitField(stream, 9) << "[count]";
InitField(stream, 10) << "[avg ms]";
InitField(stream, 11) << "[avg %]";
InitField(stream, 11) << "[cdf %]";
InitField(stream, 10) << "[mem KB]";
InitField(stream, 10) << "[times called]";
stream << std::endl;
}
float cdf = 0.0f;
while (!timings.empty()) {
auto entry = timings.top();
timings.pop();
const std::string node_type = entry.second.first;
const float memory = entry.second.second / 1000.0f;
const int64_t node_type_total_us = entry.first;
const float time_per_run_ms = node_type_total_us / 1000.0f;
const float percentage =
((entry.first / static_cast<float>(accumulated_us)) * 100.0f);
cdf += percentage;
if (options_.format_as_csv) {
stream << node_type << ", " << node_type_map_count[node_type] << ", "
<< time_per_run_ms << ", " << percentage << "%, " << cdf << "%, "
<< memory << ", " << node_type_map_times_called[node_type]
<< std::endl;
} else {
InitField(stream, kNodeTypeWidth) << node_type;
InitField(stream, 9) << node_type_map_count[node_type];
InitField(stream, 10) << time_per_run_ms;
InitField(stream, 10) << percentage << "%";
InitField(stream, 10) << cdf << "%";
InitField(stream, 10) << memory;
InitField(stream, 9) << node_type_map_times_called[node_type];
stream << std::endl;
}
}
stream << std::endl;
return stream.str();
}
std::string StatsCalculator::GetStatsByMetric(const std::string& title,
SortingMetric sorting_metric,
int num_stats) const {
std::vector<const Detail*> details;
OrderNodesByMetric(sorting_metric, &details);
double cumulative_stat_on_node = 0;
std::stringstream stream;
stream << HeaderString(title) << std::endl;
int stat_num = 0;
for (auto detail : details) {
++stat_num;
if (num_stats > 0 && stat_num > num_stats) {
break;
}
cumulative_stat_on_node += detail->elapsed_time.sum();
stream << ColumnString(*detail, cumulative_stat_on_node, run_total_us_)
<< std::endl;
}
stream << std::endl;
return stream.str();
}
std::string StatsCalculator::GetOutputString() const {
std::stringstream stream;
if (options_.show_run_order) {
stream << GetStatsByMetric("Run Order", BY_RUN_ORDER,
options_.run_order_limit);
}
if (options_.show_time) {
stream << GetStatsByMetric("Top by Computation Time", BY_TIME,
options_.time_limit);
}
if (options_.show_memory) {
stream << GetStatsByMetric("Top by Memory Use", BY_MEMORY,
options_.memory_limit);
}
if (options_.show_type) {
stream << GetStatsByNodeType();
}
if (options_.show_summary) {
stream << GetShortSummary() << std::endl;
}
return stream.str();
}
void StatsCalculator::AddNodeStats(const std::string& name,
const std::string& type, int64_t run_order,
int64_t elapsed_time, int64_t mem_used) {
Detail* detail = nullptr;
if (details_.find(name) == details_.end()) {
details_.insert({name, {}});
detail = &details_.at(name);
detail->type = type;
detail->name = name;
detail->run_order = run_order;
} else {
detail = &details_.at(name);
}
detail->elapsed_time.UpdateStat(elapsed_time);
detail->mem_used.UpdateStat(mem_used);
detail->times_called++;
}
} | #include "xla/tsl/util/stats_calculator.h"
#include <cfloat>
#include "tsl/platform/test.h"
namespace tsl {
namespace {
using Detail = StatsCalculator::Detail;
TEST(StatsCalculatorTest, TotalTimeMs) {
auto options = StatSummarizerOptions();
StatsCalculator calc(options);
EXPECT_EQ(0, calc.num_runs());
calc.UpdateRunTotalUs(1);
EXPECT_EQ(1, calc.num_runs());
calc.UpdateRunTotalUs(2);
EXPECT_EQ(2, calc.num_runs());
auto run_time_us = calc.run_total_us();
EXPECT_EQ(1, run_time_us.min());
EXPECT_FLOAT_EQ(1.5, run_time_us.avg());
}
TEST(StatsCalculatorTest, AddNodeStatsUpdate) {
auto options = StatSummarizerOptions();
StatsCalculator calc(options);
EXPECT_TRUE(calc.GetDetails().empty());
const int64_t node1_run_order = 1;
const int64_t run1_start_us = 1;
const int64_t run1_end_us = 2;
const int64_t run1_mem_used = 45;
calc.AddNodeStats("node1", "type_1", node1_run_order,
run1_end_us - run1_start_us, run1_mem_used);
ASSERT_EQ(1, calc.GetDetails().size());
const Detail& detail = calc.GetDetails().at("node1");
EXPECT_EQ(1, detail.times_called);
EXPECT_EQ("node1", detail.name);
EXPECT_EQ("type_1", detail.type);
EXPECT_EQ(node1_run_order, detail.run_order);
const int64_t run2_start_us = 3;
const int64_t run2_end_us = 5;
const int64_t run2_mem_used = 145;
calc.AddNodeStats("node1", "type_1", node1_run_order,
run2_end_us - run2_start_us, run2_mem_used);
EXPECT_EQ(1, calc.GetDetails().size());
EXPECT_EQ(2, detail.times_called);
EXPECT_EQ("node1", detail.name);
EXPECT_EQ("type_1", detail.type);
EXPECT_EQ(node1_run_order, detail.run_order);
EXPECT_EQ((run1_end_us - run1_start_us) + (run2_end_us - run2_start_us),
detail.elapsed_time.sum());
EXPECT_EQ(run1_mem_used + run2_mem_used, detail.mem_used.sum());
}
TEST(StatsCalculatorTest, UpdateStat) {
Stat<double> stat;
EXPECT_TRUE(stat.empty());
EXPECT_TRUE(stat.all_same());
stat.UpdateStat(1);
EXPECT_TRUE(stat.all_same());
stat.UpdateStat(-1.0);
EXPECT_FALSE(stat.all_same());
stat.UpdateStat(100);
stat.UpdateStat(0);
EXPECT_EQ(4, stat.count());
EXPECT_EQ(-1, stat.min());
EXPECT_EQ(100, stat.max());
EXPECT_EQ(25, stat.avg());
EXPECT_EQ(1, stat.first());
EXPECT_EQ(0, stat.newest());
EXPECT_EQ(10002, stat.squared_sum());
EXPECT_EQ(625, stat.avg() * stat.avg());
EXPECT_EQ(7502.0 / 3, stat.sample_variance());
EXPECT_NEAR(50.00666622228147160678152, std::sqrt(stat.sample_variance()),
FLT_EPSILON);
EXPECT_NEAR(7502.0 / 4, stat.variance(), FLT_EPSILON);
EXPECT_NEAR(43.30704330706496060826769, stat.std_deviation(), FLT_EPSILON);
}
}
} | 2,249 |
#ifndef XLA_TSL_UTIL_DEVICE_NAME_UTILS_H_
#define XLA_TSL_UTIL_DEVICE_NAME_UTILS_H_
#include <string>
#include "tsl/platform/status.h"
#include "tsl/platform/stringpiece.h"
namespace tsl {
class DeviceNameUtils {
public:
static std::string FullName(const std::string& job, int replica, int task,
const std::string& type, int id);
struct ParsedName {
void Clear() {
has_job = false;
has_replica = false;
has_task = false;
has_type = false;
has_id = false;
job.clear();
replica = 0;
task = 0;
type.clear();
id = 0;
}
bool operator==(const ParsedName& other) const {
return (has_job ? (other.has_job && job == other.job) : !other.has_job) &&
(has_replica ? (other.has_replica && replica == other.replica)
: !other.has_replica) &&
(has_task ? (other.has_task && task == other.task)
: !other.has_task) &&
(has_type ? (other.has_type && type == other.type)
: !other.has_type) &&
(has_id ? (other.has_id && id == other.id) : !other.has_id);
}
bool operator!=(const ParsedName& other) const {
return !operator==(other);
}
bool operator<(const ParsedName& other) const {
if (has_job != other.has_job) return !has_job;
if (has_job) {
if (job < other.job) {
return true;
}
if (job > other.job) {
return false;
}
}
if (has_replica != other.has_replica) return !has_replica;
if (has_replica) {
if (replica < other.replica) {
return true;
}
if (replica > other.replica) {
return false;
}
}
if (has_task != other.has_task) return !has_task;
if (has_task) {
if (task < other.task) {
return true;
}
if (task > other.task) {
return false;
}
}
if (has_type != other.has_type) return !has_type;
if (has_type) {
if (type < other.type) {
return true;
}
if (type > other.type) {
return false;
}
}
if (has_id != other.has_id) return !has_id;
if (has_id) {
if (id < other.id) {
return true;
}
if (id > other.id) {
return false;
}
}
return false;
}
template <typename H>
friend H AbslHashValue(H h, const ParsedName& n) {
return H::combine(std::move(h), n.has_job ? n.job : "",
n.has_replica ? n.replica : 0, n.has_task ? n.task : 0,
n.has_type ? n.type : "", n.has_id ? n.id : 0);
}
bool has_job = false;
std::string job;
bool has_replica = false;
int replica = 0;
bool has_task = false;
int task = 0;
bool has_type = false;
std::string type;
bool has_id = false;
int id = 0;
};
static bool ParseFullOrLocalName(StringPiece fullname, ParsedName* parsed);
static bool ParseFullName(StringPiece fullname, ParsedName* parsed);
static absl::Status CanonicalizeDeviceName(StringPiece fullname,
StringPiece basename,
std::string* canonical_name);
static bool HasSomeDetails(const ParsedName& name) {
return name.has_job || name.has_replica || name.has_task || name.has_type ||
name.has_id;
}
static bool IsSpecification(const ParsedName& less_specific,
const ParsedName& more_specific);
static void EnsureSpecification(ParsedName* more_specific,
const ParsedName& less_specific);
static bool IsCompleteSpecification(const ParsedName& pattern,
const ParsedName& name);
static bool AreCompatibleDevNames(const ParsedName& a, const ParsedName& b);
static absl::Status MergeDevNames(ParsedName* target,
const ParsedName& other) {
return MergeDevNames(target, other, false);
}
static absl::Status MergeDevNames(ParsedName* target, const ParsedName& other,
bool allow_soft_placement);
static absl::Status MergeOverrideDevNames(ParsedName* target,
const ParsedName& other);
static void MergeUnsetDevNames(ParsedName* target, const ParsedName& other);
static bool IsSameAddressSpace(StringPiece src, StringPiece dst);
static bool IsSameAddressSpace(const ParsedName& src, const ParsedName& dst);
static bool IsDifferentAddressSpace(const ParsedName& a, const ParsedName& b);
static const ParsedName AddressSpace(const ParsedName& name);
static std::string LocalName(StringPiece type, int id);
static std::string LocalName(StringPiece fullname);
static bool ParseLocalName(StringPiece name, ParsedName* parsed);
static bool SplitDeviceName(StringPiece name, std::string* task,
std::string* device);
static bool GetTaskName(const ParsedName& pn, std::string* task);
static std::string ParsedNameToString(const ParsedName& pn);
static std::vector<string> GetNamesForDeviceMappings(const ParsedName& pn);
static std::vector<string> GetLocalNamesForDeviceMappings(
const ParsedName& pn);
static absl::Status DeviceNameToCpuDeviceName(const std::string& device_name,
std::string* host_device_name);
static bool CompareFullNames(const StringPiece& a, const StringPiece& b) {
ParsedName parsed_a;
ParsedName parsed_b;
bool a_status = ParseFullName(a, &parsed_a);
bool b_status = ParseFullName(b, &parsed_b);
if (a_status != b_status) return !a_status;
if (!a_status) return a < b;
return parsed_a < parsed_b;
}
};
std::ostream& operator<<(std::ostream& os,
const DeviceNameUtils::ParsedName& x);
}
#endif
#include "xla/tsl/util/device_name_utils.h"
#include <algorithm>
#include "tsl/platform/errors.h"
namespace tsl {
static bool IsAlpha(char c) {
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
}
static bool IsAlphaNumOrUnderscore(char c) {
return IsAlpha(c) || (c >= '0' && c <= '9') || c == '_';
}
static bool IsJobName(StringPiece in) {
return !in.empty() && IsAlpha(in.front()) &&
std::all_of(in.begin(), in.end(), IsAlphaNumOrUnderscore);
}
static bool ConsumePrefix(StringPiece* in, string* out,
StringPiece prefix_terminators) {
if (in->empty() || !IsAlpha(in->front())) return false;
const auto end_it =
std::find_first_of(in->begin(), in->end(), prefix_terminators.begin(),
prefix_terminators.end());
if (!std::all_of(in->begin(), end_it, IsAlphaNumOrUnderscore)) {
return false;
}
out->assign(in->begin(), end_it);
in->remove_prefix(end_it - in->begin());
return true;
}
static bool ConsumeJobName(StringPiece* in, string* job) {
return ConsumePrefix(in, job, "/");
}
static bool ConsumeDeviceType(StringPiece* in, string* device_type) {
return ConsumePrefix(in, device_type, "/:");
}
static bool ConsumeNumber(StringPiece* in, int* val) {
uint64 tmp;
if (str_util::ConsumeLeadingDigits(in, &tmp)) {
*val = tmp;
return true;
} else {
return false;
}
}
static string DeviceName(const string& job, int replica, int task,
const string& device_prefix, const string& device_type,
int id) {
CHECK(IsJobName(job)) << job;
CHECK_LE(0, replica);
CHECK_LE(0, task);
CHECK(!device_type.empty());
CHECK_LE(0, id);
return strings::StrCat("/job:", job, "/replica:", replica, "/task:", task,
device_prefix, device_type, ":", id);
}
string DeviceNameUtils::FullName(const string& job, int replica, int task,
const string& type, int id) {
return DeviceName(job, replica, task, "/device:", type, id);
}
namespace {
string LegacyName(const string& job, int replica, int task, const string& type,
int id) {
return DeviceName(job, replica, task, "/", absl::AsciiStrToLower(type), id);
}
}
bool DeviceNameUtils::ParseFullName(StringPiece fullname, ParsedName* p) {
p->Clear();
if (fullname == "/") {
return true;
}
while (!fullname.empty()) {
bool progress = false;
if (absl::ConsumePrefix(&fullname, "/job:")) {
p->has_job = !absl::ConsumePrefix(&fullname, "*");
if (p->has_job && !ConsumeJobName(&fullname, &p->job)) {
return false;
}
progress = true;
}
if (absl::ConsumePrefix(&fullname, "/replica:")) {
p->has_replica = !absl::ConsumePrefix(&fullname, "*");
if (p->has_replica && !ConsumeNumber(&fullname, &p->replica)) {
return false;
}
progress = true;
}
if (absl::ConsumePrefix(&fullname, "/task:")) {
p->has_task = !absl::ConsumePrefix(&fullname, "*");
if (p->has_task && !ConsumeNumber(&fullname, &p->task)) {
return false;
}
progress = true;
}
if (absl::ConsumePrefix(&fullname, "/device:")) {
p->has_type = !absl::ConsumePrefix(&fullname, "*");
if (p->has_type && !ConsumeDeviceType(&fullname, &p->type)) {
return false;
}
if (!absl::ConsumePrefix(&fullname, ":")) {
p->has_id = false;
} else {
p->has_id = !absl::ConsumePrefix(&fullname, "*");
if (p->has_id && !ConsumeNumber(&fullname, &p->id)) {
return false;
}
}
progress = true;
}
if (absl::ConsumePrefix(&fullname, "/cpu:") ||
absl::ConsumePrefix(&fullname, "/CPU:")) {
p->has_type = true;
p->type = "CPU";
p->has_id = !absl::ConsumePrefix(&fullname, "*");
if (p->has_id && !ConsumeNumber(&fullname, &p->id)) {
return false;
}
progress = true;
}
if (absl::ConsumePrefix(&fullname, "/gpu:") ||
absl::ConsumePrefix(&fullname, "/GPU:")) {
p->has_type = true;
p->type = "GPU";
p->has_id = !absl::ConsumePrefix(&fullname, "*");
if (p->has_id && !ConsumeNumber(&fullname, &p->id)) {
return false;
}
progress = true;
}
if (!progress) {
return false;
}
}
return true;
}
bool DeviceNameUtils::ParseFullOrLocalName(StringPiece fullname,
ParsedName* p) {
return ParseFullName(fullname, p) || ParseLocalName(fullname, p);
}
namespace {
void CompleteName(const DeviceNameUtils::ParsedName& parsed_basename,
DeviceNameUtils::ParsedName* parsed_name) {
if (!parsed_name->has_job) {
parsed_name->job = parsed_basename.job;
parsed_name->has_job = true;
}
if (!parsed_name->has_replica) {
parsed_name->replica = parsed_basename.replica;
parsed_name->has_replica = true;
}
if (!parsed_name->has_task) {
parsed_name->task = parsed_basename.task;
parsed_name->has_task = true;
}
if (!parsed_name->has_type) {
parsed_name->type = parsed_basename.type;
parsed_name->has_type = true;
}
if (!parsed_name->has_id) {
parsed_name->id = parsed_basename.id;
parsed_name->has_id = true;
}
}
}
absl::Status DeviceNameUtils::CanonicalizeDeviceName(StringPiece fullname,
StringPiece basename,
string* canonical_name) {
*canonical_name = "";
ParsedName parsed_basename;
if (!ParseFullName(basename, &parsed_basename)) {
return errors::InvalidArgument("Could not parse basename: ", basename,
" into a device specification.");
}
if (!(parsed_basename.has_job && parsed_basename.has_replica &&
parsed_basename.has_task && parsed_basename.has_type &&
parsed_basename.has_id)) {
return errors::InvalidArgument("Basename: ", basename,
" should be fully "
"specified.");
}
ParsedName parsed_name;
if (ParseLocalName(fullname, &parsed_name)) {
CompleteName(parsed_basename, &parsed_name);
*canonical_name = ParsedNameToString(parsed_name);
return absl::OkStatus();
}
if (ParseFullName(fullname, &parsed_name)) {
CompleteName(parsed_basename, &parsed_name);
*canonical_name = ParsedNameToString(parsed_name);
return absl::OkStatus();
}
return errors::InvalidArgument("Could not parse ", fullname,
" into a device "
"specification.");
}
string DeviceNameUtils::ParsedNameToString(const ParsedName& pn) {
string buf;
if (pn.has_job) strings::StrAppend(&buf, "/job:", pn.job);
if (pn.has_replica) strings::StrAppend(&buf, "/replica:", pn.replica);
if (pn.has_task) strings::StrAppend(&buf, "/task:", pn.task);
if (pn.has_type) {
strings::StrAppend(&buf, "/device:", pn.type, ":");
if (pn.has_id) {
strings::StrAppend(&buf, pn.id);
} else {
strings::StrAppend(&buf, "*");
}
}
return buf;
}
bool DeviceNameUtils::IsSpecification(const ParsedName& less_specific,
const ParsedName& more_specific) {
if (less_specific.has_job &&
(!more_specific.has_job || (less_specific.job != more_specific.job))) {
return false;
}
if (less_specific.has_replica &&
(!more_specific.has_replica ||
(less_specific.replica != more_specific.replica))) {
return false;
}
if (less_specific.has_task &&
(!more_specific.has_task || (less_specific.task != more_specific.task))) {
return false;
}
if (less_specific.has_type &&
(!more_specific.has_type || (less_specific.type != more_specific.type))) {
return false;
}
if (less_specific.has_id &&
(!more_specific.has_id || (less_specific.id != more_specific.id))) {
return false;
}
return true;
}
bool DeviceNameUtils::AreCompatibleDevNames(const ParsedName& a,
const ParsedName& b) {
if (a.has_job && b.has_job && (a.job != b.job)) {
return false;
}
if (a.has_replica && b.has_replica && (a.replica != b.replica)) {
return false;
}
if (a.has_task && b.has_task && (a.task != b.task)) {
return false;
}
if (a.has_type && b.has_type && (a.type != b.type)) {
return false;
}
if (a.has_id && b.has_id && (a.id != b.id)) {
return false;
}
return true;
}
void DeviceNameUtils::EnsureSpecification(ParsedName* more_specific,
const ParsedName& less_specific) {
if (less_specific.has_job) {
more_specific->has_job = true;
more_specific->job = less_specific.job;
}
if (less_specific.has_replica) {
more_specific->has_replica = true;
more_specific->replica = less_specific.replica;
}
if (less_specific.has_task) {
more_specific->has_task = true;
more_specific->task = less_specific.task;
}
if (less_specific.has_type) {
more_specific->has_type = true;
more_specific->type = less_specific.type;
}
if (less_specific.has_id) {
more_specific->has_id = true;
more_specific->id = less_specific.id;
}
}
bool DeviceNameUtils::IsCompleteSpecification(const ParsedName& pattern,
const ParsedName& name) {
CHECK(name.has_job && name.has_replica && name.has_task && name.has_type &&
name.has_id);
if (pattern.has_job && (pattern.job != name.job)) return false;
if (pattern.has_replica && (pattern.replica != name.replica)) return false;
if (pattern.has_task && (pattern.task != name.task)) return false;
if (pattern.has_type && (pattern.type != name.type)) return false;
if (pattern.has_id && (pattern.id != name.id)) return false;
return true;
}
namespace {
absl::Status MergeDevNamesImpl(DeviceNameUtils::ParsedName* target,
const DeviceNameUtils::ParsedName& other,
bool allow_soft_placement,
bool override_conflicts) {
const auto& ParsedNameToString = DeviceNameUtils::ParsedNameToString;
if (other.has_job) {
if (target->has_job && target->job != other.job) {
return errors::InvalidArgument(
"Cannot merge devices with incompatible jobs: '",
ParsedNameToString(*target), "' and '", ParsedNameToString(other),
"'");
} else {
target->has_job = other.has_job;
target->job = other.job;
}
}
if (other.has_replica) {
if (target->has_replica && target->replica != other.replica) {
return errors::InvalidArgument(
"Cannot merge devices with incompatible replicas: '",
ParsedNameToString(*target), "' and '", ParsedNameToString(other),
"'");
} else {
target->has_replica = other.has_replica;
target->replica = other.replica;
}
}
if (other.has_task) {
if (target->has_task && target->task != other.task) {
return errors::InvalidArgument(
"Cannot merge devices with incompatible tasks: '",
ParsedNameToString(*target), "' and '", ParsedNameToString(other),
"'");
} else {
target->has_task = other.has_task;
target->task = other.task;
}
}
if (other.has_type) {
if (target->has_type && target->type != other.type) {
if (!allow_soft_placement) {
return errors::InvalidArgument(
"Cannot merge devices with incompatible types: '",
ParsedNameToString(*target), "' and '", ParsedNameToString(other),
"'");
} else if (override_conflicts) {
target->type = other.type;
} else {
target->has_id = false;
target->has_type = false;
return absl::OkStatus();
}
} else {
target->has_type = other.has_type;
target->type = other.type;
}
}
if (other.has_id) {
if (target->has_id && target->id != other.id) {
if (!allow_soft_placement) {
return errors::InvalidArgument(
"Cannot merge devices with incompatible ids: '",
ParsedNameToString(*target), "' and '", ParsedNameToString(other),
"'");
} else if (override_conflicts) {
target->id = other.id;
} else {
target->has_id = false;
return absl::OkStatus();
}
} else {
target->has_id = other.has_id;
target->id = other.id;
}
}
return absl::OkStatus();
}
}
absl::Status DeviceNameUtils::MergeDevNames(ParsedName* target,
const ParsedName& other,
bool allow_soft_placement) {
return MergeDevNamesImpl(target, other, allow_soft_placement,
false);
}
absl::Status DeviceNameUtils::MergeOverrideDevNames(ParsedName* target,
const ParsedName& other) {
return MergeDevNamesImpl(target, other, true,
true);
}
void DeviceNameUtils::MergeUnsetDevNames(ParsedName* target,
const ParsedName& other) {
if (other.has_job && !target->has_job) {
target->has_job = other.has_job;
target->job = other.job;
}
if (other.has_replica && !target->has_replica) {
target->has_replica = other.has_replica;
target->replica = other.replica;
}
if (other.has_task && !target->has_task) {
target->has_task = other.has_task;
target->task = other.task;
}
if (other.has_type && !target->has_type) {
target->has_type = other.has_type;
target->type = other.type;
}
if (other.has_id && !target->has_id) {
target->has_id = other.has_id;
target->id = other.id;
}
}
bool DeviceNameUtils::IsSameAddressSpace(const ParsedName& a,
const ParsedName& b) {
return (a.has_job && b.has_job && (a.job == b.job)) &&
(a.has_replica && b.has_replica && (a.replica == b.replica)) &&
(a.has_task && b.has_task && (a.task == b.task));
}
bool DeviceNameUtils::IsSameAddressSpace(StringPiece src, StringPiece dst) {
ParsedName x;
ParsedName y;
return ParseFullName(src, &x) && ParseFullName(dst, &y) &&
IsSameAddressSpace(x, y);
}
bool DeviceNameUtils::IsDifferentAddressSpace(const ParsedName& a,
const ParsedName& b) {
return (a.has_job && b.has_job && (a.job != b.job)) ||
(a.has_replica && b.has_replica && (a.replica != b.replica)) ||
(a.has_task && b.has_task && (a.task != b.task));
}
const DeviceNameUtils::ParsedName DeviceNameUtils::AddressSpace(
const ParsedName& name) {
ParsedName address_space;
address_space.has_job = name.has_job;
address_space.has_replica = name.has_replica;
address_space.has_task = name.has_task;
address_space.job = name.job;
address_space.replica = name.replica;
address_space.task = name.task;
return address_space;
}
string DeviceNameUtils::LocalName(StringPiece type, int id) {
return strings::StrCat("/device:", type, ":", id);
}
namespace {
string LegacyLocalName(StringPiece type, int id) {
return strings::StrCat(type, ":", id);
}
}
string DeviceNameUtils::LocalName(StringPiece fullname) {
ParsedName x;
CHECK(ParseFullName(fullname, &x)) << fullname;
return LocalName(x.type, x.id);
}
bool DeviceNameUtils::ParseLocalName(StringPiece name, ParsedName* p) {
if (!ConsumeDeviceType(&name, &p->type)) {
return false;
}
p->has_type = true;
if (!absl::ConsumePrefix(&name, ":")) {
return false;
}
if (!ConsumeNumber(&name, &p->id)) {
return false;
}
p->has_id = true;
return name.empty();
}
bool DeviceNameUtils::SplitDeviceName(StringPiece name, string* task,
string* device) {
ParsedName pn;
if (ParseFullName(name, &pn) && pn.has_type && pn.has_id) {
task->clear();
task->reserve(
(pn.has_job ? (5 + pn.job.size()) : 0) +
(pn.has_replica ? (9 + 4 ) : 0) +
(pn.has_task ? (6 + 4 ) : 0));
if (pn.has_job) {
strings::StrAppend(task, "/job:", pn.job);
}
if (pn.has_replica) {
strings::StrAppend(task, "/replica:", pn.replica);
}
if (pn.has_task) {
strings::StrAppend(task, "/task:", pn.task);
}
device->clear();
strings::StrAppend(device, pn.type, ":", pn.id);
return true;
}
return false;
}
bool DeviceNameUtils::GetTaskName(const ParsedName& pn, string* task) {
if (pn.has_job && pn.has_replica && pn.has_task) {
task->clear();
task->reserve((5 + pn.job.size()) +
(9 + 4 ) +
(6 + 4 ));
strings::StrAppend(task, "/job:", pn.job);
strings::StrAppend(task, "/replica:", pn.replica);
strings::StrAppend(task, "/task:", pn.task);
return true;
}
return false;
}
std::vector<string> DeviceNameUtils::GetNamesForDeviceMappings(
const ParsedName& pn) {
if (pn.has_job && pn.has_replica && pn.has_task && pn.has_type && pn.has_id) {
return {
DeviceNameUtils::FullName(pn.job, pn.replica, pn.task, pn.type, pn.id),
LegacyName(pn.job, pn.replica, pn.task, pn.type, pn.id)};
} else {
return {};
}
}
std::vector<string> DeviceNameUtils::GetLocalNamesForDeviceMappings(
const ParsedName& pn) {
if (pn.has_type && pn.has_id) {
return {DeviceNameUtils::LocalName(pn.type, pn.id),
LegacyLocalName(pn.type, pn.id)};
} else {
return {};
}
}
absl::Status DeviceNameUtils::DeviceNameToCpuDeviceName(
const string& device_name, string* host_device_name) {
DeviceNameUtils::ParsedName device;
if (!DeviceNameUtils::ParseFullName(device_name, &device)) {
return errors::Internal("Could not parse device name ", device_name);
}
device.type = "CPU";
device.has_type = true;
device.id = 0;
device.has_id = true;
*host_device_name = DeviceNameUtils::ParsedNameToString(device);
return absl::OkStatus();
}
std::ostream& operator<<(std::ostream& os,
const DeviceNameUtils::ParsedName& x) {
os << DeviceNameUtils::ParsedNameToString(x);
return os;
}
} | #include "xla/tsl/util/device_name_utils.h"
#include <vector>
#include "tsl/lib/core/status_test_util.h"
#include "tsl/platform/errors.h"
#include "tsl/platform/strcat.h"
#include "tsl/platform/test.h"
#include "tsl/platform/test_benchmark.h"
namespace tsl {
namespace {
bool RoundTripParsedName(const string& original, const string& expected) {
DeviceNameUtils::ParsedName p;
if (!DeviceNameUtils::ParseFullName(original, &p)) {
return false;
}
string round_tripped = DeviceNameUtils::ParsedNameToString(p);
return (round_tripped == expected);
}
enum NamePart { kJob = 0x01, kReplica = 0x02, kTask = 0x04, kDevice = 0x08 };
bool RoundTripPartialName(int parts_to_test, const std::vector<string>& parts,
bool explicitDevice) {
string original, expected;
if (parts_to_test & kJob) {
strings::StrAppend(&original, "/job:", parts[0]);
strings::StrAppend(&expected, "/job:", parts[0]);
}
if (parts_to_test & kReplica) {
strings::StrAppend(&original, "/replica:", parts[1]);
strings::StrAppend(&expected, "/replica:", parts[1]);
}
if (parts_to_test & kTask) {
strings::StrAppend(&original, "/task:", parts[2]);
strings::StrAppend(&expected, "/task:", parts[2]);
}
if (parts_to_test & kDevice) {
if (explicitDevice) {
strings::StrAppend(&original, "/device:", parts[3]);
strings::StrAppend(&expected, "/device:", parts[3]);
} else {
strings::StrAppend(&original, "/", parts[3]);
strings::StrAppend(&expected,
"/device:", absl::AsciiStrToUpper(parts[3]));
}
}
return RoundTripParsedName(original, expected);
}
}
TEST(DeviceNameUtilsTest, Basic) {
EXPECT_EQ(DeviceNameUtils::FullName("hello", 1, 2, "CPU", 3),
"/job:hello/replica:1/task:2/device:CPU:3");
{
DeviceNameUtils::ParsedName p;
EXPECT_FALSE(DeviceNameUtils::ParseFullName("foobar", &p));
EXPECT_FALSE(DeviceNameUtils::ParseFullName(
"/job:123/replica:1/task:2/device:GPU:3", &p));
EXPECT_FALSE(
DeviceNameUtils::ParseFullName("/job:123/replica:1/task:2/gpu:", &p));
EXPECT_FALSE(DeviceNameUtils::ParseFullName(
"/job:123/replica:1/task:2/device:gpu:", &p));
EXPECT_FALSE(DeviceNameUtils::ParseFullName(
"/job:foo/replica:-1/task:2/device:GPU:3", &p));
EXPECT_FALSE(DeviceNameUtils::ParseFullName(
"/job:foo/replica:1/task:-2/device:GPU:3", &p));
EXPECT_FALSE(
DeviceNameUtils::ParseFullName("/job:foo/replica:1/task:2/bar:3", &p));
EXPECT_FALSE(DeviceNameUtils::ParseFullName(
"/job:foo/replica:1/task:2/device:GPU:3/extra", &p));
EXPECT_TRUE(DeviceNameUtils::ParseFullName(
"/job:foo/replica:1/task:2/device:GPU:3", &p));
EXPECT_TRUE(p.has_job);
EXPECT_TRUE(p.has_replica);
EXPECT_TRUE(p.has_task);
EXPECT_TRUE(p.has_type);
EXPECT_TRUE(p.has_id);
EXPECT_EQ(p.job, "foo");
EXPECT_EQ(p.replica, 1);
EXPECT_EQ(p.task, 2);
EXPECT_EQ(p.type, "GPU");
EXPECT_EQ(p.id, 3);
}
{
DeviceNameUtils::ParsedName p;
EXPECT_TRUE(DeviceNameUtils::ParseFullName(
"/job:foo_bar/replica:1/task:2/device:GPU:3", &p));
EXPECT_TRUE(DeviceNameUtils::ParseFullOrLocalName(
"/job:foo_bar/replica:1/task:2/device:GPU:3", &p));
EXPECT_TRUE(p.has_job);
EXPECT_TRUE(p.has_replica);
EXPECT_TRUE(p.has_task);
EXPECT_TRUE(p.has_type);
EXPECT_TRUE(p.has_id);
EXPECT_EQ(p.job, "foo_bar");
EXPECT_EQ(p.replica, 1);
EXPECT_EQ(p.task, 2);
EXPECT_EQ(p.type, "GPU");
EXPECT_EQ(p.id, 3);
}
{
DeviceNameUtils::ParsedName p;
EXPECT_TRUE(DeviceNameUtils::ParseFullName(
"/job:foo_bar/replica:1/task:2/device:GPU:3", &p));
EXPECT_TRUE(p.has_job);
EXPECT_TRUE(p.has_replica);
EXPECT_TRUE(p.has_task);
EXPECT_TRUE(p.has_type);
EXPECT_TRUE(p.has_id);
EXPECT_EQ(p.job, "foo_bar");
EXPECT_EQ(p.replica, 1);
EXPECT_EQ(p.task, 2);
EXPECT_EQ(p.type, "GPU");
EXPECT_EQ(p.id, 3);
}
{
DeviceNameUtils::ParsedName p;
EXPECT_TRUE(DeviceNameUtils::ParseFullName("/job:*/replica:4/gpu:*", &p));
EXPECT_FALSE(p.has_job);
EXPECT_TRUE(p.has_replica);
EXPECT_FALSE(p.has_task);
EXPECT_TRUE(p.has_type);
EXPECT_FALSE(p.has_id);
EXPECT_EQ(p.replica, 4);
EXPECT_EQ(p.type, "GPU");
}
{
DeviceNameUtils::ParsedName p;
EXPECT_TRUE(
DeviceNameUtils::ParseFullName("/job:*/replica:4/device:GPU:*", &p));
EXPECT_FALSE(p.has_job);
EXPECT_TRUE(p.has_replica);
EXPECT_FALSE(p.has_task);
EXPECT_TRUE(p.has_type);
EXPECT_FALSE(p.has_id);
EXPECT_EQ(p.replica, 4);
EXPECT_EQ(p.type, "GPU");
}
{
DeviceNameUtils::ParsedName p;
EXPECT_TRUE(
DeviceNameUtils::ParseFullName("/job:*/device:GPU/replica:4", &p));
EXPECT_FALSE(p.has_job);
EXPECT_TRUE(p.has_replica);
EXPECT_FALSE(p.has_task);
EXPECT_TRUE(p.has_type);
EXPECT_FALSE(p.has_id);
EXPECT_EQ(p.replica, 4);
EXPECT_EQ(p.type, "GPU");
}
{
DeviceNameUtils::ParsedName p;
EXPECT_TRUE(DeviceNameUtils::ParseFullName(
"/job:*/replica:4/device:myspecialdevice:13", &p));
EXPECT_FALSE(p.has_job);
EXPECT_TRUE(p.has_replica);
EXPECT_FALSE(p.has_task);
EXPECT_TRUE(p.has_type);
EXPECT_TRUE(p.has_id);
EXPECT_EQ(p.replica, 4);
EXPECT_EQ(p.type, "myspecialdevice");
EXPECT_EQ(p.id, 13);
}
{
DeviceNameUtils::ParsedName p;
EXPECT_TRUE(DeviceNameUtils::ParseFullName("/", &p));
EXPECT_FALSE(p.has_job);
EXPECT_FALSE(p.has_replica);
EXPECT_FALSE(p.has_task);
EXPECT_FALSE(p.has_type);
EXPECT_FALSE(p.has_id);
}
{
DeviceNameUtils::ParsedName p;
EXPECT_TRUE(
DeviceNameUtils::ParseFullName("/job:*/replica:4/device:GPU:5", &p));
EXPECT_FALSE(p.has_job);
EXPECT_TRUE(p.has_replica);
EXPECT_FALSE(p.has_task);
EXPECT_TRUE(p.has_type);
EXPECT_TRUE(p.has_id);
EXPECT_EQ(p.replica, 4);
EXPECT_EQ(p.type, "GPU");
EXPECT_EQ(p.id, 5);
}
{
DeviceNameUtils::ParsedName p;
EXPECT_TRUE(DeviceNameUtils::ParseFullName("/gpu:*/job:*/replica:4", &p));
EXPECT_FALSE(p.has_job);
EXPECT_TRUE(p.has_replica);
EXPECT_FALSE(p.has_task);
EXPECT_TRUE(p.has_type);
EXPECT_FALSE(p.has_id);
EXPECT_EQ(p.replica, 4);
EXPECT_EQ(p.type, "GPU");
}
EXPECT_TRUE(DeviceNameUtils::IsSameAddressSpace(
"/job:foo/replica:1/task:2/cpu:3",
"/job:foo/replica:1/task:2/device:GPU:4"));
EXPECT_FALSE(DeviceNameUtils::IsSameAddressSpace(
"/job:foo/replica:1/task:2/cpu:3",
"/job:foo/replica:1/task:3/device:GPU:4"));
EXPECT_FALSE(DeviceNameUtils::IsSameAddressSpace(
"/job:foo/replica:1/task:2/cpu:3",
"/job:foo/replica:10/task:2/device:GPU:4"));
EXPECT_FALSE(DeviceNameUtils::IsSameAddressSpace(
"/job:foo/replica:1/task:2/cpu:3",
"/job:bar/replica:1/task:2/device:GPU:4"));
EXPECT_EQ(DeviceNameUtils::LocalName("CPU", 1), "/device:CPU:1");
EXPECT_EQ(DeviceNameUtils::LocalName("GPU", 2), "/device:GPU:2");
EXPECT_EQ(DeviceNameUtils::LocalName("MySpecialDevice", 13),
"/device:MySpecialDevice:13");
EXPECT_EQ(
DeviceNameUtils::LocalName("/job:foo/replica:1/task:2/device:CPU:3"),
"/device:CPU:3");
EXPECT_EQ(DeviceNameUtils::LocalName("/job:foo/replica:1/task:2/cpu:3"),
"/device:CPU:3");
EXPECT_EQ(
DeviceNameUtils::LocalName("/job:foo/replica:1/task:2/device:abc:73"),
"/device:abc:73");
{
DeviceNameUtils::ParsedName p;
EXPECT_TRUE(DeviceNameUtils::ParseLocalName("CPU:10", &p));
EXPECT_TRUE(DeviceNameUtils::ParseFullOrLocalName("CPU:10", &p));
EXPECT_EQ(p.type, "CPU");
EXPECT_EQ(p.id, 10);
EXPECT_FALSE(DeviceNameUtils::ParseLocalName("cpu:abc", &p));
EXPECT_FALSE(DeviceNameUtils::ParseLocalName("abc:", &p));
EXPECT_FALSE(DeviceNameUtils::ParseLocalName("abc", &p));
EXPECT_FALSE(DeviceNameUtils::ParseLocalName("myspecialdevice", &p));
EXPECT_FALSE(DeviceNameUtils::ParseFullOrLocalName("myspecialdevice", &p));
}
{
for (int i = 0; i < 0x10; ++i) {
EXPECT_TRUE(RoundTripPartialName(i, {"foo", "3", "2", "CPU:3"},
false));
EXPECT_TRUE(RoundTripPartialName(i, {"foo", "3", "2", "GPU:3"},
false));
EXPECT_TRUE(RoundTripPartialName(i, {"foo", "3", "2", "cpu:3"},
false));
EXPECT_TRUE(RoundTripPartialName(i, {"foo", "3", "2", "gpu:3"},
false));
EXPECT_TRUE(RoundTripPartialName(i, {"foo", "3", "2", "CPU:3"},
true));
EXPECT_TRUE(RoundTripPartialName(i, {"foo", "3", "2", "GPU:3"},
true));
EXPECT_TRUE(RoundTripPartialName(i, {"foo", "3", "2", "cpu:3"},
true));
EXPECT_TRUE(RoundTripPartialName(i, {"foo", "3", "2", "gpu:3"},
true));
EXPECT_TRUE(RoundTripPartialName(i, {"foo", "3", "2", "someDevice:3"},
true));
}
}
{
DeviceNameUtils::ParsedName x, y;
DeviceNameUtils::ParseFullName("/job:work/replica:1/task:3/device:GPU:*",
&x);
DeviceNameUtils::ParseFullName("/device:CPU:*", &y);
EXPECT_FALSE(DeviceNameUtils::AreCompatibleDevNames(x, y));
}
{
DeviceNameUtils::ParsedName x, y;
DeviceNameUtils::ParseFullName("/job:work/replica:1/task:3", &x);
DeviceNameUtils::ParseFullName("/device:CPU:*", &y);
EXPECT_TRUE(DeviceNameUtils::AreCompatibleDevNames(x, y));
}
}
static bool IsCSHelper(StringPiece pattern, StringPiece actual) {
DeviceNameUtils::ParsedName p, a;
EXPECT_TRUE(DeviceNameUtils::ParseFullName(pattern, &p));
EXPECT_TRUE(DeviceNameUtils::ParseFullName(actual, &a));
return DeviceNameUtils::IsCompleteSpecification(p, a);
}
TEST(DeviceNameUtilsTest, IsCompleteSpecification) {
EXPECT_TRUE(IsCSHelper("/job:*", "/job:work/replica:1/task:2/device:GPU:3"));
EXPECT_TRUE(IsCSHelper("/job:*/replica:*",
"/job:work/replica:1/task:2/device:GPU:3"));
EXPECT_TRUE(
IsCSHelper("/job:*/task:*", "/job:work/replica:1/task:2/device:GPU:3"));
EXPECT_TRUE(IsCSHelper("/job:*/replica:*/task:*",
"/job:work/replica:1/task:2/device:GPU:3"));
EXPECT_TRUE(IsCSHelper("/job:*/replica:*/gpu:*",
"/job:work/replica:1/task:2/device:GPU:3"));
EXPECT_FALSE(
IsCSHelper("/cpu:*", "/job:worker/replica:1/task:2/device:GPU:3"));
EXPECT_FALSE(
IsCSHelper("/device:GPU:2", "/job:worker/replica:1/task:2/device:GPU:1"));
EXPECT_TRUE(
IsCSHelper("/gpu:*", "/job:worker/replica:1/task:2/device:GPU:3"));
}
static bool IsSpecHelper(StringPiece pattern, StringPiece actual) {
DeviceNameUtils::ParsedName p, a;
EXPECT_TRUE(DeviceNameUtils::ParseFullName(pattern, &p));
EXPECT_TRUE(DeviceNameUtils::ParseFullName(actual, &a));
return DeviceNameUtils::IsSpecification(p, a);
}
TEST(DeviceNameUtilsTest, IsSpecification) {
EXPECT_TRUE(
IsSpecHelper("/job:*", "/job:work/replica:1/task:2/device:GPU:3"));
EXPECT_TRUE(IsSpecHelper("/job:*", "/job:work/replica:1/device:GPU:3"));
EXPECT_TRUE(IsSpecHelper("/job:*", "/job:work/replica:1"));
EXPECT_TRUE(IsSpecHelper("/job:*", "/replica:1"));
EXPECT_TRUE(IsSpecHelper("/job:*", "/job:work"));
EXPECT_TRUE(IsSpecHelper("/job:*/replica:*",
"/job:work/replica:1/task:2/device:GPU:3"));
EXPECT_TRUE(IsSpecHelper("/job:work/replica:1/gpu:*",
"/job:work/replica:1/task:2/device:GPU:3"));
EXPECT_TRUE(IsSpecHelper("/job:work/replica:1/device:GPU:3",
"/job:work/replica:1/task:2/device:GPU:3"));
EXPECT_TRUE(IsSpecHelper("/job:work/replica:1/task:2",
"/job:work/replica:1/task:2/device:GPU:3"));
EXPECT_TRUE(IsSpecHelper("/job:work/replica:*/task:2",
"/job:work/replica:1/task:2/device:GPU:3"));
EXPECT_TRUE(IsSpecHelper("/task:*", "/job:*/replica:1/task:2/device:GPU:3"));
EXPECT_TRUE(IsSpecHelper("/task:2", "/job:*/replica:1/task:2/device:GPU:3"));
EXPECT_TRUE(IsSpecHelper("/cpu:*", "/job:*/replica:1/task:2/cpu:1"));
EXPECT_TRUE(IsSpecHelper("/cpu:0", "/cpu:0"));
EXPECT_TRUE(
IsSpecHelper("/gpu:*", "/job:worker/replica:1/task:2/device:GPU:3"));
EXPECT_FALSE(
IsSpecHelper("/job:worker/replica:1/task:2/device:GPU:3", "/gpu:*"));
EXPECT_FALSE(IsSpecHelper("/cpu:*", "/job:*/replica:1/task:2"));
EXPECT_FALSE(IsSpecHelper("/cpu:*", "/job:*/replica:1/task:2/device:GPU:1"));
EXPECT_FALSE(
IsSpecHelper("/cpu:*", "/job:worker/replica:1/task:2/device:GPU:3"));
EXPECT_FALSE(IsSpecHelper("/device:GPU:2",
"/job:worker/replica:1/task:2/device:GPU:1"));
EXPECT_FALSE(IsSpecHelper("/job:work/replica:*/task:0",
"/job:work/replica:1/task:2/device:GPU:3"));
EXPECT_FALSE(IsSpecHelper("/job:work/replica:0/task:2",
"/job:work/replica:*/task:2/device:GPU:3"));
}
TEST(DeviceNameUtilsTest, SplitDeviceName) {
string task;
string device;
EXPECT_TRUE(DeviceNameUtils::SplitDeviceName(
"/job:foo/replica:1/task:2/cpu:1", &task, &device));
EXPECT_EQ("/job:foo/replica:1/task:2", task);
EXPECT_EQ("CPU:1", device);
EXPECT_TRUE(DeviceNameUtils::SplitDeviceName(
"/job:foo/cpu:1/task:2/replica:1", &task, &device));
EXPECT_EQ("/job:foo/replica:1/task:2", task);
EXPECT_EQ("CPU:1", device);
EXPECT_TRUE(
DeviceNameUtils::SplitDeviceName("/device:GPU:3", &task, &device));
EXPECT_EQ("", task);
EXPECT_EQ("GPU:3", device);
EXPECT_FALSE(DeviceNameUtils::SplitDeviceName("gpu:3", &task, &device));
EXPECT_FALSE(DeviceNameUtils::SplitDeviceName("/job:foo/task:2/replica:1",
&task, &device));
EXPECT_TRUE(DeviceNameUtils::SplitDeviceName("/device:myspecialdevice:3",
&task, &device));
EXPECT_EQ("", task);
EXPECT_EQ("myspecialdevice:3", device);
}
static DeviceNameUtils::ParsedName Name(const string& str) {
DeviceNameUtils::ParsedName ret;
CHECK(DeviceNameUtils::ParseFullName(str, &ret)) << "Invalid name: " << str;
return ret;
}
static void MergeDevNamesHelperImpl(const string& name_a, const string& name_b,
const string& expected_merge_name,
bool allow_soft_placement) {
DeviceNameUtils::ParsedName target_a = Name(name_a);
TF_EXPECT_OK(DeviceNameUtils::MergeDevNames(&target_a, Name(name_b),
allow_soft_placement));
DeviceNameUtils::ParsedName target_b = Name(name_b);
TF_EXPECT_OK(DeviceNameUtils::MergeDevNames(&target_b, Name(name_a),
allow_soft_placement));
EXPECT_EQ(target_a, target_b);
EXPECT_EQ(target_a, Name(expected_merge_name));
EXPECT_EQ(target_b, Name(expected_merge_name));
}
static void MergeDevNamesHelper(const string& name_a, const string& name_b,
const string& expected_merge_name) {
MergeDevNamesHelperImpl(name_a, name_b, expected_merge_name, false);
}
static void MergeDevNamesHelperAllowSoftPlacement(
const string& name_a, const string& name_b,
const string& expected_merge_name) {
MergeDevNamesHelperImpl(name_a, name_b, expected_merge_name, true);
}
static void MergeDevNamesError(const string& name_a, const string& name_b,
const string& expected_error_substr) {
DeviceNameUtils::ParsedName target_a = Name(name_a);
absl::Status s = DeviceNameUtils::MergeDevNames(&target_a, Name(name_b));
EXPECT_EQ(s.code(), error::INVALID_ARGUMENT);
EXPECT_TRUE(absl::StrContains(s.message(), expected_error_substr)) << s;
}
static void MergeOverrideHelper(const string& target, const string& name,
const string& expected_merge_name) {
DeviceNameUtils::ParsedName parsed_target = Name(target);
TF_EXPECT_OK(
DeviceNameUtils::MergeOverrideDevNames(&parsed_target, Name(name)));
DeviceNameUtils::ParsedName parsed_expected = Name(expected_merge_name);
EXPECT_EQ(parsed_target, parsed_expected)
<< "parsed_target: " << DeviceNameUtils::ParsedNameToString(parsed_target)
<< " expected_name: "
<< DeviceNameUtils::ParsedNameToString(parsed_expected);
}
static void MergeUnsetDevNamesHelper(const string& name_a, const string& name_b,
const string& expected_merge_name_ab,
const string& expected_merge_name_ba) {
DeviceNameUtils::ParsedName target_a = Name(name_a);
DeviceNameUtils::MergeUnsetDevNames(&target_a, Name(name_b));
EXPECT_EQ(target_a, Name(expected_merge_name_ab));
DeviceNameUtils::ParsedName target_b = Name(name_b);
DeviceNameUtils::MergeUnsetDevNames(&target_b, Name(name_a));
EXPECT_EQ(target_b, Name(expected_merge_name_ba));
}
TEST(DeviceNameUtilsTest, MergeDevNames) {
MergeDevNamesHelper("", "", "");
MergeDevNamesHelper("/job:foo/replica:1/task:2/cpu:1",
"/job:foo/replica:1/task:2/cpu:1",
"/job:foo/replica:1/task:2/cpu:1");
MergeDevNamesHelper("", "/job:foo", "/job:foo");
MergeDevNamesHelper("", "/replica:2", "/replica:2");
MergeDevNamesHelper("", "/task:7", "/task:7");
MergeDevNamesHelper("", "/device:GPU:1", "/device:GPU:1");
MergeDevNamesHelper("/job:foo", "/task:7", "/job:foo/task:7");
MergeDevNamesHelper("/job:foo", "/device:GPU:1", "/job:foo/device:GPU:1");
MergeDevNamesHelper("/job:foo/replica:0", "/replica:0/task:1",
"/job:foo/replica:0/task:1");
MergeDevNamesHelper("", "/gpu:*", "/gpu:*");
MergeDevNamesHelper("/gpu:*", "/gpu:*", "/gpu:*");
MergeDevNamesHelper("/device:GPU:1", "/gpu:*", "/device:GPU:1");
MergeDevNamesError("/job:foo", "/job:bar", "incompatible jobs");
MergeDevNamesError("/replica:0", "/replica:1", "incompatible replicas");
MergeDevNamesError("/task:0", "/task:1", "incompatible tasks");
MergeDevNamesError("/gpu:*", "/cpu:*", "incompatible types");
MergeDevNamesError("/device:GPU:0", "/device:GPU:1", "incompatible ids");
}
TEST(DeviceNameUtilsTest, MergeDevNamesAllowSoftPlacement) {
MergeDevNamesHelperAllowSoftPlacement("/gpu:*", "/cpu:1", "");
MergeDevNamesHelperAllowSoftPlacement("/cpu:*", "/device:GPU:1", "");
MergeDevNamesHelperAllowSoftPlacement("/device:GPU:1", "/device:GPU:2",
"/device:GPU:*");
}
TEST(DeviceNameUtilsTest, MergeOverrideDevNames) {
MergeOverrideHelper("", "", "");
MergeOverrideHelper("/job:foo/replica:1/task:2/cpu:1",
"/job:foo/replica:1/task:2/cpu:1",
"/job:foo/replica:1/task:2/cpu:1");
MergeOverrideHelper("", "/job:foo", "/job:foo");
MergeOverrideHelper("", "/replica:2", "/replica:2");
MergeOverrideHelper("", "/task:7", "/task:7");
MergeOverrideHelper("", "/device:GPU:1", "/device:GPU:1");
MergeOverrideHelper("/job:foo", "/task:7", "/job:foo/task:7");
MergeOverrideHelper("/job:foo", "/device:GPU:1", "/job:foo/device:GPU:1");
MergeOverrideHelper("/job:foo/replica:0", "/replica:0/task:1",
"/job:foo/replica:0/task:1");
MergeOverrideHelper("", "/gpu:*", "/gpu:*");
MergeOverrideHelper("/gpu:*", "/gpu:*", "/gpu:*");
MergeOverrideHelper("/device:GPU:1", "/gpu:*", "/device:GPU:1");
MergeOverrideHelper("/gpu:0", "/cpu:1", "/cpu:1");
MergeOverrideHelper("/gpu:*", "/cpu:1", "/cpu:1");
MergeOverrideHelper("/cpu:*", "/device:GPU:1", "/gpu:1");
MergeOverrideHelper("/device:GPU:1", "/device:GPU:2", "/device:GPU:2");
MergeOverrideHelper("/job:foo/CPU:*", "/device:GPU:1", "/job:foo/GPU:1");
MergeOverrideHelper("/cpu:*", "/job:foo/device:GPU:1", "/job:foo/GPU:1");
MergeOverrideHelper("/task:0/cpu:*", "/device:GPU:1", "/task:0/GPU:1");
MergeOverrideHelper("/cpu:*", "/task:0/device:GPU:1", "/task:0/GPU:1");
}
TEST(DeviceNameUtilsTest, MergeUnsetDevNames) {
MergeUnsetDevNamesHelper("", "", "", "");
MergeUnsetDevNamesHelper(
"/job:foo/replica:1/task:2/cpu:1", "/job:foo/replica:1/task:2/cpu:1",
"/job:foo/replica:1/task:2/cpu:1", "/job:foo/replica:1/task:2/cpu:1");
MergeUnsetDevNamesHelper("", "/job:foo", "/job:foo", "/job:foo");
MergeUnsetDevNamesHelper("", "/replica:2", "/replica:2", "/replica:2");
MergeUnsetDevNamesHelper("", "/task:7", "/task:7", "/task:7");
MergeUnsetDevNamesHelper("", "/device:GPU:1", "/device:GPU:1",
"/device:GPU:1");
MergeUnsetDevNamesHelper("/job:foo", "/task:7", "/job:foo/task:7",
"/job:foo/task:7");
MergeUnsetDevNamesHelper("/job:foo", "/device:GPU:1", "/job:foo/device:GPU:1",
"/job:foo/device:GPU:1");
MergeUnsetDevNamesHelper("/job:foo/replica:0", "/replica:0/task:1",
"/job:foo/replica:0/task:1",
"/job:foo/replica:0/task:1");
MergeUnsetDevNamesHelper("", "/gpu:*", "/gpu:*", "/gpu:*");
MergeUnsetDevNamesHelper("/gpu:*", "/gpu:*", "/gpu:*", "/gpu:*");
MergeUnsetDevNamesHelper("/device:GPU:1", "/gpu:*", "/device:GPU:1",
"/device:GPU:1");
MergeUnsetDevNamesHelper("/job:foo", "/job:bar", "/job:foo", "/job:bar");
MergeUnsetDevNamesHelper("/replica:0", "/replica:1", "/replica:0",
"/replica:1");
MergeUnsetDevNamesHelper("/task:0", "/task:1", "/task:0", "/task:1");
MergeUnsetDevNamesHelper("/gpu:*", "/cpu:*", "/gpu:*", "/cpu:*");
MergeUnsetDevNamesHelper("/device:GPU:0", "/device:GPU:1", "/device:GPU:0",
"/device:GPU:1");
MergeUnsetDevNamesHelper("/job:foo/device:GPU", "/job:bar",
"/job:foo/device:GPU", "/job:bar/device:GPU");
}
TEST(DeviceNameUtilsTest, GetNamesForDeviceMappings) {
DeviceNameUtils::ParsedName p =
Name("/job:foo/replica:10/task:0/device:GPU:1");
EXPECT_EQ(absl::StrJoin(DeviceNameUtils::GetNamesForDeviceMappings(p), ","),
"/job:foo/replica:10/task:0/device:GPU:1,"
"/job:foo/replica:10/task:0/gpu:1");
p.has_task = false;
EXPECT_EQ(absl::StrJoin(DeviceNameUtils::GetNamesForDeviceMappings(p), ","),
"");
}
TEST(DeviceNameUtilsTest, CanonicalizeDeviceName) {
string canonical_name;
{
string basename = "/job:foo/replica:10/task:0/device:CPU:0";
TF_EXPECT_OK(DeviceNameUtils::CanonicalizeDeviceName(
"/job:foo/replica:10/task:0/device:CPU:1", basename, &canonical_name));
EXPECT_EQ("/job:foo/replica:10/task:0/device:CPU:1", canonical_name);
TF_EXPECT_OK(DeviceNameUtils::CanonicalizeDeviceName(
"/job:foo/task:0/replica:10/device:CPU:1", basename, &canonical_name));
EXPECT_EQ("/job:foo/replica:10/task:0/device:CPU:1", canonical_name);
TF_EXPECT_OK(DeviceNameUtils::CanonicalizeDeviceName(
"/job:foo/task:0/replica:10/cpu:1", basename, &canonical_name));
EXPECT_EQ("/job:foo/replica:10/task:0/device:CPU:1", canonical_name);
TF_EXPECT_OK(DeviceNameUtils::CanonicalizeDeviceName("CPU:0", basename,
&canonical_name));
EXPECT_EQ("/job:foo/replica:10/task:0/device:CPU:0", canonical_name);
absl::Status s = DeviceNameUtils::CanonicalizeDeviceName(
"/job:foo/task:0/replica/cpu:1", basename, &canonical_name);
EXPECT_EQ(s.code(), error::INVALID_ARGUMENT);
EXPECT_EQ("", canonical_name);
}
{
string fullname = "/device:CPU:0";
absl::Status s = DeviceNameUtils::CanonicalizeDeviceName(
fullname, "/device:CPU:0", &canonical_name);
EXPECT_EQ(s.code(), error::INVALID_ARGUMENT);
EXPECT_EQ("", canonical_name);
s = DeviceNameUtils::CanonicalizeDeviceName(
fullname, "/job:foo/task:0/replica/cpu:1", &canonical_name);
EXPECT_EQ(s.code(), error::INVALID_ARGUMENT);
EXPECT_EQ("", canonical_name);
}
}
TEST(DeviceNameUtilsTest, CompareFullNames) {
EXPECT_FALSE(DeviceNameUtils::CompareFullNames(
"/job:foo/replica:0/task:0/cpu:0", "/job:foo/replica:0/task:0/cpu:0"));
EXPECT_FALSE(DeviceNameUtils::CompareFullNames(
"/job:foo/replica:0/task:0/device:CPU:1",
"/job:foo/replica:0/task:0/device:CPU:0"));
EXPECT_FALSE(DeviceNameUtils::CompareFullNames(
"/job:foo/replica:0/task:1/device:CPU:0",
"/job:foo/replica:0/task:0/device:CPU:0"));
EXPECT_FALSE(DeviceNameUtils::CompareFullNames(
"/job:foo/replica:1/task:0/device:CPU:0",
"/job:foo/replica:0/task:0/device:CPU:0"));
EXPECT_FALSE(DeviceNameUtils::CompareFullNames(
"/job:goo/replica:0/task:0/device:CPU:0",
"/job:foo/replica:0/task:0/device:CPU:0"));
EXPECT_FALSE(DeviceNameUtils::CompareFullNames(
"/job:foo/replica:0/task:0/device:GPU:0",
"/job:foo/replica:0/task:0/device:CPU:0"));
EXPECT_TRUE(DeviceNameUtils::CompareFullNames(
"/job:foo/replica:0/task:0/device:CPU:0",
"/job:foo/replica:0/task:0/device:CPU:1"));
EXPECT_TRUE(DeviceNameUtils::CompareFullNames(
"/job:foo/replica:0/task:0/device:CPU:0",
"/job:foo/replica:0/task:1/device:CPU:0"));
EXPECT_TRUE(DeviceNameUtils::CompareFullNames(
"/job:foo/replica:0/task:0/device:CPU:0",
"/job:foo/replica:1/task:0/device:CPU:0"));
EXPECT_TRUE(DeviceNameUtils::CompareFullNames(
"/job:foo/replica:0/task:0/device:CPU:0",
"/job:goo/replica:0/task:0/device:CPU:0"));
EXPECT_TRUE(DeviceNameUtils::CompareFullNames(
"/job:foo/replica:0/task:0/device:CPU:0",
"/job:foo/replica:0/task:0/device:GPU:0"));
EXPECT_FALSE(
DeviceNameUtils::CompareFullNames("/device:CPU:1", "unparseablename"));
EXPECT_TRUE(
DeviceNameUtils::CompareFullNames("unparseablename", "/device:CPU:1"));
EXPECT_TRUE(DeviceNameUtils::CompareFullNames(
"/replica:0/task:0/device:CPU:1",
"/job:foo/replica:0/task:0/device:CPU:0"));
EXPECT_FALSE(DeviceNameUtils::CompareFullNames(
"/job:foo/replica:0/task:0/device:CPU:0",
"/replica:0/task:0/device:CPU:0"));
EXPECT_TRUE(DeviceNameUtils::CompareFullNames(
"/replica:0/task:0/device:CPU:0", "/replica:0/task:0/device:CPU:1"));
EXPECT_TRUE(DeviceNameUtils::CompareFullNames("/task:0/device:CPU:0",
"/task:0/device:CPU:1"));
EXPECT_TRUE(
DeviceNameUtils::CompareFullNames("/device:CPU:0", "/device:CPU:1"));
}
static void BM_ParseFullName(::testing::benchmark::State& state) {
DeviceNameUtils::ParsedName p;
for (auto s : state) {
DeviceNameUtils::ParseFullName("/job:worker/replica:3/task:0/cpu:0", &p);
}
}
BENCHMARK(BM_ParseFullName);
} | 2,250 |
#ifndef XLA_MLIR_TOOLS_MLIR_REPLAY_PUBLIC_EXECUTION_TRACE_UTILS_H_
#define XLA_MLIR_TOOLS_MLIR_REPLAY_PUBLIC_EXECUTION_TRACE_UTILS_H_
#include "absl/status/statusor.h"
#include "mlir/IR/Attributes.h"
#include "mlir/IR/Operation.h"
#include "mlir/IR/Region.h"
#include "mlir/Support/LLVM.h"
#include "xla/literal.h"
#include "xla/mlir/tools/mlir_interpreter/framework/interpreter.h"
#include "xla/mlir/tools/mlir_interpreter/framework/interpreter_value.h"
#include "xla/mlir/tools/mlir_replay/public/execution_trace.pb.h"
#include "xla/xla_data.pb.h"
namespace mlir {
namespace interpreter {
class ExecutionTraceListener : public InterpreterListener {
public:
explicit ExecutionTraceListener(ExecutionTrace* trace) : trace_(trace) {}
void BeforeOp(ArrayRef<InterpreterValue> args, Operation* op) override;
void AfterOp(ArrayRef<InterpreterValue> results) override;
void EnterRegion(ArrayRef<InterpreterValue> bbargs, Region& region) override;
void LeaveRegion(ArrayRef<InterpreterValue> yielded) override;
private:
ExecutionTrace* trace_;
SmallVector<RegionTrace*> regions_;
};
llvm::SmallVector<mlir::Attribute> ValueToAttribute(
const InterpreterValue& value, mlir::Type type);
absl::StatusOr<InterpreterValue> LiteralToValue(
const xla::LiteralProto& literal);
absl::StatusOr<InterpreterValue> LiteralToValue(
const xla::LiteralProto& literal, mlir::Type type);
absl::StatusOr<InterpreterValue> LiteralToValue(const xla::Literal& literal);
TracedValue ValueToTracedValue(const InterpreterValue& value);
absl::StatusOr<InterpreterValue> TracedValueToValue(
const TracedValue& traced_value);
llvm::SmallVector<const InstructionTrace*> FindOpExecutionsInTrace(
const ExecutionTrace& trace, mlir::Operation* op);
}
}
#endif
#include "xla/mlir/tools/mlir_replay/public/execution_trace_utils.h"
#include <cassert>
#include <complex>
#include <cstdint>
#include <functional>
#include <iterator>
#include <memory>
#include <type_traits>
#include <utility>
#include <variant>
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/Support/Casting.h"
#include "mlir/Dialect/Func/IR/FuncOps.h"
#include "mlir/IR/Attributes.h"
#include "mlir/IR/BuiltinAttributes.h"
#include "mlir/IR/BuiltinTypeInterfaces.h"
#include "mlir/IR/BuiltinTypes.h"
#include "mlir/IR/Region.h"
#include "mlir/IR/Types.h"
#include "mlir/Support/LLVM.h"
#include "xla/literal.h"
#include "xla/mlir/tools/mlir_interpreter/framework/interpreter_value.h"
#include "xla/mlir/tools/mlir_interpreter/framework/tensor_or_memref.h"
#include "xla/mlir/tools/mlir_replay/public/execution_trace.pb.h"
#include "tsl/platform/statusor.h"
namespace mlir {
namespace interpreter {
namespace {
struct TraceInterpreterValueVisitor {
TracedValue out;
void Add(float v) { out.add_floats(v); }
void Add(double v) { out.add_doubles(v); }
void Add(std::complex<float> v) {
out.add_floats(v.real());
out.add_floats(v.imag());
}
void Add(std::complex<double> v) {
out.add_doubles(v.real());
out.add_doubles(v.imag());
}
void Add(int64_t v) { out.add_ints(v); }
void Add(int32_t v) { out.add_ints(v); }
void Add(int16_t v) { out.add_ints(v); }
void Add(int8_t v) { out.add_ints(v); }
void Add(uint64_t v) { out.add_uints(v); }
void Add(uint32_t v) { out.add_uints(v); }
void Add(uint16_t v) { out.add_uints(v); }
void Add(uint8_t v) { out.add_uints(v); }
void Add(bool v) { out.add_ints(static_cast<int64_t>(v)); }
template <typename T>
void operator()(T v) {
SetElementType<T>();
out.set_is_scalar(true);
Add(v);
}
void operator()(const Tuple& t) {
out.set_element_type(TracedValue::TUPLE);
for (const auto& v : t.values) {
*out.add_tuple_elements() = ValueToTracedValue(*v);
}
}
template <typename T>
void operator()(const TensorOrMemref<T>& v) {
for (int64_t size : v.view.sizes) {
out.add_shape(size);
}
SetElementType<T>();
for (const auto& index : v.view.Indices()) {
Add(v.at(index));
}
}
template <typename T>
void SetElementType() {
out.set_element_type(GetElementType(T{}));
if constexpr (std::is_same_v<T, bool>) {
out.set_bit_width(1);
} else {
out.set_bit_width(sizeof(T) * 8);
}
}
template <typename T>
static TracedValue::ElementType GetElementType(const T&) {
if constexpr (std::is_floating_point_v<T>) {
return TracedValue::FLOAT;
} else if constexpr (std::is_integral_v<T>) {
if constexpr (std::is_unsigned_v<T>) {
return TracedValue::UNSIGNED;
} else {
return TracedValue::INTEGRAL;
}
} else {
T{"invalid type"} + 0;
return TracedValue::UNKNOWN;
}
}
template <typename T>
static TracedValue::ElementType GetElementType(const std::complex<T>&) {
return TracedValue::COMPLEX;
}
static TracedValue::ElementType GetElementType(const Tuple&) {
return TracedValue::UNKNOWN;
}
};
}
void ExecutionTraceListener::BeforeOp(ArrayRef<InterpreterValue> args,
Operation* op) {
auto* inst = regions_.back()->add_instructions();
inst->set_name(op->getName().getStringRef().str());
for (const auto& arg : args) {
*inst->add_args() = ValueToTracedValue(arg);
}
}
void ExecutionTraceListener::AfterOp(ArrayRef<InterpreterValue> results) {
auto* traced_results =
regions_.back()->mutable_instructions()->rbegin()->mutable_results();
for (const auto& result : results) {
*traced_results->Add() = ValueToTracedValue(result);
}
}
void ExecutionTraceListener::EnterRegion(ArrayRef<InterpreterValue> bbargs,
Region& region) {
if (regions_.empty()) {
regions_.push_back(trace_->mutable_trace());
} else {
regions_.push_back(
regions_.back()->mutable_instructions()->rbegin()->add_regions());
}
auto& traced_region = *regions_.back();
traced_region.set_region_number(region.getRegionNumber());
for (const auto& bbarg : bbargs) {
*traced_region.add_bbargs() = ValueToTracedValue(bbarg);
}
}
void ExecutionTraceListener::LeaveRegion(ArrayRef<InterpreterValue> yielded) {
for (const auto& result : yielded) {
*regions_.back()->add_results() = ValueToTracedValue(result);
}
regions_.pop_back();
}
llvm::SmallVector<mlir::Attribute> ValueToAttribute(
const InterpreterValue& value, mlir::Type type) {
if (std::holds_alternative<Tuple>(value.storage)) {
auto types = type.cast<TupleType>().getTypes();
const auto& t = std::get<Tuple>(value.storage);
llvm::SmallVector<mlir::Attribute> attrs;
for (const auto& [v, ty] : llvm::zip(t.values, types)) {
auto attr = ValueToAttribute(*v, ty);
assert(attr.size() == 1 && "nested tuples not supported");
attrs.push_back(attr.front());
}
return attrs;
}
if (!value.IsTensor()) {
return {cast<DenseElementsAttr>(
ValueToAttribute(value.AsUnitTensor(),
mlir::RankedTensorType::get({}, type))
.front())
.getValues<mlir::Attribute>()[0]};
}
if (!type.isa<ShapedType>()) {
return {};
}
auto shaped_ty = type.cast<ShapedType>();
return {DispatchScalarType(shaped_ty, [&](auto dummy) -> mlir::Attribute {
using T = decltype(dummy);
auto& t = std::get<TensorOrMemref<T>>(value.storage);
SmallVector<T> vals;
for (const auto& index : t.view.Indices()) {
vals.push_back(t.at(index));
}
auto attr_ty =
shaped_ty.cloneWith(t.view.sizes, shaped_ty.getElementType());
if constexpr (std::is_same_v<T, bool>) {
return mlir::DenseElementsAttr::get(attr_ty, vals);
} else {
return mlir::DenseElementsAttr::get<T>(attr_ty, vals);
}
})};
}
namespace {
template <typename T>
TensorOrMemref<T> ArrayLiteralToTensor(const xla::Literal& literal) {
SmallVector<int64_t> layout;
if (literal.shape().has_layout()) {
llvm::copy(literal.shape().layout().minor_to_major(),
std::back_inserter(layout));
}
SmallVector<int64_t> shape{literal.shape().dimensions().begin(),
literal.shape().dimensions().end()};
auto result = TensorOrMemref<T>::Empty(shape, layout);
assert(literal.size_bytes() == result.buffer->GetByteSize() &&
"expected buffer sizes to match");
memcpy(result.buffer->at(0, 0), literal.untyped_data(),
result.buffer->GetByteSize());
return result;
}
}
absl::StatusOr<InterpreterValue> LiteralToValue(const xla::Literal& literal) {
if (literal.shape().IsTuple()) {
auto elements = literal.Clone().DecomposeTuple();
Tuple result;
for (auto& element : elements) {
TF_ASSIGN_OR_RETURN(auto converted, LiteralToValue(element));
result.values.push_back(
std::make_shared<InterpreterValue>(std::move(converted)));
}
return {{result}};
}
if (literal.shape().IsToken()) {
return absl::UnimplementedError("token arguments are not implemented");
}
if (literal.shape().IsArray()) {
switch (literal.shape().element_type()) {
case xla::PRED:
return {{ArrayLiteralToTensor<bool>(literal)}};
case xla::S8:
return {{ArrayLiteralToTensor<int8_t>(literal)}};
case xla::S16:
return {{ArrayLiteralToTensor<int16_t>(literal)}};
case xla::S32:
return {{ArrayLiteralToTensor<int32_t>(literal)}};
case xla::S64:
return {{ArrayLiteralToTensor<int64_t>(literal)}};
case xla::U8:
return {{ArrayLiteralToTensor<uint8_t>(literal)}};
case xla::U16:
return {{ArrayLiteralToTensor<uint16_t>(literal)}};
case xla::U32:
return {{ArrayLiteralToTensor<uint32_t>(literal)}};
case xla::U64:
return {{ArrayLiteralToTensor<uint64_t>(literal)}};
case xla::F16:
return absl::UnimplementedError("F16 not implemented");
case xla::F32:
return {{ArrayLiteralToTensor<float>(literal)}};
case xla::BF16:
return absl::UnimplementedError("BF16 not implemented");
case xla::F64:
return {{ArrayLiteralToTensor<double>(literal)}};
case xla::F8E5M2:
return absl::UnimplementedError("F8E5M2 not implemented");
case xla::F8E4M3FN:
return absl::UnimplementedError("F8E4M3FN not implemented");
case xla::F8E4M3B11FNUZ:
return absl::UnimplementedError("F8E4M3B11FNUZ not implemented");
case xla::F8E5M2FNUZ:
return absl::UnimplementedError("F8E5M2FNUZ not implemented");
case xla::F8E4M3FNUZ:
return absl::UnimplementedError("F8E4M3FNUZ not implemented");
case xla::C64:
return {{ArrayLiteralToTensor<std::complex<float>>(literal)}};
case xla::C128:
return {{ArrayLiteralToTensor<std::complex<double>>(literal)}};
default:
break;
}
}
return absl::InvalidArgumentError("unexpected literal type");
}
absl::StatusOr<InterpreterValue> LiteralToValue(
const xla::LiteralProto& literal) {
TF_ASSIGN_OR_RETURN(auto deserialized,
xla::Literal::CreateFromProto(literal));
return LiteralToValue(deserialized);
}
absl::StatusOr<InterpreterValue> LiteralToValue(
const xla::LiteralProto& literal, mlir::Type type) {
TF_ASSIGN_OR_RETURN(auto result, LiteralToValue(literal));
return {DispatchScalarType(type, [&](auto dummy) -> InterpreterValue {
TensorOrMemref<decltype(dummy)> cast;
cast.view = result.View();
cast.buffer = result.GetBuffer();
return {cast};
})};
}
TracedValue ValueToTracedValue(const InterpreterValue& value) {
TraceInterpreterValueVisitor visitor;
std::visit(visitor, value.storage);
return visitor.out;
}
absl::StatusOr<InterpreterValue> TracedValueToValue(
const TracedValue& traced_value) {
auto extract = [&](auto dummy, auto& elements) -> InterpreterValue {
using T = decltype(dummy);
if (traced_value.is_scalar()) {
return {static_cast<T>(elements[0])};
}
auto result =
TensorOrMemref<T>::Empty(llvm::to_vector(traced_value.shape()));
for (auto [index, element] : llvm::zip(result.view.Indices(), elements)) {
result.at(index) = element;
}
return {result};
};
auto extract_complex = [&](auto& elements) -> InterpreterValue {
using T = std::complex<std::decay_t<decltype(elements[0])>>;
if (traced_value.is_scalar()) {
return {T{elements[0], elements[1]}};
}
auto result =
TensorOrMemref<T>::Empty(llvm::to_vector(traced_value.shape()));
int64_t i = 0;
for (auto it = result.view.Indices().begin(),
end = result.view.Indices().end();
it != end; ++it, i += 2) {
result.at(*it) = {elements[i], elements[i + 1]};
}
return {result};
};
switch (traced_value.element_type()) {
case TracedValue::UNKNOWN:
break;
case TracedValue::FLOAT:
if (traced_value.bit_width() == 32) {
return extract(float{}, traced_value.floats());
}
return extract(double{}, traced_value.doubles());
case TracedValue::UNSIGNED:
switch (traced_value.bit_width()) {
case 1:
return extract(bool{}, traced_value.ints());
case 8:
return extract(uint8_t{}, traced_value.uints());
case 16:
return extract(uint16_t{}, traced_value.uints());
case 32:
return extract(uint32_t{}, traced_value.uints());
case 64:
return extract(uint64_t{}, traced_value.uints());
}
break;
case TracedValue::INTEGRAL:
switch (traced_value.bit_width()) {
case 8:
return extract(int8_t{}, traced_value.ints());
case 16:
return extract(int16_t{}, traced_value.ints());
case 32:
return extract(int32_t{}, traced_value.ints());
case 64:
return extract(int64_t{}, traced_value.ints());
}
break;
case TracedValue::COMPLEX:
switch (traced_value.bit_width()) {
case 64:
return extract_complex(traced_value.floats());
case 128:
return extract_complex(traced_value.doubles());
}
break;
case TracedValue::TUPLE:
Tuple result;
for (const auto& elem : traced_value.tuple_elements()) {
TF_ASSIGN_OR_RETURN(auto converted, TracedValueToValue(elem));
result.values.push_back(
std::make_shared<InterpreterValue>(std::move(converted)));
}
return {{std::move(result)}};
}
return absl::InvalidArgumentError("unexpected type: " +
traced_value.DebugString());
}
llvm::SmallVector<const InstructionTrace*> FindOpExecutionsInTrace(
const ExecutionTrace& trace, mlir::Operation* op) {
llvm::SmallVector<int64_t> region_indices;
llvm::SmallVector<int64_t> op_indices;
std::function<void(mlir::Operation*)> get_op_path;
get_op_path = [&](mlir::Operation* op) {
auto* parent = op->getParentOp();
if (!llvm::isa<func::FuncOp>(parent)) {
get_op_path(parent);
region_indices.push_back(op->getParentRegion()->getRegionNumber());
}
int64_t index = 0;
while ((op = op->getPrevNode()) != nullptr) ++index;
op_indices.push_back(index);
};
get_op_path(op);
llvm::SmallVector<const InstructionTrace*> result;
std::function<void(const RegionTrace& trace, int index)> step;
step = [&](const RegionTrace& trace, int index) {
auto& instruction_trace = trace.instructions(op_indices[index]);
if (region_indices.size() > index) {
for (const auto& region : instruction_trace.regions()) {
if (region.region_number() == region_indices[index]) {
step(region, index + 1);
}
}
} else {
result.push_back(&instruction_trace);
}
};
step(trace.trace(), 0);
return result;
}
}
} | #include "xla/mlir/tools/mlir_replay/public/execution_trace_utils.h"
#include <cmath>
#include <complex>
#include <cstdint>
#include <memory>
#include <utility>
#include <vector>
#include <gtest/gtest.h>
#include "llvm/ADT/STLExtras.h"
#include "mlir/Support/LLVM.h"
#include "xla/literal.h"
#include "xla/literal_util.h"
#include "xla/mlir/tools/mlir_interpreter/framework/interpreter_value.h"
#include "xla/mlir/tools/mlir_interpreter/framework/tensor_or_memref.h"
#include "tsl/platform/statusor.h"
namespace mlir {
namespace interpreter {
namespace {
class TracedValueRoundTripTest
: public ::testing::TestWithParam<InterpreterValue> {};
TEST_P(TracedValueRoundTripTest, Run) {
auto traced_value = ValueToTracedValue(GetParam());
TF_ASSERT_OK_AND_ASSIGN(auto value, TracedValueToValue(traced_value));
EXPECT_EQ(GetParam(), value) << GetParam().ToString();
}
template <typename T>
InterpreterValue MakeTensor(ArrayRef<int64_t> shape, ArrayRef<T> values) {
auto result = TensorOrMemref<T>::Empty(shape);
for (auto [indices, value] : llvm::zip(result.view.Indices(), values)) {
result.at(indices) = value;
}
return {result};
}
template <typename T>
std::shared_ptr<T> WrapShared(T value) {
return std::make_shared<T>(std::move(value));
}
INSTANTIATE_TEST_SUITE_P(
RoundTrip, TracedValueRoundTripTest,
::testing::ValuesIn(std::vector<InterpreterValue>{
{uint8_t{42}},
{uint16_t{43}},
{uint32_t{44}},
{uint64_t{45}},
{int8_t{-47}},
{int16_t{-48}},
{int32_t{-49}},
{int64_t{-50}},
{float{42.0}},
{double{42.0}},
{std::complex<float>{1.0, 2.0}},
{std::complex<double>{3.0, 4.0}},
{true},
{false},
{MakeTensor<int16_t>({1, 2}, {42, 43})},
{MakeTensor<double>({2, 2}, {1.0, -INFINITY, INFINITY, NAN})},
{MakeTensor<std::complex<double>>({}, {{1.0, 2.0}})},
{Tuple{SmallVector<std::shared_ptr<InterpreterValue>>{
WrapShared(InterpreterValue{42}),
WrapShared(InterpreterValue{43.0}),
}}}}));
class FromLiteralTest
: public ::testing::TestWithParam<
std::pair<std::shared_ptr<xla::Literal>, InterpreterValue>> {};
TEST_P(FromLiteralTest, Run) {
TF_ASSERT_OK_AND_ASSIGN(auto value, LiteralToValue(*GetParam().first));
EXPECT_EQ(value, GetParam().second)
<< value.ToString() << " vs " << GetParam().second.ToString();
}
std::vector<std::pair<std::shared_ptr<xla::Literal>, InterpreterValue>>
MakeInputs() {
using ::xla::LiteralUtil;
return {
{WrapShared(LiteralUtil::CreateR2<uint8_t>({{41, 42}})),
MakeTensor<uint8_t>({1, 2}, {41, 42})},
{WrapShared(LiteralUtil::CreateR0<uint16_t>(43)),
MakeTensor<uint16_t>({}, {43})},
{WrapShared(LiteralUtil::CreateR0<uint32_t>(44)),
MakeTensor<uint32_t>({}, {44})},
{WrapShared(LiteralUtil::CreateR0<uint64_t>(45)),
MakeTensor<uint64_t>({}, {45})},
{WrapShared(LiteralUtil::CreateR0<int8_t>(46)),
MakeTensor<int8_t>({}, {46})},
{WrapShared(LiteralUtil::CreateR0<int16_t>(47)),
MakeTensor<int16_t>({}, {47})},
{WrapShared(LiteralUtil::CreateR0<int32_t>(48)),
MakeTensor<int32_t>({}, {48})},
{WrapShared(LiteralUtil::CreateR0<int64_t>(49)),
MakeTensor<int64_t>({}, {49})},
{WrapShared(LiteralUtil::CreateR0<float>(50.0)),
MakeTensor<float>({}, {50.0})},
{WrapShared(LiteralUtil::CreateR0<double>(51.0)),
MakeTensor<double>({}, {51.0})},
{WrapShared(LiteralUtil::CreateR0<std::complex<float>>({52.0, 53.0})),
MakeTensor<std::complex<float>>({}, {{52.0, 53.0}})},
{WrapShared(LiteralUtil::CreateR0<std::complex<double>>({54.0, 55.0})),
MakeTensor<std::complex<double>>({}, {{54.0, 55.0}})},
{WrapShared(LiteralUtil::CreateR1<bool>({true, false})),
MakeTensor<bool>({2}, {true, false})},
{WrapShared(
LiteralUtil::MakeTupleOwned(LiteralUtil::CreateR0<bool>(true),
LiteralUtil::CreateR0<int8_t>(56))),
InterpreterValue{Tuple{SmallVector<std::shared_ptr<InterpreterValue>>{
std::make_shared<InterpreterValue>(MakeTensor<bool>({}, {true})),
std::make_shared<InterpreterValue>(
MakeTensor<int8_t>({}, {56}))}}}}};
}
INSTANTIATE_TEST_SUITE_P(Test, FromLiteralTest,
::testing::ValuesIn(MakeInputs()));
}
}
} | 2,251 |
#ifndef XLA_MLIR_TOOLS_MLIR_INTERPRETER_FRAMEWORK_REGISTRATION_H_
#define XLA_MLIR_TOOLS_MLIR_INTERPRETER_FRAMEWORK_REGISTRATION_H_
#include <cstddef>
#include <cstdint>
#include <functional>
#include <optional>
#include <type_traits>
#include <utility>
#include "absl/strings/str_cat.h"
#include "llvm/ADT/Sequence.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/TypeName.h"
#include "mlir/IR/Operation.h"
#include "mlir/Support/LLVM.h"
#include "xla/mlir/tools/mlir_interpreter/framework/interpreter.h"
#include "xla/mlir/tools/mlir_interpreter/framework/interpreter_value.h"
#include "xla/mlir/tools/mlir_interpreter/framework/interpreter_value_util.h"
#define MLIR_INTERPRETER_CONCAT_IMPL(x, y) x##y
#define MLIR_INTERPRETER_CONCAT(x, y) MLIR_INTERPRETER_CONCAT_IMPL(x, y)
#define REGISTER_MLIR_INTERPRETER_OP(args...) \
static int MLIR_INTERPRETER_CONCAT(init_, __COUNTER__) = []() { \
::mlir::interpreter::detail::RegisterInterpreterOp(args); \
return 1; \
}();
namespace mlir {
namespace interpreter {
namespace detail {
using InterpreterFunction = std::function<SmallVector<InterpreterValue>(
MutableArrayRef<InterpreterValue>, mlir::Operation*, InterpreterState&)>;
InterpreterFunction GetFunction(llvm::StringRef name);
void RegisterInterpreterOp(llvm::StringRef name,
InterpreterValue (*fn)(const InterpreterValue&));
void RegisterInterpreterOp(llvm::StringRef name,
InterpreterValue (*fn)(const InterpreterValue&,
const InterpreterValue&));
template <typename T>
struct is_optional : std::false_type {};
template <typename T>
struct is_optional<std::optional<T>> : std::true_type {};
template <typename ArgT>
auto TypedInterpreterOpConvertArg(MutableArrayRef<InterpreterValue> args,
InterpreterState& state) {
constexpr bool optional = is_optional<ArgT>::value;
constexpr bool single = std::is_same_v<ArgT, InterpreterValue> ||
is_valid_interpreter_value_v<ArgT>;
if constexpr (optional) {
if (args.empty()) {
return ArgT{};
}
}
if constexpr (single || optional) {
if (args.size() != 1) {
state.AddFailure("Expected a single argument for the operand");
return ArgT{};
}
}
auto fail = [&]() {
state.AddFailure(absl::StrCat("Unable to convert argument (variant index ",
args[0].storage.index(), ") to ",
llvm::getTypeName<ArgT>().str()));
return ArgT{};
};
if constexpr (single) {
if (auto arg = InterpreterValueDynCast<ArgT>(args[0])) {
return ArgT{*arg};
}
return fail();
} else if constexpr (optional) {
using T = std::decay_t<decltype(*std::declval<ArgT>())>;
if (auto arg = InterpreterValueDynCast<T>(args[0])) {
return arg;
}
return fail();
} else {
using E = std::decay_t<decltype(*std::declval<ArgT>().begin())>;
if constexpr (std::is_same_v<E, InterpreterValue>) {
return ArgT{args};
} else {
return UnpackInterpreterValues<E>(args);
}
}
}
template <typename RetT>
SmallVector<InterpreterValue> TypedInterpreterOpConvertRet(RetT ret) {
if constexpr (std::is_same_v<RetT, InterpreterValue>) {
return {ret};
} else if constexpr (is_valid_interpreter_value_v<RetT>) {
return {InterpreterValue{ret}};
} else if constexpr (std::is_same_v<RetT, SmallVector<InterpreterValue>>) {
return ret;
} else {
using E = std::decay_t<decltype(*std::declval<RetT>().begin())>;
return PackInterpreterValues(ArrayRef<E>(ret));
}
}
template <typename Op, typename Ret, typename... T, size_t... Indices>
void RegisterTypedInterpreterOpImpl(Ret (*fn)(InterpreterState&, Op, T... args),
std::index_sequence<Indices...>) {
RegisterInterpreterOp(
Op::getOperationName(),
[fn](MutableArrayRef<InterpreterValue> args, mlir::Operation* op,
InterpreterState& state) -> SmallVector<InterpreterValue> {
auto cast = llvm::dyn_cast<Op>(op);
if (!cast) {
state.AddFailure(absl::StrCat(
"failed to cast op '", op->getName().getStringRef().str(),
"' to expected type (", llvm::getTypeName<Op>().str(), ")"));
return {};
}
int64_t used_args = 0;
for (auto i : llvm::seq(0ul, sizeof...(T))) {
used_args += cast.getODSOperandIndexAndLength(i).second;
}
if (args.size() != used_args) {
state.AddFailure("Op handler did not use all arguments");
return {};
}
auto extract_arg = [&](auto index, auto* dummy) {
auto [pos, length] = cast.getODSOperandIndexAndLength(index);
using ArgT = std::decay_t<decltype(*dummy)>;
return TypedInterpreterOpConvertArg<ArgT>(args.slice(pos, length),
state);
};
if constexpr (std::is_same_v<Ret, void>) {
fn(state, cast, extract_arg(Indices, (std::decay_t<T>*){nullptr})...);
return {};
} else {
Ret ret = fn(state, cast,
extract_arg(Indices, (std::decay_t<T>*){nullptr})...);
return TypedInterpreterOpConvertRet(ret);
}
});
}
template <typename Op, typename Ret, typename... T>
void RegisterInterpreterOp(Ret (*fn)(InterpreterState&, Op, T...)) {
RegisterTypedInterpreterOpImpl(fn, std::index_sequence_for<T...>{});
}
void RegisterInterpreterOp(
llvm::StringRef name,
InterpreterValue (*fn)(MutableArrayRef<InterpreterValue>));
void RegisterInterpreterOp(llvm::StringRef name,
void (*fn)(MutableArrayRef<InterpreterValue>));
void RegisterInterpreterOp(
llvm::StringRef name,
std::function<llvm::SmallVector<InterpreterValue>(
MutableArrayRef<InterpreterValue>, mlir::Operation*, InterpreterState&)>
fn);
void RegisterInterpreterOp(llvm::StringRef name, llvm::StringRef original);
}
}
}
#endif
#include "xla/mlir/tools/mlir_interpreter/framework/registration.h"
#include <cassert>
#include <functional>
#include <utility>
#include "mlir/IR/Operation.h"
#include "mlir/Support/LLVM.h"
#include "xla/mlir/tools/mlir_interpreter/framework/interpreter.h"
#include "xla/mlir/tools/mlir_interpreter/framework/interpreter_value.h"
namespace mlir {
namespace interpreter {
namespace detail {
namespace {
DenseMap<llvm::StringRef, llvm::StringRef>& GetOpAliases() {
static DenseMap<llvm::StringRef, llvm::StringRef>* aliases = nullptr;
if (!aliases) {
aliases = new DenseMap<llvm::StringRef, llvm::StringRef>();
}
return *aliases;
}
DenseMap<llvm::StringRef, InterpreterFunction>& GetFunctions() {
static DenseMap<llvm::StringRef, InterpreterFunction>* functions = nullptr;
if (!functions) {
functions = new DenseMap<llvm::StringRef, InterpreterFunction>();
}
return *functions;
}
}
InterpreterFunction GetFunction(llvm::StringRef name) {
const auto& fns = GetFunctions();
auto fn = fns.find(name);
if (fn != fns.end()) {
return fn->second;
}
const auto& aliases = GetOpAliases();
auto alias = aliases.find(name);
if (alias != aliases.end()) {
return fns.find(alias->second)->second;
}
return nullptr;
}
void RegisterInterpreterOp(llvm::StringRef name,
InterpreterValue (*fn)(const InterpreterValue&)) {
RegisterInterpreterOp(
name,
[fn](MutableArrayRef<InterpreterValue> operands, mlir::Operation*,
InterpreterState&) -> SmallVector<InterpreterValue> {
assert(operands.size() == 1 && "unexpected number of operands");
return {fn(operands[0])};
});
}
void RegisterInterpreterOp(llvm::StringRef name,
InterpreterValue (*fn)(const InterpreterValue&,
const InterpreterValue&)) {
RegisterInterpreterOp(
name,
[fn](MutableArrayRef<InterpreterValue> operands, mlir::Operation*,
InterpreterState&) -> SmallVector<InterpreterValue> {
assert(operands.size() == 2 && "unexpected number of operands");
return {fn(operands[0], operands[1])};
});
}
void RegisterInterpreterOp(
llvm::StringRef name,
InterpreterValue (*fn)(MutableArrayRef<InterpreterValue>)) {
RegisterInterpreterOp(
name,
[fn](MutableArrayRef<InterpreterValue> operands, mlir::Operation*,
InterpreterState&) -> SmallVector<InterpreterValue> {
return {fn(operands)};
});
}
void RegisterInterpreterOp(llvm::StringRef name,
void (*fn)(MutableArrayRef<InterpreterValue>)) {
RegisterInterpreterOp(
name,
[fn](MutableArrayRef<InterpreterValue> operands, mlir::Operation*,
InterpreterState&) -> SmallVector<InterpreterValue> {
fn(operands);
return {};
});
}
void RegisterInterpreterOp(
llvm::StringRef name,
std::function<llvm::SmallVector<InterpreterValue>(
MutableArrayRef<InterpreterValue>, mlir::Operation*, InterpreterState&)>
fn) {
GetFunctions()[name] = std::move(fn);
}
void RegisterInterpreterOp(llvm::StringRef name, llvm::StringRef original) {
GetOpAliases()[name] = original;
}
}
}
} | #include "tensorflow/core/framework/registration/registration.h"
#include <gmock/gmock.h>
#include "tensorflow/core/platform/test.h"
namespace tensorflow {
namespace {
using ::testing::Eq;
#define STORE_NEXT_ID_IMPL(id, name) constexpr int name = id
#define STORE_NEXT_ID(name) TF_NEW_ID_FOR_INIT(STORE_NEXT_ID_IMPL, name)
STORE_NEXT_ID(kBaseId);
STORE_NEXT_ID(kNextId1);
STORE_NEXT_ID(kNextId2);
TEST(NewIdForInitTest, SequentialIds) {
static_assert(kBaseId >= 0, "kBaseId < 0");
static_assert(kNextId1 == kBaseId + 1, "kNextId1 != kBaseId+1");
static_assert(kNextId2 == kBaseId + 2, "kNextId2 != kBaseId+2");
}
int observed_unconditional_init;
InitOnStartupMarker const kUnconditionalInitMarker =
InitOnStartupMarker{} << []() {
observed_unconditional_init++;
return InitOnStartupMarker{};
};
TEST(InitOnStartupTest, Unconditional) {
EXPECT_THAT(observed_unconditional_init, Eq(1));
}
template <bool Enable>
int observed_conditional_init;
template <bool Enable>
InitOnStartupMarker const kConditionalInitMarker =
TF_INIT_ON_STARTUP_IF(Enable) << []() {
(observed_conditional_init<Enable>)++;
return InitOnStartupMarker{};
};
template InitOnStartupMarker const kConditionalInitMarker<true>;
template InitOnStartupMarker const kConditionalInitMarker<false>;
TEST(InitOnStartupTest, DISABLED_Conditional) {
EXPECT_THAT(observed_conditional_init<true>, Eq(1));
EXPECT_THAT(observed_conditional_init<false>, Eq(0));
}
template <bool Enable>
int observed_conditional_init_immediate;
template <bool Enable>
InitOnStartupMarker const kConditionalInitImmediateMarker =
TF_INIT_ON_STARTUP_IF(Enable) << ([]() {
(observed_conditional_init_immediate<Enable>)++;
return InitOnStartupMarker{};
})();
template InitOnStartupMarker const kConditionalInitImmediateMarker<true>;
template InitOnStartupMarker const kConditionalInitImmediateMarker<false>;
TEST(InitOnStartupTest, DISABLED_ConditionalImmediate) {
EXPECT_THAT(observed_conditional_init_immediate<true>, Eq(1));
EXPECT_THAT(observed_conditional_init_immediate<false>, Eq(0));
}
}
} | 2,252 |
#ifndef XLA_MLIR_TOOLS_MLIR_INTERPRETER_FRAMEWORK_INTERPRETER_VALUE_H_
#define XLA_MLIR_TOOLS_MLIR_INTERPRETER_FRAMEWORK_INTERPRETER_VALUE_H_
#include <cassert>
#include <complex>
#include <cstdint>
#include <functional>
#include <memory>
#include <optional>
#include <string>
#include <variant>
#include "llvm/ADT/ArrayRef.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
#include "mlir/IR/BuiltinTypes.h"
#include "mlir/IR/TypeUtilities.h"
#include "mlir/IR/Types.h"
#include "mlir/Support/LLVM.h"
#include "xla/mlir/tools/mlir_interpreter/framework/tensor_or_memref.h"
namespace mlir {
namespace interpreter {
struct InterpreterValue;
struct Tuple {
bool operator==(const Tuple& other) const;
SmallVector<std::shared_ptr<InterpreterValue>> values;
};
struct InterpreterValue {
void Print(llvm::raw_ostream& os) const;
std::string ToString() const;
InterpreterValue ExtractElement(llvm::ArrayRef<int64_t> indices) const;
void InsertElement(llvm::ArrayRef<int64_t> indices,
const InterpreterValue& value);
void Fill(
const std::function<InterpreterValue(llvm::ArrayRef<int64_t> indices)>&
f);
InterpreterValue AsUnitTensor(bool is_vector = false) const;
int64_t AsInt() const;
uint64_t AsUInt() const;
double AsDouble() const;
int64_t GetByteSizeOfElement() const;
InterpreterValue Clone(ArrayRef<int64_t> layout = {}) const;
InterpreterValue CoerceLayout(llvm::ArrayRef<int64_t> layout) const;
InterpreterValue TypedAlike(llvm::ArrayRef<int64_t> shape) const;
static InterpreterValue MakeTensor(mlir::Type element_type,
SmallVector<int64_t> shape);
BufferView& View();
const BufferView& View() const;
std::shared_ptr<Buffer> GetBuffer() const;
bool IsTensor() const;
bool operator==(const InterpreterValue& other) const {
if (storage.index() != other.storage.index()) return false;
if (IsTensor() || std::holds_alternative<Tuple>(storage))
return storage == other.storage;
return AsUnitTensor() == other.AsUnitTensor();
}
std::variant<
Tuple, bool, float, double, uint8_t, int8_t, uint16_t, int16_t, uint32_t,
int32_t, uint64_t, int64_t, std::complex<float>, std::complex<double>,
TensorOrMemref<bool>, TensorOrMemref<float>, TensorOrMemref<double>,
TensorOrMemref<uint8_t>, TensorOrMemref<int8_t>, TensorOrMemref<uint16_t>,
TensorOrMemref<int16_t>, TensorOrMemref<uint32_t>,
TensorOrMemref<int32_t>, TensorOrMemref<uint64_t>,
TensorOrMemref<int64_t>, TensorOrMemref<std::complex<float>>,
TensorOrMemref<std::complex<double>>>
storage;
};
template <typename T>
constexpr static bool is_valid_interpreter_value_v =
std::is_constructible_v<decltype(InterpreterValue::storage), T>;
template <typename T>
std::optional<T> InterpreterValueDynCast(InterpreterValue v) {
if constexpr (std::is_same_v<T, InterpreterValue>) {
return v;
}
if constexpr (is_valid_interpreter_value_v<T>) {
if (std::holds_alternative<T>(v.storage)) {
return std::get<T>(v.storage);
}
}
if (v.IsTensor() && !is_tensor_or_memref_v<T>) {
if (v.View().GetNumElements() != 1) {
return std::nullopt;
}
return InterpreterValueDynCast<T>(v.ExtractElement({}));
}
return std::visit(
[](auto v) -> std::optional<T> {
if constexpr (std::is_convertible_v<decltype(v), T>) {
return v;
} else {
return std::nullopt;
}
},
v.storage);
}
template <typename T>
T InterpreterValueCast(InterpreterValue v) {
auto ret = InterpreterValueDynCast<T>(v);
assert(ret && "cast failed");
return *std::move(ret);
}
template <class Fn>
auto DispatchScalarType(mlir::Type ty, Fn&& functor) {
ty = getElementTypeOrSelf(ty);
if (ty.isF32()) {
return functor(float{});
}
if (ty.isF64()) {
return functor(double{});
}
if (ty.isUnsignedInteger(64)) {
return functor(uint64_t{});
}
if (ty.isInteger(64) || ty.isIndex()) {
return functor(int64_t{});
}
if (ty.isUnsignedInteger(32)) {
return functor(uint32_t{});
}
if (ty.isInteger(32)) {
return functor(int32_t{});
}
if (ty.isUnsignedInteger(16)) {
return functor(uint16_t{});
}
if (ty.isInteger(16)) {
return functor(int16_t{});
}
if (ty.isUnsignedInteger(8)) {
return functor(uint8_t{});
}
if (ty.isInteger(8)) {
return functor(int8_t{});
}
if (ty.isInteger(1)) {
return functor(bool{});
}
if (auto complex = mlir::dyn_cast<ComplexType>(ty)) {
if (complex.getElementType().isF32()) {
return functor(std::complex<float>{});
}
if (complex.getElementType().isF64()) {
return functor(std::complex<double>{});
}
}
llvm::errs() << "DispatchScalarType unimplemented for " << ty << "\n";
llvm_unreachable("unimplemented");
}
}
}
#endif
#include "xla/mlir/tools/mlir_interpreter/framework/interpreter_value.h"
#include <cassert>
#include <complex>
#include <cstdint>
#include <functional>
#include <iterator>
#include <memory>
#include <string>
#include <string_view>
#include <type_traits>
#include <variant>
#include "llvm/ADT/STLExtras.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
#include "mlir/IR/BuiltinTypes.h"
#include "mlir/IR/Types.h"
#include "mlir/Support/LLVM.h"
#include "xla/mlir/tools/mlir_interpreter/framework/tensor_or_memref.h"
namespace mlir {
namespace interpreter {
namespace {
struct TypeStr {
static std::string_view Get(bool) { return "i1"; }
static std::string_view Get(int64_t) { return "i64"; }
static std::string_view Get(int32_t) { return "i32"; }
static std::string_view Get(int16_t) { return "i16"; }
static std::string_view Get(int8_t) { return "i8"; }
static std::string_view Get(uint64_t) { return "ui64"; }
static std::string_view Get(uint32_t) { return "ui32"; }
static std::string_view Get(uint16_t) { return "ui16"; }
static std::string_view Get(uint8_t) { return "ui8"; }
static std::string_view Get(float) { return "f32"; }
static std::string_view Get(double) { return "f64"; }
static std::string_view Get(std::complex<float>) { return "complex<f32>"; }
static std::string_view Get(std::complex<double>) { return "complex<f64>"; }
};
struct InterpreterValuePrinter {
llvm::raw_ostream& os;
template <typename T>
void operator()(const TensorOrMemref<T>& t) {
if (!t.buffer) {
os << "Memref: null";
return;
}
if (t.view.is_vector) {
os << "vector<";
} else {
os << "TensorOrMemref<";
}
ArrayRef<int64_t> sizes = t.view.sizes;
for (int64_t size : sizes.drop_back(t.view.num_vector_dims.value_or(0))) {
os << size << "x";
}
if (t.view.num_vector_dims) {
os << "vector<";
for (int64_t size : sizes.take_back(*t.view.num_vector_dims)) {
os << size << "x";
}
os << TypeStr::Get(T{}) << ">>: ";
} else {
os << TypeStr::Get(T{}) << ">: ";
}
SmallVector<int64_t> indices(t.view.Rank() +
t.view.num_vector_dims.value_or(0));
std::function<void(int64_t)> print;
print = [&](int64_t dim) {
if (dim == indices.size()) {
PrintScalar(t.at(indices));
} else {
os << "[";
for (int64_t i = 0; i < t.view.sizes[dim]; ++i) {
if (i > 0) os << ", ";
indices[dim] = i;
print(dim + 1);
}
os << "]";
}
};
if (t.buffer->Deallocated()) {
os << "<<deallocated>>";
} else {
print(0);
}
}
void operator()(const Tuple& t) {
os << "(";
bool first = true;
for (const auto& v : t.values) {
if (!first) os << ", ";
first = false;
v->Print(os);
}
os << ")";
}
template <typename T>
void operator()(const T& t) {
os << TypeStr::Get(t) << ": ";
PrintScalar(t);
}
template <typename T>
void PrintScalar(const T& v) {
os << v;
}
template <typename T>
void PrintScalar(const std::complex<T>& v) {
os << v.real() << (v.imag() >= 0 ? "+" : "") << v.imag() << "i";
}
void PrintScalar(bool v) { os << (v ? "true" : "false"); }
void PrintScalar(int8_t v) { os << (int)v; }
void PrintScalar(uint8_t v) { os << (int)v; }
};
}
void InterpreterValue::Print(llvm::raw_ostream& os) const {
std::visit(InterpreterValuePrinter{os}, storage);
}
std::string InterpreterValue::ToString() const {
std::string buf;
llvm::raw_string_ostream os(buf);
Print(os);
return buf;
}
InterpreterValue InterpreterValue::ExtractElement(
llvm::ArrayRef<int64_t> indices) const {
return std::visit(
[&](auto& it) -> InterpreterValue {
using T = std::decay_t<decltype(it)>;
if constexpr (is_tensor_or_memref_v<T>) {
if (it.view.num_vector_dims) {
return {it.VectorAt(indices)};
} else {
return {it.at(indices)};
}
} else if constexpr (std::is_same_v<T, Tuple>) {
llvm_unreachable("extracting from tuples is unsupported");
} else {
return {it};
}
},
storage);
}
void InterpreterValue::InsertElement(llvm::ArrayRef<int64_t> indices,
const InterpreterValue& value) {
std::visit(
[&](auto& it) {
using T = std::decay_t<decltype(it)>;
if constexpr (is_tensor_or_memref_v<T>) {
if (it.view.num_vector_dims) {
auto subview = it.VectorAt(indices);
const auto& values = std::get<T>(value.storage);
assert(values.view.sizes == subview.view.sizes &&
"mismatched sizes");
for (const auto& index : subview.view.Indices()) {
subview.at(index) = values.at(index);
}
} else {
it.at(indices) = std::get<typename T::element_type>(value.storage);
}
} else if constexpr (std::is_same_v<T, Tuple>) {
llvm_unreachable("inserting into tuples is unsupported");
} else {
it = std::get<T>(value.storage);
}
},
storage);
}
void InterpreterValue::Fill(
const std::function<InterpreterValue(llvm::ArrayRef<int64_t> indices)>& f) {
std::visit(
[&](auto& it) {
using T = std::decay_t<decltype(it)>;
if constexpr (is_tensor_or_memref_v<T>) {
for (const auto& indices : it.view.Indices()) {
if (it.view.num_vector_dims) {
auto subview = it.VectorAt(indices);
auto value = std::get<T>(f(indices).storage);
for (const auto& index : subview.view.Indices()) {
subview.at(index) = value.at(index);
}
} else {
it.at(indices) =
std::get<typename T::element_type>(f(indices).storage);
}
}
} else if constexpr (std::is_same_v<T, Tuple>) {
llvm_unreachable("Filling tuples is unsupported");
} else {
it = std::get<T>(f({}).storage);
}
},
storage);
}
InterpreterValue InterpreterValue::Clone(ArrayRef<int64_t> layout) const {
return std::visit(
[&](const auto& it) -> InterpreterValue {
using T = std::decay_t<decltype(it)>;
if constexpr (is_tensor_or_memref_v<T>) {
return {it.Clone(layout)};
} else if constexpr (std::is_same_v<T, Tuple>) {
llvm_unreachable("cloning tuples is unsupported");
} else {
return {it};
}
},
storage);
}
InterpreterValue InterpreterValue::CoerceLayout(
ArrayRef<int64_t> layout) const {
const auto& view = this->View();
if (view.strides == BufferView::GetStridesForLayout(view.sizes, layout)) {
return *this;
}
return Clone(layout);
}
InterpreterValue InterpreterValue::TypedAlike(
llvm::ArrayRef<int64_t> shape) const {
return std::visit(
[&](const auto& it) -> InterpreterValue {
using T = std::decay_t<decltype(it)>;
if constexpr (is_tensor_or_memref_v<T>) {
return {T::Empty(shape)};
} else if constexpr (std::is_same_v<T, Tuple>) {
llvm_unreachable("TypedAlike for tuples is unsupported");
} else {
return {TensorOrMemref<T>::Empty(shape)};
}
},
storage);
}
InterpreterValue InterpreterValue::MakeTensor(mlir::Type element_type,
SmallVector<int64_t> shape) {
auto vector_ty = llvm::dyn_cast<VectorType>(element_type);
if (vector_ty) {
llvm::copy(vector_ty.getShape(), std::back_inserter(shape));
}
return DispatchScalarType(element_type, [&](auto dummy) -> InterpreterValue {
auto tensor = TensorOrMemref<decltype(dummy)>::Empty(shape);
if (vector_ty) {
tensor.view.num_vector_dims = vector_ty.getRank();
}
return {tensor};
});
}
BufferView& InterpreterValue::View() {
return std::visit(
[](auto& it) -> BufferView& {
if constexpr (is_tensor_or_memref_v<decltype(it)>) {
return it.view;
}
llvm_unreachable("view is only supported for tensors");
},
storage);
}
const BufferView& InterpreterValue::View() const {
return std::visit(
[](const auto& it) -> const BufferView& {
if constexpr (is_tensor_or_memref_v<decltype(it)>) {
return it.view;
}
llvm_unreachable("view is only supported for tensors");
},
storage);
}
bool InterpreterValue::IsTensor() const {
return std::visit(
[](const auto& it) { return is_tensor_or_memref_v<decltype(it)>; },
storage);
}
InterpreterValue InterpreterValue::AsUnitTensor(bool is_vector) const {
auto result = TypedAlike({});
result.InsertElement({}, *this);
result.View().is_vector = is_vector;
return result;
}
bool Tuple::operator==(const Tuple& other) const {
if (other.values.size() != values.size()) return false;
for (const auto& [lhs, rhs] : llvm::zip(values, other.values)) {
if (!(*lhs == *rhs)) return false;
}
return true;
}
std::shared_ptr<Buffer> InterpreterValue::GetBuffer() const {
return std::visit(
[](const auto& it) -> std::shared_ptr<interpreter::Buffer> {
if constexpr (is_tensor_or_memref_v<decltype(it)>) {
return it.buffer;
} else {
llvm_unreachable("buffer() is only supported for tensors");
}
},
storage);
}
int64_t InterpreterValue::AsInt() const {
auto visit = [](auto value) -> int64_t {
if constexpr (std::is_integral_v<decltype(value)>) {
return static_cast<int64_t>(value);
} else {
llvm_unreachable("only integral types can be converted to ints");
}
};
return std::visit(visit, storage);
}
uint64_t InterpreterValue::AsUInt() const {
auto visit = [](auto value) -> uint64_t {
if constexpr (std::is_integral_v<decltype(value)>) {
if constexpr (std::is_signed_v<decltype(value)>) {
return static_cast<uint64_t>(
static_cast<std::make_unsigned_t<decltype(value)>>(value));
} else {
return static_cast<uint64_t>(value);
}
} else {
llvm_unreachable("only integral types can be converted to ints");
}
};
return std::visit(visit, storage);
}
double InterpreterValue::AsDouble() const {
auto visit = [](auto value) -> int64_t {
if constexpr (std::is_floating_point_v<decltype(value)>) {
return static_cast<double>(value);
} else {
llvm_unreachable("only float types can be converted to ints");
}
};
return std::visit(visit, storage);
}
int64_t InterpreterValue::GetByteSizeOfElement() const {
return std::visit(
[](const auto& it) -> int64_t {
using T = std::decay_t<decltype(it)>;
if constexpr (is_tensor_or_memref_v<T>) {
return sizeof(typename T::element_type);
} else {
llvm_unreachable("scalars have no element sizes");
}
},
storage);
}
}
} | #include "xla/mlir/tools/mlir_interpreter/framework/interpreter_value.h"
#include <complex>
#include <cstdint>
#include <optional>
#include <variant>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "llvm/ADT/ArrayRef.h"
#include "xla/mlir/tools/mlir_interpreter/framework/tensor_or_memref.h"
namespace mlir {
namespace interpreter {
namespace {
using ::testing::ElementsAre;
using ::testing::IsEmpty;
TEST(InterpreterValueTest, FillUnitTensor) {
auto t = TensorOrMemref<int64_t>::Empty({});
t.at({}) = 42;
InterpreterValue v{t};
v.Fill([](llvm::ArrayRef<int64_t>) { return InterpreterValue{int64_t{43}}; });
ASSERT_EQ(t.at({}), 43);
}
TEST(InterpreterValueTest, Fill1DTensor) {
auto t = TensorOrMemref<int64_t>::Empty({3});
InterpreterValue v{t};
v.Fill([](llvm::ArrayRef<int64_t> indices) {
return InterpreterValue{indices[0]};
});
ASSERT_EQ(t.at(0), 0);
ASSERT_EQ(t.at(1), 1);
ASSERT_EQ(t.at(2), 2);
}
TEST(InterpreterValueTest, FillTensorOfVector) {
auto t = TensorOrMemref<int64_t>::Empty({4, 2});
t.view.num_vector_dims = 1;
InterpreterValue v{t};
v.Fill([](llvm::ArrayRef<int64_t> indices) -> InterpreterValue {
EXPECT_EQ(indices.size(), 1);
auto r = TensorOrMemref<int64_t>::Empty({2});
r.view.is_vector = true;
r.at(0) = indices[0];
r.at(1) = indices[0] * 10;
return {r};
});
ASSERT_EQ(
v.ToString(),
"TensorOrMemref<4xvector<2xi64>>: [[0, 0], [1, 10], [2, 20], [3, 30]]");
}
TEST(InterpreterValueTest, FillZeroSizedTensor) {
auto t = TensorOrMemref<int64_t>::Empty({0, 1});
InterpreterValue v{t};
bool was_called = false;
v.Fill([&](llvm::ArrayRef<int64_t> indices) {
was_called = true;
return InterpreterValue{indices[0]};
});
EXPECT_FALSE(was_called);
}
TEST(InterpreterValueTest, TypedAlike) {
InterpreterValue v{TensorOrMemref<int32_t>::Empty({})};
auto TypedAlike = v.TypedAlike({1, 2, 3});
ASSERT_TRUE(
std::holds_alternative<TensorOrMemref<int32_t>>(TypedAlike.storage));
ASSERT_THAT(TypedAlike.View().sizes, ElementsAre(1, 2, 3));
}
TEST(InterpreterValueTest, AsUnitTensor) {
InterpreterValue v{42};
InterpreterValue wrapped = v.AsUnitTensor();
ASSERT_THAT(wrapped.View().sizes, IsEmpty());
ASSERT_EQ(std::get<TensorOrMemref<int32_t>>(wrapped.storage).at({}), 42);
}
TEST(InterpreterValueTest, IsTensor) {
ASSERT_FALSE(InterpreterValue{42}.IsTensor());
ASSERT_TRUE(InterpreterValue{TensorOrMemref<int32_t>::Empty({})}.IsTensor());
}
TEST(InterpreterValueTest, AsInt) {
ASSERT_EQ(InterpreterValue{int64_t{42}}.AsInt(), 42);
ASSERT_EQ(InterpreterValue{int32_t{42}}.AsInt(), 42);
ASSERT_EQ(InterpreterValue{int16_t{42}}.AsInt(), 42);
ASSERT_EQ(InterpreterValue{int8_t{42}}.AsInt(), 42);
ASSERT_EQ(InterpreterValue{int8_t{-1}}.AsInt(), -1);
}
TEST(InterpreterValueTest, AsUInt) {
ASSERT_EQ(InterpreterValue{int16_t{-1}}.AsUInt(), 65535);
ASSERT_EQ(InterpreterValue{int8_t{-1}}.AsUInt(), 255);
}
TEST(InterpreterValueTest, CloneTensor) {
auto tensor = TensorOrMemref<int64_t>::Empty({3});
tensor.at(0) = 1;
tensor.at(1) = 2;
tensor.at(2) = 3;
InterpreterValue wrapped{tensor};
auto clone = wrapped.Clone();
tensor.at(0) = 4;
auto& cloned_tensor = std::get<TensorOrMemref<int64_t>>(clone.storage);
ASSERT_EQ(cloned_tensor.at(0), 1);
ASSERT_EQ(cloned_tensor.at(1), 2);
ASSERT_EQ(cloned_tensor.at(2), 3);
}
TEST(InterpreterValueTest, CloneWithLayouts) {
auto tensor = TensorOrMemref<int64_t>::Empty({3, 5}, {0, 1});
tensor.at({2, 4}) = 42;
InterpreterValue wrapped{tensor};
auto clone = wrapped.Clone();
ASSERT_EQ(clone.View().strides,
BufferView::GetStridesForLayout({3, 5}, {1, 0}));
ASSERT_EQ(clone.ExtractElement({2, 4}).AsInt(), 42);
}
TEST(InterpreterValueTest, CoerceLayoutNoop) {
auto tensor = TensorOrMemref<int64_t>::Empty({3, 5}, {0, 1});
tensor.at({2, 4}) = 42;
InterpreterValue wrapped{tensor};
auto coerced = wrapped.CoerceLayout({0, 1});
ASSERT_EQ(tensor.buffer,
std::get<TensorOrMemref<int64_t>>(coerced.storage).buffer);
}
TEST(InterpreterValueTest, CoerceLayout) {
auto tensor = TensorOrMemref<int64_t>::Empty({3, 5});
tensor.at({2, 4}) = 42;
InterpreterValue wrapped{tensor};
auto clone = wrapped.CoerceLayout({0, 1});
ASSERT_EQ(clone.View().strides,
BufferView::GetStridesForLayout({3, 5}, {0, 1}));
ASSERT_EQ(clone.ExtractElement({2, 4}).AsInt(), 42);
}
TEST(InterpreterValueTest, CoerceLayoutSquare) {
auto tensor = TensorOrMemref<float>::Empty({2, 2});
tensor.at({0, 0}) = 1;
tensor.at({0, 1}) = 2;
tensor.at({1, 0}) = 3;
tensor.at({1, 1}) = 4;
InterpreterValue wrapped{tensor};
auto clone = wrapped.CoerceLayout({0, 1});
auto& cloned_tensor = std::get<TensorOrMemref<float>>(clone.storage);
EXPECT_EQ(
*reinterpret_cast<float*>(cloned_tensor.buffer->at(0, sizeof(float))), 1);
EXPECT_EQ(
*reinterpret_cast<float*>(cloned_tensor.buffer->at(1, sizeof(float))), 3);
EXPECT_EQ(
*reinterpret_cast<float*>(cloned_tensor.buffer->at(2, sizeof(float))), 2);
EXPECT_EQ(
*reinterpret_cast<float*>(cloned_tensor.buffer->at(3, sizeof(float))), 4);
}
TEST(InterpreterValueTest, CloneScalar) {
InterpreterValue value{42};
auto clone = value.Clone();
ASSERT_THAT(std::get<int32_t>(clone.storage), 42);
}
TEST(InterpreterValueTest, ToString) {
InterpreterValue value{TensorOrMemref<int64_t>::Empty({3})};
ASSERT_EQ(value.ToString(), "TensorOrMemref<3xi64>: [0, 0, 0]");
}
TEST(InterpreterValueTest, ToString2d) {
InterpreterValue value{TensorOrMemref<int64_t>::Empty({3, 2})};
ASSERT_EQ(value.ToString(),
"TensorOrMemref<3x2xi64>: [[0, 0], [0, 0], [0, 0]]");
}
TEST(InterpreterValueTest, ToString0d) {
InterpreterValue value{TensorOrMemref<int64_t>::Empty({})};
ASSERT_EQ(value.ToString(), "TensorOrMemref<i64>: 0");
}
TEST(InterpreterValueTest, ToStringComplex) {
InterpreterValue value{std::complex<float>{}};
ASSERT_EQ(value.ToString(), "complex<f32>: 0.000000e+00+0.000000e+00i");
}
TEST(CastTest, UnpackTensor) {
InterpreterValue value{TensorOrMemref<int8_t>::Empty({1, 1})};
value.InsertElement({0, 0}, {int8_t{1}});
ASSERT_EQ(InterpreterValueCast<int64_t>(value), 1);
ASSERT_EQ(InterpreterValueCast<uint8_t>(value), 1);
ASSERT_EQ(InterpreterValueCast<float>(value), 1.0f);
ASSERT_EQ(InterpreterValueCast<double>(value), 1.0);
InterpreterValue non_unit{TensorOrMemref<int8_t>::Empty({2, 2})};
ASSERT_EQ(InterpreterValueDynCast<int64_t>(non_unit), std::nullopt);
}
TEST(CastTest, IdentityCast) {
InterpreterValue value{TensorOrMemref<float>::Empty({1, 1})};
ASSERT_EQ(InterpreterValueCast<InterpreterValue>(value), value);
}
TEST(CastTest, CastToUnsigned) {
InterpreterValue value{int8_t{-1}};
ASSERT_EQ(InterpreterValueCast<uint8_t>(value), 255);
ASSERT_EQ(InterpreterValueCast<uint16_t>(value), 65535);
}
}
}
} | 2,253 |
#ifndef XLA_MLIR_TOOLS_MLIR_INTERPRETER_FRAMEWORK_TENSOR_OR_MEMREF_H_
#define XLA_MLIR_TOOLS_MLIR_INTERPRETER_FRAMEWORK_TENSOR_OR_MEMREF_H_
#include <math.h>
#include <cmath>
#include <complex>
#include <cstddef>
#include <cstdint>
#include <iterator>
#include <memory>
#include <optional>
#include <string>
#include <type_traits>
#include <utility>
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/raw_ostream.h"
#include "mlir/IR/Operation.h"
#include "mlir/Support/LLVM.h"
#include "mlir/Support/LogicalResult.h"
namespace mlir {
namespace interpreter {
template <typename T>
bool IsEqual(T a, T b) {
return a == b;
}
#ifndef MLIR_INTERPRETER_COMPARE_DOUBLES_EXACT
template <>
inline bool IsEqual(double a, double b) {
if (isinf(a) || isinf(b)) {
return a == b;
}
return fabs(a - b) < 1e-14;
}
template <>
inline bool IsEqual(std::complex<double> a, std::complex<double> b) {
return IsEqual(a.real(), b.real()) && IsEqual(a.imag(), b.imag());
}
#endif
struct BufferView {
int64_t offset;
llvm::SmallVector<int64_t> sizes;
llvm::SmallVector<int64_t> strides;
std::optional<int64_t> num_vector_dims = std::nullopt;
bool is_vector = false;
int64_t Rank() const { return sizes.size() - num_vector_dims.value_or(0); }
LogicalResult Slice(int64_t dim_index, int64_t dim_offset);
LogicalResult Slice(int64_t dim_index, int64_t dim_offset, int64_t dim_size,
int64_t dim_stride = 1);
LogicalResult Subview(ArrayRef<int64_t> subview_offsets,
ArrayRef<int64_t> subview_sizes,
ArrayRef<int64_t> subview_strides);
int64_t GetNumElements(bool include_vector_dimsms = false) const;
class LogicalIndexView {
public:
class Iterator {
public:
using iterator_category = std::forward_iterator_tag;
using value_type = llvm::SmallVector<int64_t>;
using difference_type = std::ptrdiff_t;
using pointer = llvm::SmallVector<int64_t>*;
using reference = llvm::SmallVector<int64_t>&;
const llvm::SmallVector<int64_t>& operator*() const {
return view_indices_;
}
const llvm::SmallVector<int64_t>* operator->() const {
return &view_indices_;
}
Iterator& operator++() {
auto index_it = view_indices_.rbegin();
auto size_it = view_->sizes.rbegin();
if (!include_vector_dims_) {
std::advance(size_it, view_->num_vector_dims.value_or(0));
}
for (auto e = view_indices_.rend(); index_it != e;
++index_it, ++size_it) {
++*index_it;
if (*index_it < *size_it) {
return *this;
}
*index_it = 0;
}
view_indices_.clear();
view_indices_.push_back(-1);
return *this;
}
Iterator operator++(int) {
auto tmp = *this;
++(*this);
return tmp;
}
bool operator==(const Iterator& other) const {
return view_indices_ == other.view_indices_;
}
bool operator!=(const Iterator& other) const { return !(*this == other); }
private:
friend class LogicalIndexView;
Iterator(const BufferView* view, llvm::SmallVector<int64_t> indices,
bool include_vector_dims)
: view_(view),
view_indices_(std::move(indices)),
include_vector_dims_(include_vector_dims) {}
const BufferView* view_;
llvm::SmallVector<int64_t> view_indices_;
bool include_vector_dims_;
};
Iterator begin() const {
if (view_->GetNumElements() == 0) return end();
return {
view_,
llvm::SmallVector<int64_t>(
view_->Rank() +
(include_vector_dims_ ? view_->num_vector_dims.value_or(0) : 0)),
include_vector_dims_};
}
Iterator end() const { return {view_, {-1}, false}; }
private:
friend class BufferView;
LogicalIndexView(const BufferView* view, bool include_vector_dims)
: view_(view), include_vector_dims_(include_vector_dims) {}
const BufferView* view_;
bool include_vector_dims_;
};
std::optional<int64_t> GetPhysicalIndex(
llvm::ArrayRef<int64_t> view_indices) const;
LogicalIndexView Indices(bool include_vector_dims = false) const {
return LogicalIndexView{this, include_vector_dims};
}
std::optional<int64_t> GetCollapsedStride(llvm::ArrayRef<int64_t> dims) const;
bool InBounds(llvm::ArrayRef<int64_t> view_indices) const;
static SmallVector<int64_t> GetDefaultStrides(ArrayRef<int64_t> sizes);
static SmallVector<int64_t> GetStridesForLayout(ArrayRef<int64_t> sizes,
ArrayRef<int64_t> layout);
};
class Buffer {
private:
struct Dummy {};
public:
template <typename T>
static std::shared_ptr<Buffer> Allocate(size_t size) {
return std::make_shared<Buffer>(Dummy{}, size, sizeof(T));
}
char* at(std::optional<int64_t> idx, int64_t element_size) {
auto byte_offset = GetByteOffset(idx, element_size);
if (!byte_offset) {
return &storage_.data()[0];
}
return &storage_.data()[*byte_offset];
}
const char* at(std::optional<int64_t> idx, int64_t element_size) const {
auto byte_offset = GetByteOffset(idx, element_size);
if (!byte_offset) {
return &storage_.data()[0];
}
return &storage_.data()[*byte_offset];
}
Buffer(Dummy, size_t num_elements, size_t element_size)
: storage_(num_elements * element_size) {}
int64_t GetByteSize() const { return storage_.size(); }
void Deallocate(mlir::Operation* op) {
if (is_alloca_) {
SetFailure("deallocated stack buffer");
} else if (freed_by_ != nullptr) {
std::string failure;
llvm::raw_string_ostream os(failure);
os << "double-free\n";
os << " Note: allocated by " << *allocated_by_ << "\n";
os << " Note: previously freed by " << *freed_by_ << "\n";
SetFailure(failure);
} else {
freed_by_ = op;
}
}
bool Deallocated() const { return freed_by_ != nullptr; }
mlir::Operation* FreedByOp() const { return freed_by_; }
void SetAllocatedBy(mlir::Operation* allocated_by) {
this->allocated_by_ = allocated_by;
}
void SetFailure(llvm::StringRef failure) const {
this->failure_ = failure.str();
}
llvm::StringRef GetFailure() const { return failure_; }
void SetIsAlloca() { is_alloca_ = true; }
private:
std::optional<size_t> GetByteOffset(std::optional<int64_t> idx,
int64_t element_size) const {
if (!idx) {
SetFailure("out of bounds access");
return std::nullopt;
}
if (freed_by_ != nullptr) {
std::string failure;
llvm::raw_string_ostream os(failure);
os << "use-after-free\n";
os << " Note: allocated by " << *allocated_by_ << "\n";
os << " Note: previously freed by " << *freed_by_ << "\n";
SetFailure(failure);
return std::nullopt;
}
return *idx * element_size;
}
llvm::SmallVector<char> storage_;
mlir::Operation* freed_by_ = nullptr;
mlir::Operation* allocated_by_ = nullptr;
bool is_alloca_ = false;
mutable std::string failure_;
};
template <typename T>
struct TensorOrMemref {
using element_type = T;
static TensorOrMemref<T> Empty(ArrayRef<int64_t> sizes,
ArrayRef<int64_t> layout = {}) {
BufferView dummy{0, SmallVector<int64_t>(sizes), {}};
return EmptyLike(dummy, layout);
}
static TensorOrMemref<T> EmptyLike(const BufferView& view,
ArrayRef<int64_t> layout = {}) {
BufferView new_view = view;
new_view.offset = 0;
new_view.strides = BufferView::GetStridesForLayout(view.sizes, layout);
return {Buffer::Allocate<T>(view.GetNumElements(true)), new_view};
}
TensorOrMemref<T> Clone(ArrayRef<int64_t> layout = {}) const {
auto out = EmptyLike(view, layout);
for (auto [src_index, dst_index] :
llvm::zip(view.Indices(true), out.view.Indices(true))) {
out.at(dst_index) = at(src_index);
}
return out;
}
const T& at(ArrayRef<int64_t> indices) const {
return *reinterpret_cast<const T*>(
buffer->at(view.GetPhysicalIndex(indices), sizeof(T)));
}
T& at(ArrayRef<int64_t> indices) {
return *reinterpret_cast<T*>(
buffer->at(view.GetPhysicalIndex(indices), sizeof(T)));
}
TensorOrMemref VectorAt(ArrayRef<int64_t> indices) const {
auto offset = view.GetPhysicalIndex(indices);
BufferView subview;
subview.strides = {view.strides.begin() + view.Rank(), view.strides.end()};
subview.sizes = {view.sizes.begin() + view.Rank(), view.sizes.end()};
if (offset) {
subview.offset = *offset;
} else {
buffer->SetFailure("out of bounds access");
}
subview.is_vector = true;
subview.num_vector_dims = std::nullopt;
return {buffer, subview};
}
bool operator==(const TensorOrMemref& other) const {
if (buffer->Deallocated() || other.buffer->Deallocated()) return false;
if (other.view.sizes != view.sizes) return false;
if (other.view.num_vector_dims != view.num_vector_dims) return false;
for (const auto& indices : view.Indices(true)) {
if constexpr (std::is_floating_point_v<T>) {
bool thisnan = isnan(at(indices));
bool othernan = isnan(other.at(indices));
if (thisnan || othernan) {
if (thisnan && othernan) continue;
return false;
}
}
if (!IsEqual(at(indices), other.at(indices))) return false;
}
return true;
}
std::shared_ptr<Buffer> buffer;
BufferView view;
};
template <typename T>
struct is_tensor_or_memref : std::false_type {};
template <typename T>
struct is_tensor_or_memref<TensorOrMemref<T>> : std::true_type {};
template <typename T>
inline constexpr bool is_tensor_or_memref_v =
is_tensor_or_memref<std::decay_t<T>>::value;
}
}
#endif
#include "xla/mlir/tools/mlir_interpreter/framework/tensor_or_memref.h"
#include <cstddef>
#include <cstdint>
#include <optional>
#include <utility>
#include "mlir/Dialect/Utils/IndexingUtils.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallVector.h"
#include "mlir/Support/LLVM.h"
#include "mlir/Support/LogicalResult.h"
namespace mlir {
namespace interpreter {
std::optional<int64_t> BufferView::GetPhysicalIndex(
llvm::ArrayRef<int64_t> view_indices) const {
int64_t result = offset;
if (!InBounds(view_indices)) {
return std::nullopt;
}
for (int64_t i = 0; i < view_indices.size(); ++i) {
result += view_indices[i] * strides[i];
}
return result;
}
bool BufferView::InBounds(llvm::ArrayRef<int64_t> view_indices) const {
if (view_indices.size() > sizes.size()) {
return false;
}
for (auto [index, size] : llvm::zip(view_indices, sizes)) {
if (index < 0 || index >= size) {
return false;
}
}
return true;
}
SmallVector<int64_t> BufferView::GetDefaultStrides(ArrayRef<int64_t> sizes) {
SmallVector<int64_t> result(sizes.size());
int64_t stride = 1;
for (int64_t i = result.size() - 1; i >= 0; --i) {
result[i] = stride;
stride *= sizes[i];
}
return result;
}
SmallVector<int64_t> BufferView::GetStridesForLayout(ArrayRef<int64_t> sizes,
ArrayRef<int64_t> layout) {
if (layout.empty()) return GetDefaultStrides(sizes);
auto inverse_layout = invertPermutationVector(layout);
SmallVector<int64_t> result(sizes.size());
int64_t stride = 1;
for (int64_t i = 0; i < layout.size(); ++i) {
result[inverse_layout[i]] = stride;
stride *= sizes[inverse_layout[i]];
}
return result;
}
LogicalResult BufferView::Slice(int64_t dim_index, int64_t dim_offset) {
llvm::SmallVector<int64_t> offsets(Rank(), 0);
offsets[dim_index] = dim_offset;
if (auto new_offset = GetPhysicalIndex(offsets)) {
offset = *new_offset;
} else {
return failure();
}
if (dim_index >= Rank()) --*num_vector_dims;
strides.erase(strides.begin() + dim_index);
sizes.erase(sizes.begin() + dim_index);
return success();
}
LogicalResult BufferView::Slice(int64_t dim_index, int64_t dim_offset,
int64_t dim_size, int64_t dim_stride) {
llvm::SmallVector<int64_t> offsets(Rank(), 0);
offsets[dim_index] = dim_offset;
if (dim_size == 0) {
offset = 0;
} else if (auto new_offset = GetPhysicalIndex(offsets)) {
offset = *new_offset;
} else {
return failure();
}
sizes[dim_index] = dim_size;
strides[dim_index] *= dim_stride;
return success();
}
LogicalResult BufferView::Subview(ArrayRef<int64_t> subview_offsets,
ArrayRef<int64_t> subview_sizes,
ArrayRef<int64_t> subview_strides) {
if (auto new_offset = GetPhysicalIndex(subview_offsets)) {
offset = *new_offset;
} else {
return failure();
}
for (auto [in_size, subview_offset, subview_size, subview_stride] :
llvm::zip(sizes, subview_offsets, subview_sizes, subview_strides)) {
int64_t limit_index = subview_offset + (subview_size - 1) * subview_stride;
if (subview_offset < 0 || subview_offset >= in_size || limit_index < 0 ||
limit_index >= in_size) {
return failure();
}
}
for (auto [in_stride, subview_stride] : llvm::zip(strides, subview_strides)) {
in_stride *= subview_stride;
}
sizes = llvm::to_vector(subview_sizes);
return success();
}
int64_t BufferView::GetNumElements(bool include_vector_dims) const {
size_t n = 1;
for (auto size : ArrayRef<int64_t>(sizes).drop_back(
include_vector_dims ? 0 : num_vector_dims.value_or(0))) {
n *= size;
}
return n;
}
std::optional<int64_t> BufferView::GetCollapsedStride(
llvm::ArrayRef<int64_t> dims) const {
using StrideAndDim = std::pair<int64_t, int64_t>;
llvm::SmallVector<StrideAndDim> strides_and_dims;
for (auto dim : dims) {
if (sizes[dim] != 1) {
strides_and_dims.emplace_back(strides[dim], dim);
}
}
if (strides_and_dims.empty()) {
return 0;
}
llvm::sort(strides_and_dims);
int64_t next_stride = strides_and_dims.front().first;
for (auto [stride, dim] : strides_and_dims) {
if (stride != next_stride) {
return std::nullopt;
}
next_stride *= sizes[dim];
}
return strides_and_dims.front().first;
}
}
} | #include "xla/mlir/tools/mlir_interpreter/framework/tensor_or_memref.h"
#include <algorithm>
#include <cstdint>
#include <optional>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "absl/strings/str_join.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallBitVector.h"
#include "llvm/ADT/SmallVector.h"
#include "mlir/Support/LLVM.h"
namespace mlir {
namespace interpreter {
namespace {
using ::testing::ElementsAre;
TEST(TensorOrMemrefTest, DefaultStrides) {
EXPECT_THAT(BufferView::GetDefaultStrides({1, 2, 3}), ElementsAre(6, 3, 1));
}
TEST(TensorOrMemrefTest, StridesForLayout) {
EXPECT_THAT(BufferView::GetStridesForLayout({1, 2, 3}, {2, 1, 0}),
ElementsAre(6, 3, 1));
EXPECT_THAT(BufferView::GetStridesForLayout({1, 2, 3}, {0, 1, 2}),
ElementsAre(1, 1, 2));
EXPECT_THAT(BufferView::GetStridesForLayout({3, 3, 3, 3}, {3, 0, 1, 2}),
ElementsAre(27, 1, 3, 9));
}
std::optional<int64_t> GetCollapsedStrideNaive(llvm::ArrayRef<int64_t> dims,
const BufferView& view) {
BufferView f;
for (int64_t dim : dims) {
f.sizes.push_back(view.sizes[dim]);
}
llvm::SmallBitVector v(view.GetNumElements());
for (const auto& indices : f.Indices()) {
SmallVector<int64_t> view_indices(view.Rank());
for (auto [dim, index] : llvm::zip(dims, indices)) {
view_indices[dim] = index;
}
v[*view.GetPhysicalIndex(view_indices)] = true;
}
if (v.count() != f.GetNumElements()) return std::nullopt;
if (f.GetNumElements() <= 1) return 0;
int64_t min = v.find_first();
int64_t expected_stride = (v.find_last() - min) / (f.GetNumElements() - 1);
for (int64_t i = 0; i < f.GetNumElements(); ++i) {
if (!v[i * expected_stride + min]) {
return std::nullopt;
}
}
return expected_stride;
}
TEST(TensorOrMemrefTest, CollapsedStride) {
BufferView view{.sizes = {1, 2, 3, 1, 5},
.strides = BufferView::GetDefaultStrides({1, 2, 3, 1, 5})};
auto check_all = [&]() {
for (int64_t i = 0; i < (1 << view.Rank()); ++i) {
SmallVector<int64_t> dims;
for (int64_t dim = 0; dim < view.Rank(); ++dim) {
if (i & (1 << dim)) dims.push_back(dim);
}
do {
auto v = view.GetCollapsedStride(dims);
auto n = GetCollapsedStrideNaive(dims, view);
EXPECT_EQ(n, v) << "checking " << absl::StrJoin(dims, ", ");
} while (std::next_permutation(dims.begin(), dims.end()));
}
};
check_all();
ASSERT_TRUE(view.Slice(3, 0).succeeded());
check_all();
}
}
}
} | 2,254 |
#ifndef XLA_RUNTIME_BUFFER_USE_H_
#define XLA_RUNTIME_BUFFER_USE_H_
#include "absl/container/flat_hash_set.h"
#include "absl/types/span.h"
#include "xla/service/buffer_assignment.h"
namespace xla {
class BufferUse {
public:
enum class MemoryAccess { kRead, kWrite };
static constexpr MemoryAccess kRead = MemoryAccess::kRead;
static constexpr MemoryAccess kWrite = MemoryAccess::kWrite;
BufferUse(BufferAllocation::Slice slice, MemoryAccess access)
: slice_(slice), access_(access) {}
static BufferUse Read(BufferAllocation::Slice slice) {
return BufferUse(slice, MemoryAccess::kRead);
}
static BufferUse Write(BufferAllocation::Slice slice) {
return BufferUse(slice, MemoryAccess::kWrite);
}
class ReadWriteSet {
public:
ReadWriteSet();
void Add(BufferUse use);
void AddRead(BufferAllocation::Slice slice);
void AddWrite(BufferAllocation::Slice slice);
void AddAll(absl::Span<const BufferUse> uses);
bool HasConflicts(const BufferUse& use) const;
bool HasConflicts(absl::Span<const BufferUse> uses) const;
bool HasConflicts(const ReadWriteSet& other);
private:
absl::flat_hash_set<BufferAllocation::Slice> read_;
absl::flat_hash_set<BufferAllocation::Slice> write_;
};
bool operator==(const BufferUse& other) const {
return slice_ == other.slice_ && access_ == other.access_;
}
bool operator!=(const BufferUse& other) const { return !(*this == other); }
const BufferAllocation::Slice& slice() const { return slice_; }
MemoryAccess access() const { return access_; }
template <typename H>
friend H AbslHashValue(H h, const BufferUse& use) {
return H::combine(std::move(h), use.slice_, use.access_);
}
private:
BufferAllocation::Slice slice_;
MemoryAccess access_;
};
}
#endif
#include "xla/runtime/buffer_use.h"
#include "absl/algorithm/container.h"
#include "absl/container/flat_hash_set.h"
#include "absl/types/span.h"
#include "xla/service/buffer_assignment.h"
namespace xla {
BufferUse::ReadWriteSet::ReadWriteSet() = default;
void BufferUse::ReadWriteSet::Add(BufferUse use) {
switch (use.access()) {
case BufferUse::kRead:
AddRead(use.slice());
break;
case BufferUse::kWrite:
AddWrite(use.slice());
break;
}
}
void BufferUse::ReadWriteSet::AddRead(BufferAllocation::Slice slice) {
read_.insert(slice);
}
void BufferUse::ReadWriteSet::AddWrite(BufferAllocation::Slice slice) {
write_.insert(slice);
}
void BufferUse::ReadWriteSet::AddAll(absl::Span<const BufferUse> uses) {
for (const auto& use : uses) Add(use);
}
bool BufferUse::ReadWriteSet::HasConflicts(const BufferUse& use) const {
auto overlaps = [](const absl::flat_hash_set<BufferAllocation::Slice>& set,
const BufferUse& use) {
return set.contains(use.slice()) ||
absl::c_any_of(set, [&](const BufferAllocation::Slice& slice) {
return slice.OverlapsWith(use.slice());
});
};
return use.access() == MemoryAccess::kWrite
? overlaps(write_, use) || overlaps(read_, use)
: overlaps(write_, use);
}
bool BufferUse::ReadWriteSet::HasConflicts(
absl::Span<const BufferUse> uses) const {
return absl::c_any_of(
uses, [&](const BufferUse& use) { return HasConflicts(use); });
}
bool BufferUse::ReadWriteSet::HasConflicts(const ReadWriteSet& other) {
return absl::c_any_of(other.read_,
[&](const BufferAllocation::Slice& slice) {
return HasConflicts({slice, BufferUse::kRead});
}) ||
absl::c_any_of(other.write_,
[&](const BufferAllocation::Slice& slice) {
return HasConflicts({slice, BufferUse::kWrite});
});
}
} | #include "xla/runtime/buffer_use.h"
#include "xla/service/buffer_assignment.h"
#include "tsl/platform/test.h"
namespace xla {
namespace {
TEST(BufferUseTest, Equality) {
BufferAllocation alloc(0, 1024, 0);
BufferAllocation::Slice slice0(&alloc, 0, 10);
BufferUse use0(slice0, BufferUse::MemoryAccess::kRead);
BufferUse use1(slice0, BufferUse::MemoryAccess::kWrite);
BufferUse use2(slice0, BufferUse::MemoryAccess::kRead);
EXPECT_NE(use0, use1);
EXPECT_EQ(use0, use2);
}
TEST(BufferUseTest, ReadWriteSet) {
BufferUse::ReadWriteSet rwset;
BufferAllocation alloc(0, 1024, 0);
BufferAllocation::Slice slice0(&alloc, 0, 10);
BufferAllocation::Slice slice1(&alloc, 5, 10);
BufferAllocation::Slice slice2(&alloc, 10, 10);
rwset.Add(BufferUse::Read(slice0));
EXPECT_FALSE(rwset.HasConflicts({BufferUse::Read(slice1)}));
EXPECT_TRUE(rwset.HasConflicts({BufferUse::Write(slice1)}));
EXPECT_FALSE(rwset.HasConflicts({BufferUse::Write(slice2)}));
rwset.Add(BufferUse::Read(slice1));
EXPECT_TRUE(rwset.HasConflicts({BufferUse::Write(slice2)}));
}
}
} | 2,255 |
#ifndef TENSORFLOW_TSL_PLATFORM_SCANNER_H_
#define TENSORFLOW_TSL_PLATFORM_SCANNER_H_
#include <string>
#include "tsl/platform/macros.h"
#include "tsl/platform/str_util.h"
#include "tsl/platform/stringpiece.h"
namespace tsl {
namespace strings {
class Scanner {
public:
enum CharClass {
ALL,
DIGIT,
LETTER,
LETTER_DIGIT,
LETTER_DIGIT_DASH_UNDERSCORE,
LETTER_DIGIT_DASH_DOT_SLASH,
LETTER_DIGIT_DASH_DOT_SLASH_UNDERSCORE,
LETTER_DIGIT_DOT,
LETTER_DIGIT_DOT_PLUS_MINUS,
LETTER_DIGIT_DOT_UNDERSCORE,
LETTER_DIGIT_UNDERSCORE,
LOWERLETTER,
LOWERLETTER_DIGIT,
LOWERLETTER_DIGIT_UNDERSCORE,
NON_ZERO_DIGIT,
SPACE,
UPPERLETTER,
RANGLE,
};
explicit Scanner(StringPiece source) : cur_(source) { RestartCapture(); }
Scanner& One(CharClass clz) {
if (cur_.empty() || !Matches(clz, cur_[0])) {
return Error();
}
cur_.remove_prefix(1);
return *this;
}
Scanner& ZeroOrOneLiteral(StringPiece s) {
str_util::ConsumePrefix(&cur_, s);
return *this;
}
Scanner& OneLiteral(StringPiece s) {
if (!str_util::ConsumePrefix(&cur_, s)) {
error_ = true;
}
return *this;
}
Scanner& Any(CharClass clz) {
while (!cur_.empty() && Matches(clz, cur_[0])) {
cur_.remove_prefix(1);
}
return *this;
}
Scanner& Many(CharClass clz) { return One(clz).Any(clz); }
Scanner& RestartCapture() {
capture_start_ = cur_.data();
capture_end_ = nullptr;
return *this;
}
Scanner& StopCapture() {
capture_end_ = cur_.data();
return *this;
}
Scanner& Eos() {
if (!cur_.empty()) error_ = true;
return *this;
}
Scanner& AnySpace() { return Any(SPACE); }
Scanner& ScanUntil(char end_ch) {
ScanUntilImpl(end_ch, false);
return *this;
}
Scanner& ScanEscapedUntil(char end_ch) {
ScanUntilImpl(end_ch, true);
return *this;
}
char Peek(char default_value = '\0') const {
return cur_.empty() ? default_value : cur_[0];
}
int empty() const { return cur_.empty(); }
bool GetResult(StringPiece* remaining = nullptr,
StringPiece* capture = nullptr);
private:
void ScanUntilImpl(char end_ch, bool escaped);
Scanner& Error() {
error_ = true;
return *this;
}
static bool IsLetter(char ch) {
return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z');
}
static bool IsLowerLetter(char ch) { return ch >= 'a' && ch <= 'z'; }
static bool IsDigit(char ch) { return ch >= '0' && ch <= '9'; }
static bool IsSpace(char ch) {
return (ch == ' ' || ch == '\t' || ch == '\n' || ch == '\v' || ch == '\f' ||
ch == '\r');
}
static bool Matches(CharClass clz, char ch) {
switch (clz) {
case ALL:
return true;
case DIGIT:
return IsDigit(ch);
case LETTER:
return IsLetter(ch);
case LETTER_DIGIT:
return IsLetter(ch) || IsDigit(ch);
case LETTER_DIGIT_DASH_UNDERSCORE:
return (IsLetter(ch) || IsDigit(ch) || ch == '-' || ch == '_');
case LETTER_DIGIT_DASH_DOT_SLASH:
return IsLetter(ch) || IsDigit(ch) || ch == '-' || ch == '.' ||
ch == '/';
case LETTER_DIGIT_DASH_DOT_SLASH_UNDERSCORE:
return (IsLetter(ch) || IsDigit(ch) || ch == '-' || ch == '.' ||
ch == '/' || ch == '_');
case LETTER_DIGIT_DOT:
return IsLetter(ch) || IsDigit(ch) || ch == '.';
case LETTER_DIGIT_DOT_PLUS_MINUS:
return IsLetter(ch) || IsDigit(ch) || ch == '+' || ch == '-' ||
ch == '.';
case LETTER_DIGIT_DOT_UNDERSCORE:
return IsLetter(ch) || IsDigit(ch) || ch == '.' || ch == '_';
case LETTER_DIGIT_UNDERSCORE:
return IsLetter(ch) || IsDigit(ch) || ch == '_';
case LOWERLETTER:
return ch >= 'a' && ch <= 'z';
case LOWERLETTER_DIGIT:
return IsLowerLetter(ch) || IsDigit(ch);
case LOWERLETTER_DIGIT_UNDERSCORE:
return IsLowerLetter(ch) || IsDigit(ch) || ch == '_';
case NON_ZERO_DIGIT:
return IsDigit(ch) && ch != '0';
case SPACE:
return IsSpace(ch);
case UPPERLETTER:
return ch >= 'A' && ch <= 'Z';
case RANGLE:
return ch == '>';
}
return false;
}
StringPiece cur_;
const char* capture_start_ = nullptr;
const char* capture_end_ = nullptr;
bool error_ = false;
friend class ScannerTest;
Scanner(const Scanner&) = delete;
void operator=(const Scanner&) = delete;
};
}
}
#endif
#include "tsl/platform/scanner.h"
namespace tsl {
namespace strings {
void Scanner::ScanUntilImpl(char end_ch, bool escaped) {
for (;;) {
if (cur_.empty()) {
Error();
return;
}
const char ch = cur_[0];
if (ch == end_ch) {
return;
}
cur_.remove_prefix(1);
if (escaped && ch == '\\') {
if (cur_.empty()) {
Error();
return;
}
cur_.remove_prefix(1);
}
}
}
bool Scanner::GetResult(StringPiece* remaining, StringPiece* capture) {
if (error_) {
return false;
}
if (remaining != nullptr) {
*remaining = cur_;
}
if (capture != nullptr) {
const char* end = capture_end_ == nullptr ? cur_.data() : capture_end_;
*capture = StringPiece(capture_start_, end - capture_start_);
}
return true;
}
}
} | #include "tsl/platform/scanner.h"
#include "tsl/platform/test.h"
namespace tsl {
namespace strings {
class ScannerTest : public ::testing::Test {
protected:
string ClassStr(Scanner::CharClass clz) {
string s;
for (int i = 0; i < 256; ++i) {
char ch = i;
if (Scanner::Matches(clz, ch)) {
s += ch;
}
}
return s;
}
};
TEST_F(ScannerTest, Any) {
StringPiece remaining, match;
EXPECT_TRUE(Scanner(" horse0123")
.Any(Scanner::SPACE)
.Any(Scanner::DIGIT)
.Any(Scanner::LETTER)
.GetResult(&remaining, &match));
EXPECT_EQ(" horse", match);
EXPECT_EQ("0123", remaining);
EXPECT_TRUE(Scanner("")
.Any(Scanner::SPACE)
.Any(Scanner::DIGIT)
.Any(Scanner::LETTER)
.GetResult(&remaining, &match));
EXPECT_EQ("", remaining);
EXPECT_EQ("", match);
EXPECT_TRUE(Scanner("----")
.Any(Scanner::SPACE)
.Any(Scanner::DIGIT)
.Any(Scanner::LETTER)
.GetResult(&remaining, &match));
EXPECT_EQ("----", remaining);
EXPECT_EQ("", match);
}
TEST_F(ScannerTest, AnySpace) {
StringPiece remaining, match;
EXPECT_TRUE(Scanner(" a b ")
.AnySpace()
.One(Scanner::LETTER)
.AnySpace()
.GetResult(&remaining, &match));
EXPECT_EQ(" a ", match);
EXPECT_EQ("b ", remaining);
}
TEST_F(ScannerTest, AnyEscapedNewline) {
StringPiece remaining, match;
EXPECT_TRUE(Scanner("\\\n")
.Any(Scanner::LETTER_DIGIT_UNDERSCORE)
.GetResult(&remaining, &match));
EXPECT_EQ("\\\n", remaining);
EXPECT_EQ("", match);
}
TEST_F(ScannerTest, AnyEmptyString) {
StringPiece remaining, match;
EXPECT_TRUE(Scanner("")
.Any(Scanner::LETTER_DIGIT_UNDERSCORE)
.GetResult(&remaining, &match));
EXPECT_EQ("", remaining);
EXPECT_EQ("", match);
}
TEST_F(ScannerTest, Eos) {
EXPECT_FALSE(Scanner("a").Eos().GetResult());
EXPECT_TRUE(Scanner("").Eos().GetResult());
EXPECT_FALSE(Scanner("abc").OneLiteral("ab").Eos().GetResult());
EXPECT_TRUE(Scanner("abc").OneLiteral("abc").Eos().GetResult());
}
TEST_F(ScannerTest, Many) {
StringPiece remaining, match;
EXPECT_TRUE(Scanner("abc").Many(Scanner::LETTER).GetResult());
EXPECT_FALSE(Scanner("0").Many(Scanner::LETTER).GetResult());
EXPECT_FALSE(Scanner("").Many(Scanner::LETTER).GetResult());
EXPECT_TRUE(
Scanner("abc ").Many(Scanner::LETTER).GetResult(&remaining, &match));
EXPECT_EQ(" ", remaining);
EXPECT_EQ("abc", match);
EXPECT_TRUE(
Scanner("abc").Many(Scanner::LETTER).GetResult(&remaining, &match));
EXPECT_EQ("", remaining);
EXPECT_EQ("abc", match);
}
TEST_F(ScannerTest, One) {
StringPiece remaining, match;
EXPECT_TRUE(Scanner("abc").One(Scanner::LETTER).GetResult());
EXPECT_FALSE(Scanner("0").One(Scanner::LETTER).GetResult());
EXPECT_FALSE(Scanner("").One(Scanner::LETTER).GetResult());
EXPECT_TRUE(Scanner("abc")
.One(Scanner::LETTER)
.One(Scanner::LETTER)
.GetResult(&remaining, &match));
EXPECT_EQ("c", remaining);
EXPECT_EQ("ab", match);
EXPECT_TRUE(Scanner("a").One(Scanner::LETTER).GetResult(&remaining, &match));
EXPECT_EQ("", remaining);
EXPECT_EQ("a", match);
}
TEST_F(ScannerTest, OneLiteral) {
EXPECT_FALSE(Scanner("abc").OneLiteral("abC").GetResult());
EXPECT_TRUE(Scanner("abc").OneLiteral("ab").OneLiteral("c").GetResult());
}
TEST_F(ScannerTest, ScanUntil) {
StringPiece remaining, match;
EXPECT_TRUE(Scanner(R"(' \1 \2 \3 \' \\'rest)")
.OneLiteral("'")
.ScanUntil('\'')
.OneLiteral("'")
.GetResult(&remaining, &match));
EXPECT_EQ(R"( \\'rest)", remaining);
EXPECT_EQ(R"(' \1 \2 \3 \')", match);
remaining = match = "unset";
EXPECT_FALSE(Scanner(R"(' \1 \2 \3 \\rest)")
.OneLiteral("'")
.ScanUntil('\'')
.GetResult(&remaining, &match));
EXPECT_EQ("unset", remaining);
EXPECT_EQ("unset", match);
remaining = match = "";
EXPECT_TRUE(
Scanner(R"(123\456)").ScanUntil('\\').GetResult(&remaining, &match));
EXPECT_EQ(R"(\456)", remaining);
EXPECT_EQ("123", match);
}
TEST_F(ScannerTest, ScanEscapedUntil) {
StringPiece remaining, match;
EXPECT_TRUE(Scanner(R"(' \1 \2 \3 \' \\'rest)")
.OneLiteral("'")
.ScanEscapedUntil('\'')
.OneLiteral("'")
.GetResult(&remaining, &match));
EXPECT_EQ("rest", remaining);
EXPECT_EQ(R"(' \1 \2 \3 \' \\')", match);
remaining = match = "unset";
EXPECT_FALSE(Scanner(R"(' \1 \2 \3 \' \\rest)")
.OneLiteral("'")
.ScanEscapedUntil('\'')
.GetResult(&remaining, &match));
EXPECT_EQ("unset", remaining);
EXPECT_EQ("unset", match);
}
TEST_F(ScannerTest, ZeroOrOneLiteral) {
StringPiece remaining, match;
EXPECT_TRUE(
Scanner("abc").ZeroOrOneLiteral("abC").GetResult(&remaining, &match));
EXPECT_EQ("abc", remaining);
EXPECT_EQ("", match);
EXPECT_TRUE(
Scanner("abcd").ZeroOrOneLiteral("ab").ZeroOrOneLiteral("c").GetResult(
&remaining, &match));
EXPECT_EQ("d", remaining);
EXPECT_EQ("abc", match);
EXPECT_TRUE(
Scanner("").ZeroOrOneLiteral("abc").GetResult(&remaining, &match));
EXPECT_EQ("", remaining);
EXPECT_EQ("", match);
}
TEST_F(ScannerTest, CaptureAndGetResult) {
StringPiece remaining, match;
Scanner scan(" first second");
EXPECT_TRUE(scan.Any(Scanner::SPACE)
.RestartCapture()
.One(Scanner::LETTER)
.Any(Scanner::LETTER_DIGIT)
.StopCapture()
.Any(Scanner::SPACE)
.GetResult(&remaining, &match));
EXPECT_EQ("second", remaining);
EXPECT_EQ("first", match);
EXPECT_TRUE(scan.GetResult());
remaining = "";
EXPECT_TRUE(scan.GetResult(&remaining));
EXPECT_EQ("second", remaining);
remaining = "";
match = "";
EXPECT_TRUE(scan.GetResult(&remaining, &match));
EXPECT_EQ("second", remaining);
EXPECT_EQ("first", match);
scan.RestartCapture().One(Scanner::LETTER).One(Scanner::LETTER);
remaining = "";
match = "";
EXPECT_TRUE(scan.GetResult(&remaining, &match));
EXPECT_EQ("cond", remaining);
EXPECT_EQ("se", match);
}
TEST_F(ScannerTest, MultipleGetResultExtendsCapture) {
StringPiece remaining, match;
Scanner scan("one2three");
EXPECT_TRUE(scan.Many(Scanner::LETTER).GetResult(&remaining, &match));
EXPECT_EQ("2three", remaining);
EXPECT_EQ("one", match);
EXPECT_TRUE(scan.Many(Scanner::DIGIT).GetResult(&remaining, &match));
EXPECT_EQ("three", remaining);
EXPECT_EQ("one2", match);
EXPECT_TRUE(scan.Many(Scanner::LETTER).GetResult(&remaining, &match));
EXPECT_EQ("", remaining);
EXPECT_EQ("one2three", match);
}
TEST_F(ScannerTest, FailedMatchDoesntChangeResult) {
Scanner scan("name");
StringPiece remaining = "rem";
StringPiece match = "match";
EXPECT_FALSE(scan.One(Scanner::SPACE).GetResult(&remaining, &match));
EXPECT_EQ("rem", remaining);
EXPECT_EQ("match", match);
}
TEST_F(ScannerTest, DefaultCapturesAll) {
Scanner scan("a b");
StringPiece remaining = "rem";
StringPiece match = "match";
EXPECT_TRUE(scan.Any(Scanner::LETTER)
.AnySpace()
.Any(Scanner::LETTER)
.GetResult(&remaining, &match));
EXPECT_EQ("", remaining);
EXPECT_EQ("a b", match);
}
TEST_F(ScannerTest, AllCharClasses) {
EXPECT_EQ(256, ClassStr(Scanner::ALL).size());
EXPECT_EQ("0123456789", ClassStr(Scanner::DIGIT));
EXPECT_EQ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
ClassStr(Scanner::LETTER));
EXPECT_EQ("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
ClassStr(Scanner::LETTER_DIGIT));
EXPECT_EQ(
"-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_"
"abcdefghijklmnopqrstuvwxyz",
ClassStr(Scanner::LETTER_DIGIT_DASH_UNDERSCORE));
EXPECT_EQ(
"-./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz",
ClassStr(Scanner::LETTER_DIGIT_DASH_DOT_SLASH));
EXPECT_EQ(
"-./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_"
"abcdefghijklmnopqrstuvwxyz",
ClassStr(Scanner::LETTER_DIGIT_DASH_DOT_SLASH_UNDERSCORE));
EXPECT_EQ(".0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
ClassStr(Scanner::LETTER_DIGIT_DOT));
EXPECT_EQ("+-.0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
ClassStr(Scanner::LETTER_DIGIT_DOT_PLUS_MINUS));
EXPECT_EQ(".0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz",
ClassStr(Scanner::LETTER_DIGIT_DOT_UNDERSCORE));
EXPECT_EQ("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz",
ClassStr(Scanner::LETTER_DIGIT_UNDERSCORE));
EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", ClassStr(Scanner::LOWERLETTER));
EXPECT_EQ("0123456789abcdefghijklmnopqrstuvwxyz",
ClassStr(Scanner::LOWERLETTER_DIGIT));
EXPECT_EQ("0123456789_abcdefghijklmnopqrstuvwxyz",
ClassStr(Scanner::LOWERLETTER_DIGIT_UNDERSCORE));
EXPECT_EQ("123456789", ClassStr(Scanner::NON_ZERO_DIGIT));
EXPECT_EQ("\t\n\v\f\r ", ClassStr(Scanner::SPACE));
EXPECT_EQ("ABCDEFGHIJKLMNOPQRSTUVWXYZ", ClassStr(Scanner::UPPERLETTER));
EXPECT_EQ(">", ClassStr(Scanner::RANGLE));
}
TEST_F(ScannerTest, Peek) {
EXPECT_EQ('a', Scanner("abc").Peek());
EXPECT_EQ('a', Scanner("abc").Peek('b'));
EXPECT_EQ('\0', Scanner("").Peek());
EXPECT_EQ('z', Scanner("").Peek('z'));
EXPECT_EQ('A', Scanner("0123A").Any(Scanner::DIGIT).Peek());
EXPECT_EQ('\0', Scanner("0123A").Any(Scanner::LETTER_DIGIT).Peek());
}
}
} | 2,256 |
#ifndef TENSORFLOW_TSL_PLATFORM_STRINGPRINTF_H_
#define TENSORFLOW_TSL_PLATFORM_STRINGPRINTF_H_
#include <stdarg.h>
#include <string>
#include "tsl/platform/macros.h"
#include "tsl/platform/types.h"
namespace tsl {
namespace strings {
std::string Printf(const char* format, ...)
TF_PRINTF_ATTRIBUTE(1, 2);
void Appendf(std::string* dst, const char* format, ...)
TF_PRINTF_ATTRIBUTE(2, 3);
void Appendv(std::string* dst, const char* format, va_list ap);
}
}
#endif
#include "tsl/platform/stringprintf.h"
#include <errno.h>
#include <stdarg.h>
#include <stdio.h>
namespace tsl {
namespace strings {
void Appendv(string* dst, const char* format, va_list ap) {
static const int kSpaceLength = 1024;
char space[kSpaceLength];
va_list backup_ap;
va_copy(backup_ap, ap);
int result = vsnprintf(space, kSpaceLength, format, backup_ap);
va_end(backup_ap);
if (result < kSpaceLength) {
if (result >= 0) {
dst->append(space, result);
return;
}
#ifdef _MSC_VER
va_copy(backup_ap, ap);
result = vsnprintf(nullptr, 0, format, backup_ap);
va_end(backup_ap);
#endif
if (result < 0) {
return;
}
}
int length = result + 1;
char* buf = new char[length];
va_copy(backup_ap, ap);
result = vsnprintf(buf, length, format, backup_ap);
va_end(backup_ap);
if (result >= 0 && result < length) {
dst->append(buf, result);
}
delete[] buf;
}
string Printf(const char* format, ...) {
va_list ap;
va_start(ap, format);
string result;
Appendv(&result, format, ap);
va_end(ap);
return result;
}
void Appendf(string* dst, const char* format, ...) {
va_list ap;
va_start(ap, format);
Appendv(dst, format, ap);
va_end(ap);
}
}
} | #include "tsl/platform/stringprintf.h"
#include <string>
#include "tsl/platform/test.h"
namespace tsl {
namespace strings {
namespace {
TEST(PrintfTest, Empty) {
EXPECT_EQ("", Printf("%s", string().c_str()));
EXPECT_EQ("", Printf("%s", ""));
}
TEST(PrintfTest, Misc) {
#if !defined(_MSC_VER)
EXPECT_EQ("123hello w", Printf("%3$d%2$s %1$c", 'w', "hello", 123));
#endif
}
TEST(AppendfTest, Empty) {
string value("Hello");
const char* empty = "";
Appendf(&value, "%s", empty);
EXPECT_EQ("Hello", value);
}
TEST(AppendfTest, EmptyString) {
string value("Hello");
Appendf(&value, "%s", "");
EXPECT_EQ("Hello", value);
}
TEST(AppendfTest, String) {
string value("Hello");
Appendf(&value, " %s", "World");
EXPECT_EQ("Hello World", value);
}
TEST(AppendfTest, Int) {
string value("Hello");
Appendf(&value, " %d", 123);
EXPECT_EQ("Hello 123", value);
}
TEST(PrintfTest, Multibyte) {
char* old_locale = setlocale(LC_CTYPE, nullptr);
setlocale(LC_CTYPE, "en_US.utf8");
const char kInvalidCodePoint[] = "\375\067s";
string value = Printf("%.*s", 3, kInvalidCodePoint);
EXPECT_TRUE(value.empty() || value == kInvalidCodePoint);
int n = 2048;
char* buf = new char[n + 1];
memset(buf, ' ', n - 3);
memcpy(buf + n - 3, kInvalidCodePoint, 4);
value = Printf("%.*s", n, buf);
EXPECT_TRUE(value.empty() || value == buf);
delete[] buf;
setlocale(LC_CTYPE, old_locale);
}
TEST(PrintfTest, NoMultibyte) {
char* old_locale = setlocale(LC_CTYPE, nullptr);
setlocale(LC_CTYPE, "POSIX");
string value = Printf("%.*s", 3, "\375\067s");
setlocale(LC_CTYPE, old_locale);
EXPECT_EQ("\375\067s", value);
}
TEST(PrintfTest, DontOverwriteErrno) {
errno = ECHILD;
string value = Printf("Hello, %s!", "World");
EXPECT_EQ(ECHILD, errno);
}
TEST(PrintfTest, LargeBuf) {
int n = 2048;
char* buf = new char[n + 1];
memset(buf, ' ', n);
buf[n] = 0;
string value = Printf("%s", buf);
EXPECT_EQ(buf, value);
delete[] buf;
}
}
}
} | 2,257 |
#ifndef TENSORFLOW_TSL_PLATFORM_CODING_H_
#define TENSORFLOW_TSL_PLATFORM_CODING_H_
#include "tsl/platform/stringpiece.h"
#include "tsl/platform/tstring.h"
#include "tsl/platform/types.h"
namespace tsl {
namespace core {
static const int kMaxVarint32Bytes = 5;
static const int kMaxVarint64Bytes = 10;
extern void EncodeFixed16(char* dst, uint16 value);
extern void EncodeFixed32(char* dst, uint32 value);
extern void EncodeFixed64(char* dst, uint64 value);
extern void PutFixed16(string* dst, uint16 value);
extern void PutFixed32(string* dst, uint32 value);
extern void PutFixed64(string* dst, uint64 value);
extern void PutVarint32(string* dst, uint32 value);
extern void PutVarint64(string* dst, uint64 value);
extern void PutVarint32(tstring* dst, uint32 value);
extern void PutVarint64(tstring* dst, uint64 value);
extern bool GetVarint32(StringPiece* input, uint32* value);
extern bool GetVarint64(StringPiece* input, uint64* value);
extern const char* GetVarint32Ptr(const char* p, const char* limit, uint32* v);
extern const char* GetVarint64Ptr(const char* p, const char* limit, uint64* v);
extern const char* GetVarint32PtrFallback(const char* p, const char* limit,
uint32* value);
extern const char* GetVarint32Ptr(const char* p, const char* limit,
uint32* value);
extern char* EncodeVarint32(char* dst, uint32 v);
extern char* EncodeVarint64(char* dst, uint64 v);
extern int VarintLength(uint64_t v);
}
}
#endif
#include "tsl/platform/coding.h"
#include "tsl/platform/byte_order.h"
#include "tsl/platform/stringpiece.h"
#include "tsl/platform/tstring.h"
#include "tsl/platform/types.h"
namespace tsl {
namespace core {
void EncodeFixed16(char* buf, uint16 value) {
if (port::kLittleEndian) {
memcpy(buf, &value, sizeof(value));
} else {
buf[0] = value & 0xff;
buf[1] = (value >> 8) & 0xff;
}
}
void EncodeFixed32(char* buf, uint32 value) {
if (port::kLittleEndian) {
memcpy(buf, &value, sizeof(value));
} else {
buf[0] = value & 0xff;
buf[1] = (value >> 8) & 0xff;
buf[2] = (value >> 16) & 0xff;
buf[3] = (value >> 24) & 0xff;
}
}
void EncodeFixed64(char* buf, uint64 value) {
if (port::kLittleEndian) {
memcpy(buf, &value, sizeof(value));
} else {
buf[0] = value & 0xff;
buf[1] = (value >> 8) & 0xff;
buf[2] = (value >> 16) & 0xff;
buf[3] = (value >> 24) & 0xff;
buf[4] = (value >> 32) & 0xff;
buf[5] = (value >> 40) & 0xff;
buf[6] = (value >> 48) & 0xff;
buf[7] = (value >> 56) & 0xff;
}
}
void PutFixed16(string* dst, uint16 value) {
char buf[sizeof(value)];
EncodeFixed16(buf, value);
dst->append(buf, sizeof(buf));
}
void PutFixed32(string* dst, uint32 value) {
char buf[sizeof(value)];
EncodeFixed32(buf, value);
dst->append(buf, sizeof(buf));
}
void PutFixed64(string* dst, uint64 value) {
char buf[sizeof(value)];
EncodeFixed64(buf, value);
dst->append(buf, sizeof(buf));
}
char* EncodeVarint32(char* dst, uint32 v) {
unsigned char* ptr = reinterpret_cast<unsigned char*>(dst);
static const int B = 128;
if (v < (1 << 7)) {
*(ptr++) = v;
} else if (v < (1 << 14)) {
*(ptr++) = v | B;
*(ptr++) = v >> 7;
} else if (v < (1 << 21)) {
*(ptr++) = v | B;
*(ptr++) = (v >> 7) | B;
*(ptr++) = v >> 14;
} else if (v < (1 << 28)) {
*(ptr++) = v | B;
*(ptr++) = (v >> 7) | B;
*(ptr++) = (v >> 14) | B;
*(ptr++) = v >> 21;
} else {
*(ptr++) = v | B;
*(ptr++) = (v >> 7) | B;
*(ptr++) = (v >> 14) | B;
*(ptr++) = (v >> 21) | B;
*(ptr++) = v >> 28;
}
return reinterpret_cast<char*>(ptr);
}
void PutVarint32(string* dst, uint32 v) {
char buf[5];
char* ptr = EncodeVarint32(buf, v);
dst->append(buf, ptr - buf);
}
void PutVarint32(tstring* dst, uint32 v) {
char buf[5];
char* ptr = EncodeVarint32(buf, v);
dst->append(buf, ptr - buf);
}
char* EncodeVarint64(char* dst, uint64 v) {
static const int B = 128;
unsigned char* ptr = reinterpret_cast<unsigned char*>(dst);
while (v >= B) {
*(ptr++) = (v & (B - 1)) | B;
v >>= 7;
}
*(ptr++) = static_cast<unsigned char>(v);
return reinterpret_cast<char*>(ptr);
}
void PutVarint64(string* dst, uint64 v) {
char buf[10];
char* ptr = EncodeVarint64(buf, v);
dst->append(buf, ptr - buf);
}
void PutVarint64(tstring* dst, uint64 v) {
char buf[10];
char* ptr = EncodeVarint64(buf, v);
dst->append(buf, ptr - buf);
}
int VarintLength(uint64_t v) {
int len = 1;
while (v >= 128) {
v >>= 7;
len++;
}
return len;
}
const char* GetVarint32Ptr(const char* p, const char* limit, uint32* value) {
if (p < limit) {
uint32 result = *(reinterpret_cast<const unsigned char*>(p));
if ((result & 128) == 0) {
*value = result;
return p + 1;
}
}
return GetVarint32PtrFallback(p, limit, value);
}
const char* GetVarint32PtrFallback(const char* p, const char* limit,
uint32* value) {
uint32 result = 0;
for (uint32 shift = 0; shift <= 28 && p < limit; shift += 7) {
uint32 byte = *(reinterpret_cast<const unsigned char*>(p));
p++;
if (byte & 128) {
result |= ((byte & 127) << shift);
} else {
result |= (byte << shift);
*value = result;
return reinterpret_cast<const char*>(p);
}
}
return nullptr;
}
bool GetVarint32(StringPiece* input, uint32* value) {
const char* p = input->data();
const char* limit = p + input->size();
const char* q = GetVarint32Ptr(p, limit, value);
if (q == nullptr) {
return false;
} else {
*input = StringPiece(q, limit - q);
return true;
}
}
const char* GetVarint64Ptr(const char* p, const char* limit, uint64* value) {
uint64 result = 0;
for (uint32 shift = 0; shift <= 63 && p < limit; shift += 7) {
uint64 byte = *(reinterpret_cast<const unsigned char*>(p));
p++;
if (byte & 128) {
result |= ((byte & 127) << shift);
} else {
result |= (byte << shift);
*value = result;
return reinterpret_cast<const char*>(p);
}
}
return nullptr;
}
bool GetVarint64(StringPiece* input, uint64* value) {
const char* p = input->data();
const char* limit = p + input->size();
const char* q = GetVarint64Ptr(p, limit, value);
if (q == nullptr) {
return false;
} else {
*input = StringPiece(q, limit - q);
return true;
}
}
}
} | #include "tensorflow/core/lib/core/coding.h"
#include <vector>
#include "tensorflow/core/platform/test.h"
namespace tensorflow {
namespace core {
TEST(Coding, Fixed16) {
static const uint16 N = 50000;
string s;
for (uint16 v = 0; v < N; v++) {
char buf[sizeof(uint16)];
EncodeFixed16(buf, v);
s.append(buf, sizeof(buf));
}
const char* p = s.data();
for (uint16 v = 0; v < N; v++) {
uint16 actual = DecodeFixed16(p);
ASSERT_EQ(v, actual);
p += sizeof(uint16);
}
}
TEST(Coding, Fixed32) {
static const uint32 N = 100000;
string s;
for (uint32 v = 0; v < N; v++) {
char buf[sizeof(uint32)];
EncodeFixed32(buf, v);
s.append(buf, sizeof(buf));
}
const char* p = s.data();
for (uint32 v = 0; v < N; v++) {
uint32 actual = DecodeFixed32(p);
ASSERT_EQ(v, actual);
p += sizeof(uint32);
}
}
TEST(Coding, Fixed64) {
string s;
for (int power = 0; power <= 63; power++) {
uint64 v = static_cast<uint64>(1) << power;
char buf[sizeof(uint64)];
EncodeFixed64(buf, v - 1);
s.append(buf, sizeof(buf));
EncodeFixed64(buf, v + 0);
s.append(buf, sizeof(buf));
EncodeFixed64(buf, v + 1);
s.append(buf, sizeof(buf));
}
const char* p = s.data();
for (int power = 0; power <= 63; power++) {
uint64 v = static_cast<uint64>(1) << power;
uint64 actual;
actual = DecodeFixed64(p);
ASSERT_EQ(v - 1, actual);
p += sizeof(uint64);
actual = DecodeFixed64(p);
ASSERT_EQ(v + 0, actual);
p += sizeof(uint64);
actual = DecodeFixed64(p);
ASSERT_EQ(v + 1, actual);
p += sizeof(uint64);
}
}
TEST(Coding, EncodingOutput) {
char dst[8];
EncodeFixed16(dst, 0x0201);
ASSERT_EQ(0x01, static_cast<int>(dst[0]));
ASSERT_EQ(0x02, static_cast<int>(dst[1]));
EncodeFixed32(dst, 0x04030201);
ASSERT_EQ(0x01, static_cast<int>(dst[0]));
ASSERT_EQ(0x02, static_cast<int>(dst[1]));
ASSERT_EQ(0x03, static_cast<int>(dst[2]));
ASSERT_EQ(0x04, static_cast<int>(dst[3]));
EncodeFixed64(dst, 0x0807060504030201ull);
ASSERT_EQ(0x01, static_cast<int>(dst[0]));
ASSERT_EQ(0x02, static_cast<int>(dst[1]));
ASSERT_EQ(0x03, static_cast<int>(dst[2]));
ASSERT_EQ(0x04, static_cast<int>(dst[3]));
ASSERT_EQ(0x05, static_cast<int>(dst[4]));
ASSERT_EQ(0x06, static_cast<int>(dst[5]));
ASSERT_EQ(0x07, static_cast<int>(dst[6]));
ASSERT_EQ(0x08, static_cast<int>(dst[7]));
}
TEST(Coding, Varint32) {
string s;
for (uint32 i = 0; i < (32 * 32); i++) {
uint32 v = (i / 32) << (i % 32);
PutVarint32(&s, v);
}
const char* p = s.data();
const char* limit = p + s.size();
for (uint32 i = 0; i < (32 * 32); i++) {
uint32 expected = (i / 32) << (i % 32);
uint32 actual;
p = GetVarint32Ptr(p, limit, &actual);
ASSERT_TRUE(p != nullptr);
ASSERT_EQ(expected, actual);
}
ASSERT_EQ(p, s.data() + s.size());
}
TEST(Coding, Varint64) {
std::vector<uint64> values;
values.push_back(0);
values.push_back(100);
values.push_back(~static_cast<uint64>(0));
values.push_back(~static_cast<uint64>(0) - 1);
for (uint32 k = 0; k < 64; k++) {
const uint64 power = 1ull << k;
values.push_back(power);
values.push_back(power - 1);
values.push_back(power + 1);
}
string s;
for (size_t i = 0; i < values.size(); i++) {
PutVarint64(&s, values[i]);
}
const char* p = s.data();
const char* limit = p + s.size();
for (size_t i = 0; i < values.size(); i++) {
ASSERT_TRUE(p < limit);
uint64 actual;
p = GetVarint64Ptr(p, limit, &actual);
ASSERT_TRUE(p != nullptr);
ASSERT_EQ(values[i], actual);
}
ASSERT_EQ(p, limit);
}
TEST(Coding, Varint32Overflow) {
uint32 result;
string input("\x81\x82\x83\x84\x85\x11");
ASSERT_TRUE(GetVarint32Ptr(input.data(), input.data() + input.size(),
&result) == nullptr);
}
TEST(Coding, Varint32Truncation) {
uint32 large_value = (1u << 31) + 100;
string s;
PutVarint32(&s, large_value);
uint32 result;
for (size_t len = 0; len < s.size() - 1; len++) {
ASSERT_TRUE(GetVarint32Ptr(s.data(), s.data() + len, &result) == nullptr);
}
ASSERT_TRUE(GetVarint32Ptr(s.data(), s.data() + s.size(), &result) !=
nullptr);
ASSERT_EQ(large_value, result);
}
TEST(Coding, Varint64Overflow) {
uint64 result;
string input("\x81\x82\x83\x84\x85\x81\x82\x83\x84\x85\x11");
ASSERT_TRUE(GetVarint64Ptr(input.data(), input.data() + input.size(),
&result) == nullptr);
}
TEST(Coding, Varint64Truncation) {
uint64 large_value = (1ull << 63) + 100ull;
string s;
PutVarint64(&s, large_value);
uint64 result;
for (size_t len = 0; len < s.size() - 1; len++) {
ASSERT_TRUE(GetVarint64Ptr(s.data(), s.data() + len, &result) == nullptr);
}
ASSERT_TRUE(GetVarint64Ptr(s.data(), s.data() + s.size(), &result) !=
nullptr);
ASSERT_EQ(large_value, result);
}
}
} | 2,258 |
#ifndef TENSORFLOW_TSL_PLATFORM_ABI_H_
#define TENSORFLOW_TSL_PLATFORM_ABI_H_
#include <string>
#include "tsl/platform/types.h"
namespace tsl {
namespace port {
std::string MaybeAbiDemangle(const char* name);
}
}
#endif
#include "tsl/platform/abi.h"
#include "tsl/platform/types.h"
#if defined(_MSC_VER)
#include <windows.h>
#include <cstring>
#else
#include <cxxabi.h>
#include <cstdlib>
#endif
#include <memory>
#include <string>
#if defined(_MSC_VER)
extern "C" char* __unDName(char* output_string, const char* name,
int max_string_length, void* (*p_alloc)(std::size_t),
void (*p_free)(void*), unsigned short disable_flags);
#endif
namespace tsl {
namespace port {
string MaybeAbiDemangle(const char* name) {
#if defined(_MSC_VER)
std::unique_ptr<char> demangled{__unDName(nullptr, name, 0, std::malloc,
std::free,
static_cast<unsigned short>(0))};
return string(demangled.get() != nullptr ? demangled.get() : name);
#else
int status = 0;
std::unique_ptr<char, void (*)(void*)> res{
abi::__cxa_demangle(name, nullptr, nullptr, &status), std::free};
return (status == 0) ? res.get() : name;
#endif
}
}
} | #include "tsl/platform/abi.h"
#include <typeinfo>
#include "tsl/platform/test.h"
namespace tsl {
struct MyRandomPODType {};
TEST(AbiTest, AbiDemangleTest) {
EXPECT_EQ(port::MaybeAbiDemangle(typeid(int).name()), "int");
#ifdef PLATFORM_WINDOWS
const char pod_type_name[] = "struct tsl::MyRandomPODType";
#else
const char pod_type_name[] = "tsl::MyRandomPODType";
#endif
EXPECT_EQ(port::MaybeAbiDemangle(typeid(MyRandomPODType).name()),
pod_type_name);
EXPECT_EQ(
port::MaybeAbiDemangle("help! i'm caught in a C++ mangle factoryasdf"),
"help! i'm caught in a C++ mangle factoryasdf");
}
} | 2,259 |
#ifndef TENSORFLOW_TSL_PLATFORM_FILE_SYSTEM_H_
#define TENSORFLOW_TSL_PLATFORM_FILE_SYSTEM_H_
#include <stdint.h>
#include <functional>
#include <memory>
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>
#include "tsl/platform/cord.h"
#include "tsl/platform/errors.h"
#include "tsl/platform/file_statistics.h"
#include "tsl/platform/macros.h"
#include "tsl/platform/platform.h"
#include "tsl/platform/stringpiece.h"
#include "tsl/platform/types.h"
#ifdef PLATFORM_WINDOWS
#undef DeleteFile
#undef CopyFile
#undef TranslateName
#endif
namespace tsl {
class FileAcl;
class RandomAccessFile;
class ReadOnlyMemoryRegion;
class WritableFile;
class FileSystem;
struct TransactionToken {
FileSystem* owner;
void* token;
};
class FileSystem {
public:
virtual absl::Status NewRandomAccessFile(
const std::string& fname, std::unique_ptr<RandomAccessFile>* result) {
return NewRandomAccessFile(fname, nullptr, result);
}
virtual absl::Status NewRandomAccessFile(
const std::string& fname, TransactionToken* token,
std::unique_ptr<RandomAccessFile>* result) {
return absl::OkStatus();
}
virtual absl::Status NewWritableFile(const std::string& fname,
std::unique_ptr<WritableFile>* result) {
return NewWritableFile(fname, nullptr, result);
}
virtual absl::Status NewWritableFile(const std::string& fname,
TransactionToken* token,
std::unique_ptr<WritableFile>* result) {
return absl::OkStatus();
}
virtual absl::Status NewAppendableFile(
const std::string& fname, std::unique_ptr<WritableFile>* result) {
return NewAppendableFile(fname, nullptr, result);
}
virtual absl::Status NewAppendableFile(
const std::string& fname, TransactionToken* token,
std::unique_ptr<WritableFile>* result) {
return absl::OkStatus();
}
virtual absl::Status NewReadOnlyMemoryRegionFromFile(
const std::string& fname, std::unique_ptr<ReadOnlyMemoryRegion>* result) {
return NewReadOnlyMemoryRegionFromFile(fname, nullptr, result);
}
virtual absl::Status NewReadOnlyMemoryRegionFromFile(
const std::string& fname, TransactionToken* token,
std::unique_ptr<ReadOnlyMemoryRegion>* result) {
return absl::OkStatus();
}
virtual absl::Status FileExists(const std::string& fname) {
return FileExists(fname, nullptr);
}
virtual absl::Status FileExists(const std::string& fname,
TransactionToken* token) {
return absl::OkStatus();
}
virtual bool FilesExist(const std::vector<string>& files,
std::vector<absl::Status>* status) {
return FilesExist(files, nullptr, status);
}
virtual bool FilesExist(const std::vector<string>& files,
TransactionToken* token,
std::vector<absl::Status>* status);
virtual absl::Status GetChildren(const std::string& dir,
std::vector<string>* result) {
return GetChildren(dir, nullptr, result);
}
virtual absl::Status GetChildren(const std::string& dir,
TransactionToken* token,
std::vector<string>* result) {
return absl::OkStatus();
}
virtual absl::Status GetMatchingPaths(const std::string& pattern,
std::vector<string>* results) {
return GetMatchingPaths(pattern, nullptr, results);
}
virtual absl::Status GetMatchingPaths(const std::string& pattern,
TransactionToken* token,
std::vector<string>* results) {
return absl::OkStatus();
}
virtual bool Match(const std::string& filename, const std::string& pattern);
virtual absl::Status Stat(const std::string& fname, FileStatistics* stat) {
return Stat(fname, nullptr, stat);
}
virtual absl::Status Stat(const std::string& fname, TransactionToken* token,
FileStatistics* stat) {
return absl::OkStatus();
}
virtual absl::Status DeleteFile(const std::string& fname) {
return DeleteFile(fname, nullptr);
}
virtual absl::Status DeleteFile(const std::string& fname,
TransactionToken* token) {
return absl::OkStatus();
}
virtual absl::Status CreateDir(const std::string& dirname) {
return CreateDir(dirname, nullptr);
}
virtual absl::Status CreateDir(const std::string& dirname,
TransactionToken* token) {
return absl::OkStatus();
}
virtual absl::Status RecursivelyCreateDir(const std::string& dirname) {
return RecursivelyCreateDir(dirname, nullptr);
}
virtual absl::Status RecursivelyCreateDir(const std::string& dirname,
TransactionToken* token);
virtual absl::Status DeleteDir(const std::string& dirname) {
return DeleteDir(dirname, nullptr);
}
virtual absl::Status DeleteDir(const std::string& dirname,
TransactionToken* token) {
return absl::OkStatus();
}
virtual absl::Status DeleteRecursively(const std::string& dirname,
int64_t* undeleted_files,
int64_t* undeleted_dirs) {
return DeleteRecursively(dirname, nullptr, undeleted_files, undeleted_dirs);
}
virtual absl::Status DeleteRecursively(const std::string& dirname,
TransactionToken* token,
int64_t* undeleted_files,
int64_t* undeleted_dirs);
virtual absl::Status GetFileSize(const std::string& fname,
uint64* file_size) {
return GetFileSize(fname, nullptr, file_size);
}
virtual absl::Status GetFileSize(const std::string& fname,
TransactionToken* token, uint64* file_size) {
return absl::OkStatus();
}
virtual absl::Status RenameFile(const std::string& src,
const std::string& target) {
return RenameFile(src, target, nullptr);
}
virtual absl::Status RenameFile(const std::string& src,
const std::string& target,
TransactionToken* token) {
return absl::OkStatus();
}
virtual absl::Status CopyFile(const std::string& src,
const std::string& target) {
return CopyFile(src, target, nullptr);
}
virtual absl::Status CopyFile(const std::string& src,
const std::string& target,
TransactionToken* token);
virtual std::string TranslateName(const std::string& name) const;
virtual absl::Status IsDirectory(const std::string& fname) {
return IsDirectory(fname, nullptr);
}
virtual absl::Status IsDirectory(const std::string& fname,
TransactionToken* token);
virtual absl::Status HasAtomicMove(const std::string& path,
bool* has_atomic_move);
virtual absl::Status CanCreateTempFile(const std::string& fname,
bool* can_create_temp_file);
virtual void FlushCaches() { FlushCaches(nullptr); }
virtual void FlushCaches(TransactionToken* token);
virtual char Separator() const;
std::pair<StringPiece, StringPiece> SplitPath(StringPiece uri) const;
virtual StringPiece Basename(StringPiece path) const;
StringPiece Dirname(StringPiece path) const;
StringPiece Extension(StringPiece path) const;
std::string CleanPath(StringPiece path) const;
std::string CreateURI(StringPiece scheme, StringPiece host,
StringPiece path) const;
bool IsAbsolutePath(tsl::StringPiece path) const;
#ifndef SWIG
template <typename... T>
std::string JoinPath(const T&... args) {
return JoinPathImpl({args...});
}
#endif
std::string JoinPathImpl(std::initializer_list<tsl::StringPiece> paths);
void ParseURI(StringPiece remaining, StringPiece* scheme, StringPiece* host,
StringPiece* path) const;
virtual absl::Status StartTransaction(TransactionToken** token) {
*token = nullptr;
return absl::OkStatus();
}
virtual absl::Status AddToTransaction(const std::string& path,
TransactionToken* token) {
return absl::OkStatus();
}
virtual absl::Status EndTransaction(TransactionToken* token) {
return absl::OkStatus();
}
virtual absl::Status GetTokenOrStartTransaction(const std::string& path,
TransactionToken** token) {
*token = nullptr;
return absl::OkStatus();
}
virtual absl::Status GetTransactionForPath(const std::string& path,
TransactionToken** token) {
*token = nullptr;
return absl::OkStatus();
}
virtual std::string DecodeTransaction(const TransactionToken* token);
virtual absl::Status SetOption(const string& key, const string& value) {
return errors::Unimplemented("SetOption");
}
virtual absl::Status SetOption(const std::string& name,
const std::vector<string>& values) {
return errors::Unimplemented("SetOption");
}
virtual absl::Status SetOption(const std::string& name,
const std::vector<int64_t>& values) {
return errors::Unimplemented("SetOption");
}
virtual absl::Status SetOption(const std::string& name,
const std::vector<double>& values) {
return errors::Unimplemented("SetOption");
}
virtual absl::Status SetFileAcl(std::shared_ptr<FileAcl> file_acl) {
return errors::Unimplemented("SetFileAcl");
}
FileSystem() {}
virtual ~FileSystem() = default;
};
#define TF_USE_FILESYSTEM_METHODS_WITH_NO_TRANSACTION_SUPPORT \
using FileSystem::NewRandomAccessFile; \
using FileSystem::NewWritableFile; \
using FileSystem::NewAppendableFile; \
using FileSystem::NewReadOnlyMemoryRegionFromFile; \
using FileSystem::FileExists; \
using FileSystem::GetChildren; \
using FileSystem::GetMatchingPaths; \
using FileSystem::Stat; \
using FileSystem::DeleteFile; \
using FileSystem::RecursivelyCreateDir; \
using FileSystem::DeleteDir; \
using FileSystem::DeleteRecursively; \
using FileSystem::GetFileSize; \
using FileSystem::RenameFile; \
using FileSystem::CopyFile; \
using FileSystem::IsDirectory; \
using FileSystem::FlushCaches
class WrappedFileSystem : public FileSystem {
public:
TF_USE_FILESYSTEM_METHODS_WITH_NO_TRANSACTION_SUPPORT;
absl::Status NewRandomAccessFile(
const std::string& fname, TransactionToken* token,
std::unique_ptr<RandomAccessFile>* result) override {
return fs_->NewRandomAccessFile(fname, (token ? token : token_), result);
}
absl::Status NewWritableFile(const std::string& fname,
TransactionToken* token,
std::unique_ptr<WritableFile>* result) override {
return fs_->NewWritableFile(fname, (token ? token : token_), result);
}
absl::Status NewAppendableFile(
const std::string& fname, TransactionToken* token,
std::unique_ptr<WritableFile>* result) override {
return fs_->NewAppendableFile(fname, (token ? token : token_), result);
}
absl::Status NewReadOnlyMemoryRegionFromFile(
const std::string& fname, TransactionToken* token,
std::unique_ptr<ReadOnlyMemoryRegion>* result) override {
return fs_->NewReadOnlyMemoryRegionFromFile(fname, (token ? token : token_),
result);
}
absl::Status FileExists(const std::string& fname,
TransactionToken* token) override {
return fs_->FileExists(fname, (token ? token : token_));
}
bool FilesExist(const std::vector<string>& files, TransactionToken* token,
std::vector<absl::Status>* status) override {
return fs_->FilesExist(files, (token ? token : token_), status);
}
absl::Status GetChildren(const std::string& dir, TransactionToken* token,
std::vector<string>* result) override {
return fs_->GetChildren(dir, (token ? token : token_), result);
}
absl::Status GetMatchingPaths(const std::string& pattern,
TransactionToken* token,
std::vector<string>* results) override {
return fs_->GetMatchingPaths(pattern, (token ? token : token_), results);
}
bool Match(const std::string& filename, const std::string& pattern) override {
return fs_->Match(filename, pattern);
}
absl::Status Stat(const std::string& fname, TransactionToken* token,
FileStatistics* stat) override {
return fs_->Stat(fname, (token ? token : token_), stat);
}
absl::Status DeleteFile(const std::string& fname,
TransactionToken* token) override {
return fs_->DeleteFile(fname, (token ? token : token_));
}
absl::Status CreateDir(const std::string& dirname,
TransactionToken* token) override {
return fs_->CreateDir(dirname, (token ? token : token_));
}
absl::Status RecursivelyCreateDir(const std::string& dirname,
TransactionToken* token) override {
return fs_->RecursivelyCreateDir(dirname, (token ? token : token_));
}
absl::Status DeleteDir(const std::string& dirname,
TransactionToken* token) override {
return fs_->DeleteDir(dirname, (token ? token : token_));
}
absl::Status DeleteRecursively(const std::string& dirname,
TransactionToken* token,
int64_t* undeleted_files,
int64_t* undeleted_dirs) override {
return fs_->DeleteRecursively(dirname, (token ? token : token_),
undeleted_files, undeleted_dirs);
}
absl::Status GetFileSize(const std::string& fname, TransactionToken* token,
uint64* file_size) override {
return fs_->GetFileSize(fname, (token ? token : token_), file_size);
}
absl::Status RenameFile(const std::string& src, const std::string& target,
TransactionToken* token) override {
return fs_->RenameFile(src, target, (token ? token : token_));
}
absl::Status CopyFile(const std::string& src, const std::string& target,
TransactionToken* token) override {
return fs_->CopyFile(src, target, (token ? token : token_));
}
std::string TranslateName(const std::string& name) const override {
return fs_->TranslateName(name);
}
absl::Status IsDirectory(const std::string& fname,
TransactionToken* token) override {
return fs_->IsDirectory(fname, (token ? token : token_));
}
absl::Status HasAtomicMove(const std::string& path,
bool* has_atomic_move) override {
return fs_->HasAtomicMove(path, has_atomic_move);
}
void FlushCaches(TransactionToken* token) override {
return fs_->FlushCaches((token ? token : token_));
}
char Separator() const override { return fs_->Separator(); }
StringPiece Basename(StringPiece path) const override {
return fs_->Basename(path);
}
absl::Status StartTransaction(TransactionToken** token) override {
return fs_->StartTransaction(token);
}
absl::Status AddToTransaction(const std::string& path,
TransactionToken* token) override {
return fs_->AddToTransaction(path, (token ? token : token_));
}
absl::Status EndTransaction(TransactionToken* token) override {
return fs_->EndTransaction(token);
}
absl::Status GetTransactionForPath(const std::string& path,
TransactionToken** token) override {
return fs_->GetTransactionForPath(path, token);
}
absl::Status GetTokenOrStartTransaction(const std::string& path,
TransactionToken** token) override {
return fs_->GetTokenOrStartTransaction(path, token);
}
std::string DecodeTransaction(const TransactionToken* token) override {
return fs_->DecodeTransaction((token ? token : token_));
}
WrappedFileSystem(FileSystem* file_system, TransactionToken* token)
: fs_(file_system), token_(token) {}
~WrappedFileSystem() override = default;
private:
FileSystem* fs_;
TransactionToken* token_;
};
class RandomAccessFile {
public:
RandomAccessFile() {}
virtual ~RandomAccessFile() = default;
virtual absl::Status Name(StringPiece* result) const {
return errors::Unimplemented("This filesystem does not support Name()");
}
virtual absl::Status Read(uint64 offset, size_t n, StringPiece* result,
char* scratch) const = 0;
#if defined(TF_CORD_SUPPORT)
virtual absl::Status Read(uint64 offset, size_t n, absl::Cord* cord) const {
return errors::Unimplemented(
"Read(uint64, size_t, absl::Cord*) is not "
"implemented");
}
#endif
private:
RandomAccessFile(const RandomAccessFile&) = delete;
void operator=(const RandomAccessFile&) = delete;
};
class WritableFile {
public:
WritableFile() {}
virtual ~WritableFile() = default;
virtual absl::Status Append(StringPiece data) = 0;
#if defined(TF_CORD_SUPPORT)
virtual absl::Status Append(const absl::Cord& cord) {
for (StringPiece chunk : cord.Chunks()) {
TF_RETURN_IF_ERROR(Append(chunk));
}
return absl::OkStatus();
}
#endif
virtual absl::Status Close() = 0; | #include "tensorflow/core/platform/file_system.h"
#include <sys/stat.h>
#include "tensorflow/core/lib/core/status_test_util.h"
#include "tensorflow/core/platform/null_file_system.h"
#include "tensorflow/core/platform/path.h"
#include "tensorflow/core/platform/str_util.h"
#include "tensorflow/core/platform/strcat.h"
#include "tensorflow/core/platform/test.h"
namespace tensorflow {
static const char* const kPrefix = "ipfs:
class InterPlanetaryFileSystem : public NullFileSystem {
public:
TF_USE_FILESYSTEM_METHODS_WITH_NO_TRANSACTION_SUPPORT;
Status FileExists(const string& fname, TransactionToken* token) override {
string parsed_path;
ParsePath(fname, &parsed_path);
if (BodyExists(parsed_path)) {
return absl::OkStatus();
}
return Status(absl::StatusCode::kNotFound, "File does not exist");
}
Status CreateDir(const string& dirname, TransactionToken* token) override {
string parsed_path;
ParsePath(dirname, &parsed_path);
if (celestial_bodies_.find(parsed_path) != celestial_bodies_.end()) {
return Status(absl::StatusCode::kAlreadyExists,
"dirname already exists.");
}
std::vector<string> split_path = str_util::Split(parsed_path, '/');
if (split_path.size() > 3) {
return Status(absl::StatusCode::kInvalidArgument, "Bad dirname");
}
if (split_path.empty()) {
return absl::OkStatus();
}
if (split_path.size() == 1) {
celestial_bodies_[""].insert(parsed_path);
celestial_bodies_.insert(
std::pair<string, std::set<string>>(parsed_path, {}));
return absl::OkStatus();
}
if (split_path.size() == 2) {
if (!BodyExists(split_path[0])) {
return Status(absl::StatusCode::kFailedPrecondition,
"Base dir not created");
}
celestial_bodies_[split_path[0]].insert(split_path[1]);
celestial_bodies_.insert(
std::pair<string, std::set<string>>(parsed_path, {}));
return absl::OkStatus();
}
if (split_path.size() == 3) {
const string& parent_path = this->JoinPath(split_path[0], split_path[1]);
if (!BodyExists(parent_path)) {
return Status(absl::StatusCode::kFailedPrecondition,
"Base dir not created");
}
celestial_bodies_[parent_path].insert(split_path[2]);
celestial_bodies_.insert(
std::pair<string, std::set<string>>(parsed_path, {}));
return absl::OkStatus();
}
return Status(absl::StatusCode::kFailedPrecondition, "Failed to create");
}
Status IsDirectory(const string& dirname, TransactionToken* token) override {
string parsed_path;
ParsePath(dirname, &parsed_path);
if (parsed_path == "evil_directory") {
LOG(FATAL) << "evil_directory cannot be accessed";
}
std::vector<string> split_path = str_util::Split(parsed_path, '/');
if (split_path.size() > 2) {
return Status(absl::StatusCode::kFailedPrecondition, "Not a dir");
}
if (celestial_bodies_.find(parsed_path) != celestial_bodies_.end()) {
return absl::OkStatus();
}
return Status(absl::StatusCode::kFailedPrecondition, "Not a dir");
}
Status GetChildren(const string& dir, TransactionToken* token,
std::vector<string>* result) override {
TF_RETURN_IF_ERROR(IsDirectory(dir, nullptr));
string parsed_path;
ParsePath(dir, &parsed_path);
result->insert(result->begin(), celestial_bodies_[parsed_path].begin(),
celestial_bodies_[parsed_path].end());
return absl::OkStatus();
}
private:
bool BodyExists(const string& name) {
return celestial_bodies_.find(name) != celestial_bodies_.end();
}
void ParsePath(const string& name, string* parsed_path) {
StringPiece scheme, host, path;
this->ParseURI(name, &scheme, &host, &path);
ASSERT_EQ(scheme, "ipfs");
ASSERT_EQ(host, "solarsystem");
absl::ConsumePrefix(&path, "/");
*parsed_path = string(path);
}
std::map<string, std::set<string>> celestial_bodies_ = {
std::pair<string, std::set<string>>(
"", {"Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn",
"Uranus", "Neptune"}),
std::pair<string, std::set<string>>("Mercury", {}),
std::pair<string, std::set<string>>("Venus", {}),
std::pair<string, std::set<string>>("Earth", {"Moon"}),
std::pair<string, std::set<string>>("Mars", {}),
std::pair<string, std::set<string>>("Jupiter",
{"Europa", "Io", "Ganymede"}),
std::pair<string, std::set<string>>("Saturn", {}),
std::pair<string, std::set<string>>("Uranus", {}),
std::pair<string, std::set<string>>("Neptune", {}),
std::pair<string, std::set<string>>("Earth/Moon", {}),
std::pair<string, std::set<string>>("Jupiter/Europa", {}),
std::pair<string, std::set<string>>("Jupiter/Io", {}),
std::pair<string, std::set<string>>("Jupiter/Ganymede", {})};
};
string Match(InterPlanetaryFileSystem* ipfs, const string& suffix_pattern) {
std::vector<string> results;
Status s = ipfs->GetMatchingPaths(ipfs->JoinPath(kPrefix, suffix_pattern),
nullptr, &results);
if (!s.ok()) {
return s.ToString();
} else {
std::vector<StringPiece> trimmed_results;
std::sort(results.begin(), results.end());
for (const string& result : results) {
StringPiece trimmed_result(result);
EXPECT_TRUE(
absl::ConsumePrefix(&trimmed_result, strings::StrCat(kPrefix, "/")));
trimmed_results.push_back(trimmed_result);
}
return absl::StrJoin(trimmed_results, ",");
}
}
TEST(InterPlanetaryFileSystemTest, IPFSMatch) {
InterPlanetaryFileSystem ipfs;
EXPECT_EQ(Match(&ipfs, "thereisnosuchfile"), "");
EXPECT_EQ(Match(&ipfs, "*"),
"Earth,Jupiter,Mars,Mercury,Neptune,Saturn,Uranus,Venus");
EXPECT_EQ(Match(&ipfs, "Jupiter*"),
"Earth/Moon,Jupiter/Europa,Jupiter/Ganymede,Jupiter/Io");
TF_EXPECT_OK(ipfs.CreateDir(ipfs.JoinPath(kPrefix, "Planet0"), nullptr));
TF_EXPECT_OK(ipfs.CreateDir(ipfs.JoinPath(kPrefix, "Planet1"), nullptr));
EXPECT_EQ(Match(&ipfs, "Planet[0-1]"), "Planet0,Planet1");
EXPECT_EQ(Match(&ipfs, "Planet?"), "Planet0,Planet1");
}
TEST(InterPlanetaryFileSystemTest, MatchSimple) {
InterPlanetaryFileSystem ipfs;
TF_EXPECT_OK(ipfs.CreateDir(ipfs.JoinPath(kPrefix, "match-00"), nullptr));
TF_EXPECT_OK(ipfs.CreateDir(ipfs.JoinPath(kPrefix, "match-0a"), nullptr));
TF_EXPECT_OK(ipfs.CreateDir(ipfs.JoinPath(kPrefix, "match-01"), nullptr));
TF_EXPECT_OK(ipfs.CreateDir(ipfs.JoinPath(kPrefix, "match-aaa"), nullptr));
EXPECT_EQ(Match(&ipfs, "match-*"), "match-00,match-01,match-0a,match-aaa");
EXPECT_EQ(Match(&ipfs, "match-0[0-9]"), "match-00,match-01");
EXPECT_EQ(Match(&ipfs, "match-?[0-9]"), "match-00,match-01");
EXPECT_EQ(Match(&ipfs, "match-?a*"), "match-0a,match-aaa");
EXPECT_EQ(Match(&ipfs, "match-??"), "match-00,match-01,match-0a");
}
TEST(InterPlanetaryFileSystemTest, MatchOnlyNeeded) {
InterPlanetaryFileSystem ipfs;
TF_EXPECT_OK(ipfs.CreateDir(ipfs.JoinPath(kPrefix, "abcd"), nullptr));
TF_EXPECT_OK(
ipfs.CreateDir(ipfs.JoinPath(kPrefix, "evil_directory"), nullptr));
EXPECT_EQ(Match(&ipfs, "abcd"), "abcd");
}
TEST(InterPlanetaryFileSystemTest, MatchDirectory) {
InterPlanetaryFileSystem ipfs;
TF_EXPECT_OK(ipfs.RecursivelyCreateDir(
ipfs.JoinPath(kPrefix, "match-00/abc/x"), nullptr));
TF_EXPECT_OK(ipfs.RecursivelyCreateDir(
ipfs.JoinPath(kPrefix, "match-0a/abc/x"), nullptr));
TF_EXPECT_OK(ipfs.RecursivelyCreateDir(
ipfs.JoinPath(kPrefix, "match-01/abc/x"), nullptr));
TF_EXPECT_OK(ipfs.RecursivelyCreateDir(
ipfs.JoinPath(kPrefix, "match-aaa/abc/x"), nullptr));
EXPECT_EQ(Match(&ipfs, "match-*/abc/x"),
"match-00/abc/x,match-01/abc/x,match-0a/abc/x,match-aaa/abc/x");
EXPECT_EQ(Match(&ipfs, "match-0[0-9]/abc/x"),
"match-00/abc/x,match-01/abc/x");
EXPECT_EQ(Match(&ipfs, "match-?[0-9]/abc/x"),
"match-00/abc/x,match-01/abc/x");
EXPECT_EQ(Match(&ipfs, "match-?a*/abc/x"), "match-0a/abc/x,match-aaa/abc/x");
EXPECT_EQ(Match(&ipfs, "match-?[^a]/abc/x"), "match-00/abc/x,match-01/abc/x");
}
TEST(InterPlanetaryFileSystemTest, MatchMultipleWildcards) {
InterPlanetaryFileSystem ipfs;
TF_EXPECT_OK(ipfs.RecursivelyCreateDir(
ipfs.JoinPath(kPrefix, "match-00/abc/00"), nullptr));
TF_EXPECT_OK(ipfs.RecursivelyCreateDir(
ipfs.JoinPath(kPrefix, "match-00/abc/01"), nullptr));
TF_EXPECT_OK(ipfs.RecursivelyCreateDir(
ipfs.JoinPath(kPrefix, "match-00/abc/09"), nullptr));
TF_EXPECT_OK(ipfs.RecursivelyCreateDir(
ipfs.JoinPath(kPrefix, "match-01/abc/00"), nullptr));
TF_EXPECT_OK(ipfs.RecursivelyCreateDir(
ipfs.JoinPath(kPrefix, "match-01/abc/04"), nullptr));
TF_EXPECT_OK(ipfs.RecursivelyCreateDir(
ipfs.JoinPath(kPrefix, "match-01/abc/10"), nullptr));
TF_EXPECT_OK(ipfs.RecursivelyCreateDir(
ipfs.JoinPath(kPrefix, "match-02/abc/00"), nullptr));
EXPECT_EQ(Match(&ipfs, "match-0[0-1]/abc/0[0-8]"),
"match-00/abc/00,match-00/abc/01,match-01/abc/00,match-01/abc/04");
}
TEST(InterPlanetaryFileSystemTest, RecursivelyCreateAlreadyExistingDir) {
InterPlanetaryFileSystem ipfs;
const string dirname = ipfs.JoinPath(kPrefix, "match-00/abc/00");
TF_EXPECT_OK(ipfs.RecursivelyCreateDir(dirname));
}
TEST(InterPlanetaryFileSystemTest, HasAtomicMove) {
InterPlanetaryFileSystem ipfs;
const string dirname = io::JoinPath(kPrefix, "match-00/abc/00");
bool has_atomic_move;
TF_EXPECT_OK(ipfs.HasAtomicMove(dirname, &has_atomic_move));
EXPECT_EQ(has_atomic_move, true);
}
TEST(InterPlanetaryFileSystemTest, CanCreateTempFile) {
InterPlanetaryFileSystem ipfs;
const string dirname = io::JoinPath(kPrefix, "match-00/abc/00");
bool can_create_temp_file;
TF_EXPECT_OK(ipfs.CanCreateTempFile(dirname, &can_create_temp_file));
EXPECT_EQ(can_create_temp_file, true);
}
class TestFileSystem : public NullFileSystem {
public:
Status IsDirectory(const string& dirname, TransactionToken* token) override {
if (dirname == "." || dirname.empty()) {
return absl::OkStatus();
}
return Status(absl::StatusCode::kFailedPrecondition, "Not a dir");
}
Status GetChildren(const string& dir, TransactionToken* token,
std::vector<string>* result) override {
if (dir == "." || dir.empty()) {
result->push_back("test");
}
return absl::OkStatus();
}
};
TEST(TestFileSystemTest, RootDirectory) {
TestFileSystem fs;
std::vector<string> results;
auto ret = fs.GetMatchingPaths("./te*", nullptr, &results);
EXPECT_EQ(1, results.size());
EXPECT_EQ("./test", results[0]);
ret = fs.GetMatchingPaths("te*", nullptr, &results);
EXPECT_EQ(1, results.size());
EXPECT_EQ("./test", results[0]);
}
} | 2,260 |
#ifndef TENSORFLOW_TSL_PLATFORM_RETRYING_UTILS_H_
#define TENSORFLOW_TSL_PLATFORM_RETRYING_UTILS_H_
#include <functional>
#include "absl/time/time.h"
#include "tsl/platform/status.h"
namespace tsl {
struct RetryConfig {
RetryConfig(int64_t init_delay_time_us = 100 * 1000,
int64_t max_delay_time_us = 32 * 1000 * 1000,
int max_retries = 10) {
this->init_delay_time_us = init_delay_time_us;
this->max_delay_time_us = max_delay_time_us;
this->max_retries = max_retries;
}
int max_retries;
int64_t init_delay_time_us;
int64_t max_delay_time_us;
};
class RetryingUtils {
public:
static absl::Status CallWithRetries(const std::function<absl::Status()>& f,
const RetryConfig& config);
static absl::Status CallWithRetries(
const std::function<absl::Status()>& f,
const std::function<void(int64_t)>& sleep_usec,
const RetryConfig& config);
static absl::Status DeleteWithRetries(
const std::function<absl::Status()>& delete_func,
const RetryConfig& config);
};
absl::Duration ComputeRetryBackoff(
int current_retry_attempt, absl::Duration min_delay = absl::Milliseconds(1),
absl::Duration max_delay = absl::Seconds(10));
}
#endif
#include "tsl/platform/retrying_utils.h"
#include <algorithm>
#include <cmath>
#include <cstdint>
#include <limits>
#include "absl/time/time.h"
#include "tsl/platform/env.h"
#include "tsl/platform/errors.h"
#include "tsl/platform/file_system.h"
#include "tsl/platform/logging.h"
#include "tsl/platform/random.h"
namespace tsl {
namespace {
bool IsRetriable(absl::StatusCode code) {
switch (code) {
case absl::StatusCode::kUnavailable:
case absl::StatusCode::kDeadlineExceeded:
case absl::StatusCode::kUnknown:
return true;
default:
return false;
}
}
double GenerateUniformRandomNumber() {
return random::New64() * (1.0 / std::numeric_limits<uint64_t>::max());
}
double GenerateUniformRandomNumberBetween(double a, double b) {
if (a == b) return a;
DCHECK_LT(a, b);
return a + GenerateUniformRandomNumber() * (b - a);
}
}
absl::Status RetryingUtils::CallWithRetries(
const std::function<absl::Status()>& f, const RetryConfig& config) {
return CallWithRetries(
f,
[](int64_t micros) {
return Env::Default()->SleepForMicroseconds(micros);
},
config);
}
absl::Status RetryingUtils::CallWithRetries(
const std::function<absl::Status()>& f,
const std::function<void(int64_t)>& sleep_usec, const RetryConfig& config) {
int retries = 0;
while (true) {
auto status = f();
if (!IsRetriable(status.code())) {
return status;
}
if (retries >= config.max_retries) {
return absl::Status(
absl::StatusCode::kAborted,
strings::StrCat(
"All ", config.max_retries,
" retry attempts failed. The last failure: ", status.message()));
}
int64_t delay_micros = 0;
if (config.init_delay_time_us > 0) {
const int64_t random_micros = random::New64() % 1000000;
delay_micros = std::min(config.init_delay_time_us << retries,
config.max_delay_time_us) +
random_micros;
}
VLOG(1) << "The operation failed and will be automatically retried in "
<< (delay_micros / 1000000.0) << " seconds (attempt "
<< (retries + 1) << " out of " << config.max_retries
<< "), caused by: " << status.ToString();
sleep_usec(delay_micros);
retries++;
}
}
absl::Status RetryingUtils::DeleteWithRetries(
const std::function<absl::Status()>& delete_func,
const RetryConfig& config) {
bool is_retried = false;
return RetryingUtils::CallWithRetries(
[delete_func, &is_retried]() {
const absl::Status status = delete_func();
if (is_retried && status.code() == error::NOT_FOUND) {
return absl::OkStatus();
}
is_retried = true;
return status;
},
config);
}
absl::Duration ComputeRetryBackoff(int current_retry_attempt,
absl::Duration min_delay,
absl::Duration max_delay) {
DCHECK_GE(current_retry_attempt, 0);
constexpr double kBackoffBase = 1.3;
constexpr double kBackoffRandMult = 0.4;
const absl::Duration first_term = min_delay * kBackoffRandMult;
absl::Duration uncapped_second_term =
min_delay * std::pow(kBackoffBase, current_retry_attempt);
absl::Duration second_term =
std::min(uncapped_second_term, max_delay - first_term);
second_term *=
GenerateUniformRandomNumberBetween(1.0 - kBackoffRandMult, 1.0);
return std::max(first_term + second_term, min_delay);
}
} | #include "tsl/platform/retrying_utils.h"
#include <cmath>
#include <fstream>
#include "absl/time/time.h"
#include "tsl/lib/core/status_test_util.h"
#include "tsl/platform/env.h"
#include "tsl/platform/errors.h"
#include "tsl/platform/str_util.h"
#include "tsl/platform/test.h"
namespace tsl {
namespace {
TEST(RetryingUtilsTest, CallWithRetries_RetryDelays) {
std::vector<double> requested_delays;
std::function<void(int64_t)> sleep = [&requested_delays](int64_t delay) {
requested_delays.emplace_back(delay / 1000000.0);
};
std::function<absl::Status()> f = []() {
return errors::Unavailable("Failed.");
};
const auto& status = RetryingUtils::CallWithRetries(
f, sleep, RetryConfig(500000 ));
EXPECT_TRUE(errors::IsAborted(status));
EXPECT_TRUE(absl::StrContains(
status.message(),
"All 10 retry attempts failed. The last failure: Failed."))
<< status;
EXPECT_EQ(10, requested_delays.size());
EXPECT_NEAR(0.5, requested_delays[0], 1.0);
EXPECT_NEAR(1.0, requested_delays[1], 1.0);
EXPECT_NEAR(2.0, requested_delays[2], 1.0);
EXPECT_NEAR(4.0, requested_delays[3], 1.0);
EXPECT_NEAR(8.0, requested_delays[4], 1.0);
EXPECT_NEAR(16.0, requested_delays[5], 1.0);
EXPECT_NEAR(32.0, requested_delays[6], 1.0);
EXPECT_NEAR(32.0, requested_delays[7], 1.0);
EXPECT_NEAR(32.0, requested_delays[8], 1.0);
EXPECT_NEAR(32.0, requested_delays[9], 1.0);
}
TEST(RetryingUtilsTest, CallWithRetries_NotFoundIsNotRetried) {
std::vector<absl::Status> results(
{errors::Unavailable("Failed."), errors::NotFound("Not found.")});
std::function<absl::Status()> f = [&results]() {
auto result = results[0];
results.erase(results.begin());
return result;
};
EXPECT_TRUE(errors::IsNotFound(RetryingUtils::CallWithRetries(
f, RetryConfig(0 ))));
}
TEST(RetryingUtilsTest, CallWithRetries_ImmediateSuccess) {
std::vector<absl::Status> results({absl::OkStatus()});
std::function<void(int64_t)> sleep = [](int64_t delay) {
ADD_FAILURE() << "Unexpected call to sleep.";
};
std::function<absl::Status()> f = [&results]() {
auto result = results[0];
results.erase(results.begin());
return result;
};
TF_EXPECT_OK(RetryingUtils::CallWithRetries(
f, sleep, RetryConfig(1L )));
}
TEST(RetryingUtilsTest, CallWithRetries_EventualSuccess) {
std::vector<absl::Status> results({errors::Unavailable("Failed."),
errors::Unavailable("Failed again."),
absl::OkStatus()});
std::function<absl::Status()> f = [&results]() {
auto result = results[0];
results.erase(results.begin());
return result;
};
TF_EXPECT_OK(RetryingUtils::CallWithRetries(
f, RetryConfig(0 )));
}
TEST(RetryingUtilsTest, DeleteWithRetries_ImmediateSuccess) {
std::vector<absl::Status> delete_results({absl::OkStatus()});
const auto delete_func = [&delete_results]() {
auto result = delete_results[0];
delete_results.erase(delete_results.begin());
return result;
};
TF_EXPECT_OK(RetryingUtils::DeleteWithRetries(
delete_func, RetryConfig(0 )));
}
TEST(RetryingUtilsTest, DeleteWithRetries_EventualSuccess) {
std::vector<absl::Status> delete_results(
{errors::Unavailable(""), absl::OkStatus()});
const auto delete_func = [&delete_results]() {
auto result = delete_results[0];
delete_results.erase(delete_results.begin());
return result;
};
TF_EXPECT_OK(RetryingUtils::DeleteWithRetries(
delete_func, RetryConfig(0 )));
}
TEST(RetryingUtilsTest, DeleteWithRetries_PermissionDeniedNotRetried) {
std::vector<absl::Status> delete_results(
{errors::Unavailable(""), errors::PermissionDenied("")});
const auto delete_func = [&delete_results]() {
auto result = delete_results[0];
delete_results.erase(delete_results.begin());
return result;
};
EXPECT_TRUE(errors::IsPermissionDenied(RetryingUtils::DeleteWithRetries(
delete_func, RetryConfig(0 ))));
}
TEST(RetryingUtilsTest, DeleteWithRetries_SuccessThroughFileNotFound) {
std::vector<absl::Status> delete_results(
{errors::Unavailable(""), errors::NotFound("")});
const auto delete_func = [&delete_results]() {
auto result = delete_results[0];
delete_results.erase(delete_results.begin());
return result;
};
TF_EXPECT_OK(RetryingUtils::DeleteWithRetries(
delete_func, RetryConfig(0 )));
}
TEST(RetryingUtilsTest, DeleteWithRetries_FirstNotFoundReturnedAsIs) {
std::vector<absl::Status> delete_results({errors::NotFound("")});
const auto delete_func = [&delete_results]() {
auto result = delete_results[0];
delete_results.erase(delete_results.begin());
return result;
};
EXPECT_EQ(error::NOT_FOUND,
RetryingUtils::DeleteWithRetries(
delete_func, RetryConfig(0 ))
.code());
}
TEST(RetryingUtilsTest, ComputeRetryBackoff) {
for (int i = 0; i < 30; ++i) {
EXPECT_LE(0.4 * absl::Milliseconds(1) +
0.6 * absl::Milliseconds(1) * std::pow(1.3, i),
ComputeRetryBackoff(i));
EXPECT_LE(
ComputeRetryBackoff(i),
0.4 * absl::Milliseconds(1) + absl::Milliseconds(1) * std::pow(1.3, i));
}
}
TEST(RetryingUtilsTest, ComputeRetryBackoff_MinMaxDelays) {
for (int i = 0; i < 30; ++i) {
EXPECT_EQ(ComputeRetryBackoff(i,
absl::Seconds(10)),
absl::Seconds(10));
EXPECT_EQ(ComputeRetryBackoff(i,
absl::Microseconds(1),
absl::Microseconds(1)),
absl::Microseconds(1));
}
}
}
} | 2,261 |
#ifndef TENSORFLOW_TSL_PLATFORM_STATUS_MATCHERS_H_
#define TENSORFLOW_TSL_PLATFORM_STATUS_MATCHERS_H_
#include <ostream>
#include <string>
#include <utility>
#include "tsl/platform/status.h"
#include "tsl/platform/statusor.h"
#include "tsl/platform/test.h"
#include "tsl/protobuf/error_codes.pb.h"
namespace tsl {
inline void PrintTo(const tsl::error::Code code, std::ostream* os) {
*os << Code_Name(code);
}
template <typename T>
void PrintTo(const StatusOr<T>& status_or, std::ostream* os) {
*os << ::testing::PrintToString(status_or.status());
if (status_or.ok()) {
*os << ": " << ::testing::PrintToString(status_or.value());
}
}
namespace testing {
namespace internal_status {
inline const absl::Status& GetStatus(const absl::Status& status) {
return status;
}
template <typename T>
inline const absl::Status& GetStatus(const StatusOr<T>& status) {
return status.status();
}
template <typename StatusOrType>
class IsOkAndHoldsMatcherImpl
: public ::testing::MatcherInterface<StatusOrType> {
public:
typedef
typename std::remove_reference<StatusOrType>::type::value_type value_type;
template <typename InnerMatcher>
explicit IsOkAndHoldsMatcherImpl(InnerMatcher&& inner_matcher)
: inner_matcher_(::testing::SafeMatcherCast<const value_type&>(
std::forward<InnerMatcher>(inner_matcher))) {}
void DescribeTo(std::ostream* os) const override {
*os << "is OK and has a value that ";
inner_matcher_.DescribeTo(os);
}
void DescribeNegationTo(std::ostream* os) const override {
*os << "isn't OK or has a value that ";
inner_matcher_.DescribeNegationTo(os);
}
bool MatchAndExplain(
StatusOrType actual_value,
::testing::MatchResultListener* result_listener) const override {
if (!actual_value.ok()) {
*result_listener << "which has status " << actual_value.status();
return false;
}
::testing::StringMatchResultListener inner_listener;
const bool matches =
inner_matcher_.MatchAndExplain(*actual_value, &inner_listener);
const std::string inner_explanation = inner_listener.str();
if (!inner_explanation.empty()) {
*result_listener << "which contains value "
<< ::testing::PrintToString(*actual_value) << ", "
<< inner_explanation;
}
return matches;
}
private:
const ::testing::Matcher<const value_type&> inner_matcher_;
};
template <typename InnerMatcher>
class IsOkAndHoldsMatcher {
public:
explicit IsOkAndHoldsMatcher(InnerMatcher inner_matcher)
: inner_matcher_(std::move(inner_matcher)) {}
template <typename StatusOrType>
operator ::testing::Matcher<StatusOrType>() const {
return ::testing::Matcher<StatusOrType>(
new IsOkAndHoldsMatcherImpl<const StatusOrType&>(inner_matcher_));
}
private:
const InnerMatcher inner_matcher_;
};
class StatusIsMatcherCommonImpl {
public:
StatusIsMatcherCommonImpl(
::testing::Matcher<const absl::StatusCode> code_matcher,
::testing::Matcher<const std::string&> message_matcher)
: code_matcher_(std::move(code_matcher)),
message_matcher_(std::move(message_matcher)) {}
void DescribeTo(std::ostream* os) const;
void DescribeNegationTo(std::ostream* os) const;
bool MatchAndExplain(const absl::Status& status,
::testing::MatchResultListener* result_listener) const;
private:
const ::testing::Matcher<const absl::StatusCode> code_matcher_;
const ::testing::Matcher<const std::string&> message_matcher_;
};
template <typename T>
class MonoStatusIsMatcherImpl : public ::testing::MatcherInterface<T> {
public:
explicit MonoStatusIsMatcherImpl(StatusIsMatcherCommonImpl common_impl)
: common_impl_(std::move(common_impl)) {}
void DescribeTo(std::ostream* os) const override {
common_impl_.DescribeTo(os);
}
void DescribeNegationTo(std::ostream* os) const override {
common_impl_.DescribeNegationTo(os);
}
bool MatchAndExplain(
T actual_value,
::testing::MatchResultListener* result_listener) const override {
return common_impl_.MatchAndExplain(GetStatus(actual_value),
result_listener);
}
private:
StatusIsMatcherCommonImpl common_impl_;
};
class StatusIsMatcher {
public:
StatusIsMatcher(::testing::Matcher<const absl::StatusCode> code_matcher,
::testing::Matcher<const std::string&> message_matcher)
: common_impl_(
::testing::MatcherCast<const absl::StatusCode>(code_matcher),
::testing::MatcherCast<const std::string&>(message_matcher)) {}
template <typename T>
operator ::testing::Matcher<T>() const {
return ::testing::MakeMatcher(new MonoStatusIsMatcherImpl<T>(common_impl_));
}
private:
const StatusIsMatcherCommonImpl common_impl_;
};
template <typename T>
class MonoIsOkMatcherImpl : public ::testing::MatcherInterface<T> {
public:
void DescribeTo(std::ostream* os) const override { *os << "is OK"; }
void DescribeNegationTo(std::ostream* os) const override {
*os << "is not OK";
}
bool MatchAndExplain(T actual_value,
::testing::MatchResultListener*) const override {
return GetStatus(actual_value).ok();
}
};
class IsOkMatcher {
public:
template <typename T>
operator ::testing::Matcher<T>() const {
return ::testing::Matcher<T>(new MonoIsOkMatcherImpl<const T&>());
}
};
}
template <typename InnerMatcher>
internal_status::IsOkAndHoldsMatcher<typename std::decay<InnerMatcher>::type>
IsOkAndHolds(InnerMatcher&& inner_matcher) {
return internal_status::IsOkAndHoldsMatcher<
typename std::decay<InnerMatcher>::type>(
std::forward<InnerMatcher>(inner_matcher));
}
template <typename CodeMatcher, typename MessageMatcher>
internal_status::StatusIsMatcher StatusIs(CodeMatcher code_matcher,
MessageMatcher message_matcher) {
return internal_status::StatusIsMatcher(std::move(code_matcher),
std::move(message_matcher));
}
template <typename MessageMatcher>
internal_status::StatusIsMatcher StatusIs(tensorflow::error::Code code_matcher,
MessageMatcher message_matcher) {
return internal_status::StatusIsMatcher(
static_cast<absl::StatusCode>(code_matcher), std::move(message_matcher));
}
template <typename CodeMatcher>
internal_status::StatusIsMatcher StatusIs(CodeMatcher code_matcher) {
return StatusIs(std::move(code_matcher), ::testing::_);
}
template <>
inline internal_status::StatusIsMatcher StatusIs(
tensorflow::error::Code code_matcher) {
return StatusIs(static_cast<absl::StatusCode>(code_matcher), ::testing::_);
}
inline internal_status::IsOkMatcher IsOk() {
return internal_status::IsOkMatcher();
}
}
}
#endif
#include "tsl/platform/status_matchers.h"
#include <ostream>
#include <string>
#include "tsl/platform/status.h"
#include "tsl/platform/test.h"
#include "tsl/protobuf/error_codes.pb.h"
namespace tsl {
namespace testing {
namespace internal_status {
void StatusIsMatcherCommonImpl::DescribeTo(std::ostream* os) const {
*os << "has a status code that ";
code_matcher_.DescribeTo(os);
*os << ", and has an error message that ";
message_matcher_.DescribeTo(os);
}
void StatusIsMatcherCommonImpl::DescribeNegationTo(std::ostream* os) const {
*os << "has a status code that ";
code_matcher_.DescribeNegationTo(os);
*os << ", or has an error message that ";
message_matcher_.DescribeNegationTo(os);
}
bool StatusIsMatcherCommonImpl::MatchAndExplain(
const absl::Status& status,
::testing::MatchResultListener* result_listener) const {
::testing::StringMatchResultListener inner_listener;
inner_listener.Clear();
if (!code_matcher_.MatchAndExplain(
static_cast<absl::StatusCode>(status.code()), &inner_listener)) {
*result_listener << (inner_listener.str().empty()
? "whose status code is wrong"
: "which has a status code " +
inner_listener.str());
return false;
}
if (!message_matcher_.Matches(std::string(status.message()))) {
*result_listener << "whose error message is wrong";
return false;
}
return true;
}
}
}
} | #include "tsl/platform/status_matchers.h"
#include <sstream>
#include <string>
#include <vector>
#include "tsl/platform/errors.h"
#include "tsl/platform/status.h"
#include "tsl/platform/statusor.h"
#include "tsl/platform/test.h"
#include "tsl/protobuf/error_codes.pb.h"
namespace tsl {
namespace testing {
namespace {
using ::testing::_;
using ::testing::ElementsAre;
using ::testing::HasSubstr;
using ::testing::Matcher;
using ::testing::MatchesRegex;
using ::testing::Ne;
using ::testing::Not;
using ::testing::PrintToString;
MATCHER_P(LessThan, upper, "") {
if (arg < upper) {
*result_listener << "which is " << (upper - arg) << " less than " << upper;
return true;
}
*result_listener << "which is " << (arg - upper) << " more than " << upper;
return false;
}
template <typename T>
std::string Describe(const Matcher<T>& matcher) {
std::stringstream ss;
matcher.DescribeTo(&ss);
return ss.str();
}
template <typename T>
std::string DescribeNegation(const Matcher<T>& matcher) {
std::stringstream ss;
matcher.DescribeNegationTo(&ss);
return ss.str();
}
template <typename T, typename V>
std::string ExplainMatch(const Matcher<T>& matcher, const V& value) {
::testing::StringMatchResultListener listener;
matcher.MatchAndExplain(value, &listener);
return listener.str();
}
TEST(IsOkAndHoldsTest, MatchesValue) {
absl::StatusOr<std::string> status_or_message("Hello, world");
EXPECT_THAT(status_or_message, IsOkAndHolds("Hello, world"));
EXPECT_THAT(status_or_message, IsOkAndHolds(HasSubstr("Hello,")));
}
TEST(IsOkAndHoldsTest, MatchesContainer) {
absl::StatusOr<std::vector<std::string>> status_or_messages =
std::vector<std::string>{"Hello, world", "Hello, tf"};
EXPECT_THAT(status_or_messages,
IsOkAndHolds(ElementsAre("Hello, world", "Hello, tf")));
EXPECT_THAT(status_or_messages,
IsOkAndHolds(ElementsAre(HasSubstr("world"), HasSubstr("tf"))));
}
TEST(IsOkAndHoldsTest, DoesNotMatchStatus) {
absl::StatusOr<std::string> status_or_message =
errors::InvalidArgument("Invalid argument");
EXPECT_THAT(status_or_message, Not(IsOkAndHolds("Hello, world")));
}
TEST(IsOkAndHoldsTest, DoesNotMatchValue) {
absl::StatusOr<std::string> status_or_message("Hello, tf");
EXPECT_THAT(status_or_message, Not(IsOkAndHolds("Hello, world")));
}
TEST(IsOkAndHoldsTest, DoesNotMatchContainer) {
absl::StatusOr<std::vector<int>> status_or_container({1, 2, 3});
EXPECT_THAT(status_or_container, Not(IsOkAndHolds(ElementsAre(4, 5, 6))));
}
TEST(IsOkAndHoldsTest, DescribeExpectedValue) {
Matcher<absl::StatusOr<std::string>> is_ok_and_has_substr =
IsOkAndHolds(HasSubstr("Hello"));
EXPECT_EQ(Describe(is_ok_and_has_substr),
"is OK and has a value that has substring \"Hello\"");
EXPECT_EQ(DescribeNegation(is_ok_and_has_substr),
"isn't OK or has a value that has no substring \"Hello\"");
}
TEST(IsOkAndHoldsTest, ExplainNotMatchingStatus) {
Matcher<absl::StatusOr<int>> is_ok_and_less_than =
IsOkAndHolds(LessThan(100));
absl::StatusOr<int> status = errors::Unknown("Unknown");
EXPECT_THAT(ExplainMatch(is_ok_and_less_than, status),
HasSubstr("which has status UNKNOWN: Unknown"));
}
TEST(IsOkAndHoldsTest, ExplainNotMatchingValue) {
Matcher<absl::StatusOr<int>> is_ok_and_less_than =
IsOkAndHolds(LessThan(100));
EXPECT_EQ(ExplainMatch(is_ok_and_less_than, 120),
"which contains value 120, which is 20 more than 100");
}
TEST(IsOkAndHoldsTest, ExplainNotMatchingContainer) {
Matcher<absl::StatusOr<std::vector<int>>> is_ok_and_less_than =
IsOkAndHolds(ElementsAre(1, 2, 3));
std::vector<int> actual{4, 5, 6};
EXPECT_THAT(ExplainMatch(is_ok_and_less_than, actual),
HasSubstr("which contains value " + PrintToString(actual)));
}
TEST(StatusIsTest, MatchesOK) {
EXPECT_THAT(absl::OkStatus(), StatusIs(error::OK));
absl::StatusOr<std::string> message("Hello, world");
EXPECT_THAT(message, StatusIs(error::OK));
}
TEST(StatusIsTest, DoesNotMatchOk) {
EXPECT_THAT(errors::DeadlineExceeded("Deadline exceeded"),
Not(StatusIs(error::OK)));
absl::StatusOr<std::string> status = errors::NotFound("Not found");
EXPECT_THAT(status, Not(StatusIs(error::OK)));
}
TEST(StatusIsTest, MatchesStatus) {
absl::Status s = errors::Cancelled("Cancelled");
EXPECT_THAT(s, StatusIs(error::CANCELLED));
EXPECT_THAT(s, StatusIs(error::CANCELLED, "Cancelled"));
EXPECT_THAT(s, StatusIs(_, "Cancelled"));
EXPECT_THAT(s, StatusIs(error::CANCELLED, _));
EXPECT_THAT(s, StatusIs(Ne(error::INVALID_ARGUMENT), _));
EXPECT_THAT(s, StatusIs(error::CANCELLED, HasSubstr("Can")));
EXPECT_THAT(s, StatusIs(error::CANCELLED, MatchesRegex("Can.*")));
}
TEST(StatusIsTest, StatusOrMatchesStatus) {
absl::StatusOr<int> s = errors::InvalidArgument("Invalid Argument");
EXPECT_THAT(s, StatusIs(error::INVALID_ARGUMENT));
EXPECT_THAT(s, StatusIs(error::INVALID_ARGUMENT, "Invalid Argument"));
EXPECT_THAT(s, StatusIs(_, "Invalid Argument"));
EXPECT_THAT(s, StatusIs(error::INVALID_ARGUMENT, _));
EXPECT_THAT(s, StatusIs(Ne(error::CANCELLED), _));
EXPECT_THAT(s, StatusIs(error::INVALID_ARGUMENT, HasSubstr("Argument")));
EXPECT_THAT(s, StatusIs(error::INVALID_ARGUMENT, MatchesRegex(".*Argument")));
}
TEST(StatusIsTest, DoesNotMatchStatus) {
absl::Status s = errors::Internal("Internal");
EXPECT_THAT(s, Not(StatusIs(error::FAILED_PRECONDITION)));
EXPECT_THAT(s, Not(StatusIs(error::INTERNAL, "Failed Precondition")));
EXPECT_THAT(s, Not(StatusIs(_, "Failed Precondition")));
EXPECT_THAT(s, Not(StatusIs(error::FAILED_PRECONDITION, _)));
}
TEST(StatusIsTest, StatusOrDoesNotMatchStatus) {
absl::StatusOr<int> s = errors::FailedPrecondition("Failed Precondition");
EXPECT_THAT(s, Not(StatusIs(error::INTERNAL)));
EXPECT_THAT(s, Not(StatusIs(error::FAILED_PRECONDITION, "Internal")));
EXPECT_THAT(s, Not(StatusIs(_, "Internal")));
EXPECT_THAT(s, Not(StatusIs(error::INTERNAL, _)));
}
TEST(StatusIsTest, DescribeExpectedValue) {
Matcher<absl::Status> status_is =
StatusIs(error::UNAVAILABLE, std::string("Unavailable"));
EXPECT_EQ(Describe(status_is),
"has a status code that is equal to UNAVAILABLE, "
"and has an error message that is equal to \"Unavailable\"");
}
TEST(StatusIsTest, DescribeNegatedExpectedValue) {
Matcher<absl::StatusOr<std::string>> status_is =
StatusIs(error::ABORTED, std::string("Aborted"));
EXPECT_EQ(DescribeNegation(status_is),
"has a status code that isn't equal to ABORTED, "
"or has an error message that isn't equal to \"Aborted\"");
}
TEST(StatusIsTest, ExplainNotMatchingErrorCode) {
Matcher<absl::Status> status_is = StatusIs(error::NOT_FOUND, _);
const absl::Status status = errors::AlreadyExists("Already exists");
EXPECT_EQ(ExplainMatch(status_is, status), "whose status code is wrong");
}
TEST(StatusIsTest, ExplainNotMatchingErrorMessage) {
Matcher<absl::Status> status_is = StatusIs(error::NOT_FOUND, "Not found");
const absl::Status status = errors::NotFound("Already exists");
EXPECT_EQ(ExplainMatch(status_is, status), "whose error message is wrong");
}
TEST(StatusIsTest, ExplainStatusOrNotMatchingErrorCode) {
Matcher<absl::StatusOr<int>> status_is = StatusIs(error::ALREADY_EXISTS, _);
const absl::StatusOr<int> status_or = errors::NotFound("Not found");
EXPECT_EQ(ExplainMatch(status_is, status_or), "whose status code is wrong");
}
TEST(StatusIsTest, ExplainStatusOrNotMatchingErrorMessage) {
Matcher<absl::StatusOr<int>> status_is =
StatusIs(error::ALREADY_EXISTS, "Already exists");
const absl::StatusOr<int> status_or = errors::AlreadyExists("Not found");
EXPECT_EQ(ExplainMatch(status_is, status_or), "whose error message is wrong");
}
TEST(StatusIsTest, ExplainStatusOrHasValue) {
Matcher<absl::StatusOr<int>> status_is =
StatusIs(error::RESOURCE_EXHAUSTED, "Resource exhausted");
const absl::StatusOr<int> value = -1;
EXPECT_EQ(ExplainMatch(status_is, value), "whose status code is wrong");
}
TEST(IsOkTest, MatchesOK) {
EXPECT_THAT(absl::OkStatus(), IsOk());
absl::StatusOr<std::string> message = std::string("Hello, world");
EXPECT_THAT(message, IsOk());
}
TEST(IsOkTest, DoesNotMatchOK) {
EXPECT_THAT(errors::PermissionDenied("Permission denied"), Not(IsOk()));
absl::StatusOr<std::string> status =
errors::Unauthenticated("Unauthenticated");
EXPECT_THAT(status, Not(IsOk()));
}
TEST(IsOkTest, DescribeExpectedValue) {
Matcher<absl::Status> status_is_ok = IsOk();
EXPECT_EQ(Describe(status_is_ok), "is OK");
Matcher<absl::StatusOr<std::string>> status_or_is_ok = IsOk();
EXPECT_EQ(Describe(status_or_is_ok), "is OK");
}
TEST(IsOkTest, DescribeNegatedExpectedValue) {
Matcher<absl::Status> status_is_ok = IsOk();
EXPECT_EQ(DescribeNegation(status_is_ok), "is not OK");
Matcher<absl::StatusOr<std::string>> status_or_is_ok = IsOk();
EXPECT_EQ(DescribeNegation(status_or_is_ok), "is not OK");
}
}
}
} | 2,262 |
#ifndef TENSORFLOW_TSL_PLATFORM_DENORMAL_H_
#define TENSORFLOW_TSL_PLATFORM_DENORMAL_H_
#include "tsl/platform/macros.h"
namespace tsl {
namespace port {
class DenormalState {
public:
DenormalState(bool flush_to_zero, bool denormals_are_zero)
: flush_to_zero_(flush_to_zero),
denormals_are_zero_(denormals_are_zero) {}
inline bool flush_to_zero() const { return flush_to_zero_; }
inline bool denormals_are_zero() const { return denormals_are_zero_; }
bool operator==(const DenormalState& other) const;
bool operator!=(const DenormalState& other) const;
private:
bool flush_to_zero_;
bool denormals_are_zero_;
};
DenormalState GetDenormalState();
bool SetDenormalState(const DenormalState& state);
class ScopedRestoreFlushDenormalState {
public:
ScopedRestoreFlushDenormalState();
~ScopedRestoreFlushDenormalState();
private:
DenormalState denormal_state_;
ScopedRestoreFlushDenormalState(const ScopedRestoreFlushDenormalState&) =
delete;
void operator=(const ScopedRestoreFlushDenormalState&) = delete;
};
class ScopedFlushDenormal {
public:
ScopedFlushDenormal();
private:
ScopedRestoreFlushDenormalState restore_;
ScopedFlushDenormal(const ScopedFlushDenormal&) = delete;
void operator=(const ScopedFlushDenormal&) = delete;
};
class ScopedDontFlushDenormal {
public:
ScopedDontFlushDenormal();
private:
ScopedRestoreFlushDenormalState restore_;
ScopedDontFlushDenormal(const ScopedDontFlushDenormal&) = delete;
void operator=(const ScopedDontFlushDenormal&) = delete;
};
}
}
#endif
#include "tsl/platform/denormal.h"
#include <cstdint>
#include "tsl/platform/cpu_info.h"
#include "tsl/platform/platform.h"
#if !defined(__SSE3__) && !defined(__clang__) && \
(defined(__GNUC__) && (__GNUC__ < 4) || \
((__GNUC__ == 4) && (__GNUC_MINOR__ < 9)))
#define GCC_WITHOUT_INTRINSICS
#endif
#if defined(PLATFORM_IS_X86) && !defined(IS_MOBILE_PLATFORM) && \
!defined(GCC_WITHOUT_INTRINSICS)
#define X86_DENORM_USE_INTRINSICS
#endif
#ifdef X86_DENORM_USE_INTRINSICS
#include <pmmintrin.h>
#endif
#if defined(PLATFORM_IS_ARM) && defined(__ARM_FP) && (__ARM_FP > 0)
#define ARM_DENORM_AVAILABLE
#define ARM_FPCR_FZ (1 << 24)
#endif
namespace tsl {
namespace port {
bool DenormalState::operator==(const DenormalState& other) const {
return flush_to_zero() == other.flush_to_zero() &&
denormals_are_zero() == other.denormals_are_zero();
}
bool DenormalState::operator!=(const DenormalState& other) const {
return !(this->operator==(other));
}
#ifdef ARM_DENORM_AVAILABLE
static inline void ArmSetFloatingPointControlRegister(uint32_t fpcr) {
#ifdef PLATFORM_IS_ARM64
__asm__ __volatile__("msr fpcr, %[fpcr]"
:
: [fpcr] "r"(static_cast<uint64_t>(fpcr)));
#else
__asm__ __volatile__("vmsr fpscr, %[fpcr]" : : [fpcr] "r"(fpcr));
#endif
}
static inline uint32_t ArmGetFloatingPointControlRegister() {
uint32_t fpcr;
#ifdef PLATFORM_IS_ARM64
uint64_t fpcr64;
__asm__ __volatile__("mrs %[fpcr], fpcr" : [fpcr] "=r"(fpcr64));
fpcr = static_cast<uint32_t>(fpcr64);
#else
__asm__ __volatile__("vmrs %[fpcr], fpscr" : [fpcr] "=r"(fpcr));
#endif
return fpcr;
}
#endif
bool SetDenormalState(const DenormalState& state) {
#ifdef X86_DENORM_USE_INTRINSICS
if (TestCPUFeature(SSE3)) {
_MM_SET_FLUSH_ZERO_MODE(state.flush_to_zero() ? _MM_FLUSH_ZERO_ON
: _MM_FLUSH_ZERO_OFF);
_MM_SET_DENORMALS_ZERO_MODE(state.denormals_are_zero()
? _MM_DENORMALS_ZERO_ON
: _MM_DENORMALS_ZERO_OFF);
return true;
}
#endif
#ifdef ARM_DENORM_AVAILABLE
if (state.flush_to_zero() == state.denormals_are_zero()) {
uint32_t fpcr = ArmGetFloatingPointControlRegister();
if (state.flush_to_zero()) {
fpcr |= ARM_FPCR_FZ;
} else {
fpcr &= ~ARM_FPCR_FZ;
}
ArmSetFloatingPointControlRegister(fpcr);
return true;
}
#endif
return false;
}
DenormalState GetDenormalState() {
#ifdef X86_DENORM_USE_INTRINSICS
if (TestCPUFeature(SSE3)) {
bool flush_zero_mode = _MM_GET_FLUSH_ZERO_MODE() == _MM_FLUSH_ZERO_ON;
bool denormals_zero_mode =
_MM_GET_DENORMALS_ZERO_MODE() == _MM_DENORMALS_ZERO_ON;
return DenormalState(flush_zero_mode, denormals_zero_mode);
}
#endif
#ifdef ARM_DENORM_AVAILABLE
uint32_t fpcr = ArmGetFloatingPointControlRegister();
if ((fpcr & ARM_FPCR_FZ) != 0) {
return DenormalState(true, true);
}
#endif
return DenormalState(false, false);
}
ScopedRestoreFlushDenormalState::ScopedRestoreFlushDenormalState()
: denormal_state_(GetDenormalState()) {}
ScopedRestoreFlushDenormalState::~ScopedRestoreFlushDenormalState() {
SetDenormalState(denormal_state_);
}
ScopedFlushDenormal::ScopedFlushDenormal() {
SetDenormalState(
DenormalState(true, true));
}
ScopedDontFlushDenormal::ScopedDontFlushDenormal() {
SetDenormalState(
DenormalState(false, false));
}
}
} | #include "tsl/platform/denormal.h"
#include <cstring>
#include <limits>
#include "tsl/platform/test.h"
namespace tsl {
namespace port {
TEST(DenormalStateTest, ConstructorAndAccessorsWork) {
const bool flush_to_zero[] = {true, true, false, false};
const bool denormals_are_zero[] = {true, false, true, false};
for (int i = 0; i < 4; ++i) {
const DenormalState state =
DenormalState(flush_to_zero[i], denormals_are_zero[i]);
EXPECT_EQ(state.flush_to_zero(), flush_to_zero[i]);
EXPECT_EQ(state.denormals_are_zero(), denormals_are_zero[i]);
}
}
uint32_t bits(float x) {
uint32_t out;
memcpy(&out, &x, sizeof(float));
return out;
}
void CheckDenormalHandling(const DenormalState& state) {
volatile float denormal_output = std::numeric_limits<float>::min();
denormal_output *= 0.25f;
if (state.flush_to_zero()) {
EXPECT_EQ(bits(denormal_output), 0x0);
} else {
EXPECT_NE(bits(denormal_output), 0x0);
}
volatile float normal_output = std::numeric_limits<float>::denorm_min();
normal_output *= std::numeric_limits<float>::max();
if (state.denormals_are_zero()) {
EXPECT_EQ(bits(normal_output), 0x0);
} else {
EXPECT_NE(bits(normal_output), 0x0);
}
}
TEST(DenormalTest, GetAndSetStateWorkWithCorrectFlushing) {
const DenormalState states[] = {
DenormalState(true, true),
DenormalState(true, false),
DenormalState(false, true),
DenormalState(false, false)};
for (const DenormalState& state : states) {
if (SetDenormalState(state)) {
EXPECT_EQ(GetDenormalState(), state);
CheckDenormalHandling(state);
}
}
}
TEST(ScopedRestoreFlushDenormalStateTest, RestoresState) {
const DenormalState flush_denormals(true,
true);
const DenormalState dont_flush_denormals(false,
false);
const bool can_set_denormal_state = SetDenormalState(flush_denormals) &&
SetDenormalState(dont_flush_denormals);
if (can_set_denormal_state) {
SetDenormalState(flush_denormals);
{
ScopedRestoreFlushDenormalState restore_state;
SetDenormalState(dont_flush_denormals);
EXPECT_EQ(GetDenormalState(), dont_flush_denormals);
}
EXPECT_EQ(GetDenormalState(), flush_denormals);
SetDenormalState(dont_flush_denormals);
{
ScopedRestoreFlushDenormalState restore_state;
SetDenormalState(flush_denormals);
EXPECT_EQ(GetDenormalState(), flush_denormals);
}
EXPECT_EQ(GetDenormalState(), dont_flush_denormals);
}
}
TEST(ScopedFlushDenormalTest, SetsFlushingAndRestoresState) {
const DenormalState flush_denormals(true,
true);
const DenormalState dont_flush_denormals(false,
false);
const bool can_set_denormal_state = SetDenormalState(flush_denormals) &&
SetDenormalState(dont_flush_denormals);
if (can_set_denormal_state) {
SetDenormalState(dont_flush_denormals);
{
ScopedFlushDenormal scoped_flush_denormal;
EXPECT_EQ(GetDenormalState(), flush_denormals);
}
EXPECT_EQ(GetDenormalState(), dont_flush_denormals);
}
}
TEST(ScopedDontFlushDenormalTest, SetsNoFlushingAndRestoresState) {
const DenormalState flush_denormals(true,
true);
const DenormalState dont_flush_denormals(false,
false);
const bool can_set_denormal_state = SetDenormalState(flush_denormals) &&
SetDenormalState(dont_flush_denormals);
if (can_set_denormal_state) {
SetDenormalState(flush_denormals);
{
ScopedDontFlushDenormal scoped_dont_flush_denormal;
EXPECT_EQ(GetDenormalState(), dont_flush_denormals);
}
EXPECT_EQ(GetDenormalState(), flush_denormals);
}
}
}
} | 2,263 |
#ifndef TENSORFLOW_TSL_PLATFORM_ERRORS_H_
#define TENSORFLOW_TSL_PLATFORM_ERRORS_H_
#include <sstream>
#include <string>
#include <type_traits>
#include <unordered_map>
#include <utility>
#include <vector>
#include "absl/base/attributes.h"
#include "absl/status/status.h"
#include "absl/strings/cord.h"
#include "absl/strings/str_join.h"
#include "tsl/platform/logging.h"
#include "tsl/platform/macros.h"
#include "tsl/platform/status.h"
#include "tsl/platform/str_util.h"
#include "tsl/platform/strcat.h"
namespace tsl {
namespace error {
using tensorflow::error::ABORTED;
using tensorflow::error::ALREADY_EXISTS;
using tensorflow::error::CANCELLED;
using tensorflow::error::Code;
using tensorflow::error::DATA_LOSS;
using tensorflow::error::DEADLINE_EXCEEDED;
using tensorflow::error::FAILED_PRECONDITION;
using tensorflow::error::INTERNAL;
using tensorflow::error::INVALID_ARGUMENT;
using tensorflow::error::NOT_FOUND;
using tensorflow::error::OK;
using tensorflow::error::OUT_OF_RANGE;
using tensorflow::error::PERMISSION_DENIED;
using tensorflow::error::RESOURCE_EXHAUSTED;
using tensorflow::error::UNAUTHENTICATED;
using tensorflow::error::UNAVAILABLE;
using tensorflow::error::UNIMPLEMENTED;
using tensorflow::error::UNKNOWN;
}
namespace errors {
namespace internal {
template <typename T>
typename std::enable_if<!std::is_convertible<T, strings::AlphaNum>::value,
std::string>::type
PrepareForStrCat(const T& t) {
std::stringstream ss;
ss << t;
return ss.str();
}
inline const strings::AlphaNum& PrepareForStrCat(const strings::AlphaNum& a) {
return a;
}
}
absl::Status IOError(const string& context, int err_number);
inline std::unordered_map<std::string, std::string> GetPayloads(
const absl::Status& status) {
std::unordered_map<std::string, std::string> payloads;
status.ForEachPayload(
[&payloads](::tsl::StringPiece key, const absl::Cord& value) {
payloads[std::string(key)] = std::string(value);
});
return payloads;
}
inline void InsertPayloads(
absl::Status& status,
const std::unordered_map<std::string, std::string>& payloads) {
for (const auto& payload : payloads) {
status.SetPayload(payload.first, absl::Cord(payload.second));
}
}
inline void CopyPayloads(const absl::Status& from, absl::Status& to) {
from.ForEachPayload([&to](::tsl::StringPiece key, const absl::Cord& value) {
to.SetPayload(key, value);
});
}
#if defined(PLATFORM_GOOGLE)
inline absl::Status Create(
absl::StatusCode code, ::tsl::StringPiece message,
const std::unordered_map<std::string, std::string>& payloads,
absl::SourceLocation loc = absl::SourceLocation::current()) {
absl::Status status(code, message, loc);
InsertPayloads(status, payloads);
return status;
}
inline absl::Status CreateWithUpdatedMessage(const absl::Status& status,
::tsl::StringPiece message) {
auto locations = status.GetSourceLocations();
auto initial_loc =
locations.empty() ? absl::SourceLocation::current() : locations[0];
absl::Status new_status = Create(static_cast<absl::StatusCode>(status.code()),
message, GetPayloads(status), initial_loc);
if (locations.size() > 1) {
for (auto loc : locations.subspan(1)) {
new_status.AddSourceLocation(loc);
}
}
return new_status;
}
#else
inline ::absl::Status Create(
absl::StatusCode code, ::tsl::StringPiece message,
const std::unordered_map<std::string, std::string>& payloads) {
Status status(code, message);
InsertPayloads(status, payloads);
return status;
}
inline ::tsl::Status CreateWithUpdatedMessage(const ::tsl::Status& status,
::tsl::StringPiece message) {
return Create(static_cast<absl::StatusCode>(status.code()), message,
GetPayloads(status));
}
#endif
template <typename... Args>
void AppendToMessage(absl::Status* status, Args... args) {
auto new_status = CreateWithUpdatedMessage(
*status, ::tsl::strings::StrCat(status->message(), "\n\t", args...));
CopyPayloads(*status, new_status);
*status = std::move(new_status);
}
#define TF_RETURN_IF_ERROR(...) \
do { \
::absl::Status _status = (__VA_ARGS__); \
if (TF_PREDICT_FALSE(!_status.ok())) { \
MAYBE_ADD_SOURCE_LOCATION(_status) \
return _status; \
} \
} while (0)
#define TF_RETURN_WITH_CONTEXT_IF_ERROR(expr, ...) \
do { \
::tsl::Status _status = (expr); \
if (TF_PREDICT_FALSE(!_status.ok())) { \
::tsl::errors::AppendToMessage(&_status, __VA_ARGS__); \
return _status; \
} \
} while (0)
template <typename... Args>
absl::Status Cancelled(Args... args) {
return absl::Status(absl::StatusCode::kCancelled,
::tsl::strings::StrCat(
::tsl::errors::internal::PrepareForStrCat(args)...));
}
template <typename... Args>
absl::Status CancelledWithPayloads(
const ::tsl::StringPiece& message,
const std::unordered_map<std::string, std::string>& payloads) {
return errors::Create(absl::StatusCode::kCancelled, message, payloads);
}
template <typename... Args>
absl::Status InvalidArgument(Args... args) {
return absl::Status(absl::StatusCode::kInvalidArgument,
::tsl::strings::StrCat(
::tsl::errors::internal::PrepareForStrCat(args)...));
}
#if defined(PLATFORM_GOOGLE)
template <typename Arg1, typename Arg2, typename Arg3, typename Arg4>
::absl::Status InvalidArgument(
Arg1 arg1, Arg2 arg2, Arg3 arg3, Arg4 arg4,
absl::SourceLocation loc = absl::SourceLocation::current()) {
return absl::Status(
absl::StatusCode::kInvalidArgument,
::tsl::strings::StrCat(::tsl::errors::internal::PrepareForStrCat(arg1),
::tsl::errors::internal::PrepareForStrCat(arg2),
::tsl::errors::internal::PrepareForStrCat(arg3),
::tsl::errors::internal::PrepareForStrCat(arg4)),
loc);
}
template <typename Arg1, typename Arg2, typename Arg3>
::absl::Status InvalidArgument(
Arg1 arg1, Arg2 arg2, Arg3 arg3,
absl::SourceLocation loc = absl::SourceLocation::current()) {
return absl::Status(
absl::StatusCode::kInvalidArgument,
::tsl::strings::StrCat(::tsl::errors::internal::PrepareForStrCat(arg1),
::tsl::errors::internal::PrepareForStrCat(arg2),
::tsl::errors::internal::PrepareForStrCat(arg3)),
loc);
}
template <typename Arg1, typename Arg2>
::absl::Status InvalidArgument(
Arg1 arg1, Arg2 arg2,
absl::SourceLocation loc = absl::SourceLocation::current()) {
return absl::Status(
absl::StatusCode::kInvalidArgument,
::tsl::strings::StrCat(::tsl::errors::internal::PrepareForStrCat(arg1),
::tsl::errors::internal::PrepareForStrCat(arg2)),
loc);
}
template <typename Arg1>
::absl::Status InvalidArgument(
Arg1 arg1, absl::SourceLocation loc = absl::SourceLocation::current()) {
return absl::Status(
absl::StatusCode::kInvalidArgument,
::tsl::strings::StrCat(::tsl::errors::internal::PrepareForStrCat(arg1)),
loc);
}
template <typename... Args>
::absl::Status InvalidArgumentWithPayloads(
const ::tsl::StringPiece& message,
const std::unordered_map<std::string, std::string>& payloads,
absl::SourceLocation loc = absl::SourceLocation::current()) {
return errors::Create(absl::StatusCode::kInvalidArgument, message, payloads,
loc);
}
#else
template <typename Arg1, typename Arg2, typename Arg3>
::absl::Status InvalidArgument(Arg1 arg1, Arg2 arg2, Arg3 arg3) {
return ::absl::Status(
absl::StatusCode::kInvalidArgument,
::tsl::strings::StrCat(::tsl::errors::internal::PrepareForStrCat(arg1),
::tsl::errors::internal::PrepareForStrCat(arg2),
::tsl::errors::internal::PrepareForStrCat(arg3)));
}
template <typename Arg1, typename Arg2>
::absl::Status InvalidArgument(Arg1 arg1, Arg2 arg2) {
return ::absl::Status(
absl::StatusCode::kInvalidArgument,
::tsl::strings::StrCat(::tsl::errors::internal::PrepareForStrCat(arg1),
::tsl::errors::internal::PrepareForStrCat(arg2)));
}
template <typename Arg1>
::absl::Status InvalidArgument(Arg1 arg1) {
return ::absl::Status(
absl::StatusCode::kInvalidArgument,
::tsl::strings::StrCat(::tsl::errors::internal::PrepareForStrCat(arg1)));
}
template <typename... Args>
::absl::Status InvalidArgumentWithPayloads(
const ::tsl::StringPiece& message,
const std::unordered_map<std::string, std::string>& payloads) {
return errors::Create(absl::StatusCode::kInvalidArgument, message, payloads);
}
#endif
template <typename... Args>
absl::Status NotFound(Args... args) {
return absl::Status(absl::StatusCode::kNotFound,
::tsl::strings::StrCat(
::tsl::errors::internal::PrepareForStrCat(args)...));
}
#if defined(PLATFORM_GOOGLE)
template <typename Arg1, typename Arg2, typename Arg3>
::absl::Status NotFound(
Arg1 arg1, Arg2 arg2, Arg3 arg3,
absl::SourceLocation loc = absl::SourceLocation::current()) {
return absl::Status(
absl::StatusCode::kNotFound,
::tsl::strings::StrCat(::tsl::errors::internal::PrepareForStrCat(arg1),
::tsl::errors::internal::PrepareForStrCat(arg2),
::tsl::errors::internal::PrepareForStrCat(arg3)),
loc);
}
template <typename Arg1, typename Arg2>
::absl::Status NotFound(
Arg1 arg1, Arg2 arg2,
absl::SourceLocation loc = absl::SourceLocation::current()) {
return absl::Status(
absl::StatusCode::kNotFound,
::tsl::strings::StrCat(::tsl::errors::internal::PrepareForStrCat(arg1),
::tsl::errors::internal::PrepareForStrCat(arg2)),
loc);
}
template <typename Arg1>
::absl::Status NotFound(
Arg1 arg1, absl::SourceLocation loc = absl::SourceLocation::current()) {
return absl::Status(
absl::StatusCode::kNotFound,
::tsl::strings::StrCat(::tsl::errors::internal::PrepareForStrCat(arg1)),
loc);
}
template <typename... Args>
::absl::Status NotFoundWithPayloads(
const ::tsl::StringPiece& message,
const std::unordered_map<std::string, std::string>& payloads,
absl::SourceLocation loc = absl::SourceLocation::current()) {
return errors::Create(absl::StatusCode::kNotFound, message, payloads, loc);
}
#else
template <typename Arg1, typename Arg2, typename Arg3>
::absl::Status NotFound(Arg1 arg1, Arg2 arg2, Arg3 arg3) {
return ::absl::Status(
absl::StatusCode::kNotFound,
::tsl::strings::StrCat(::tsl::errors::internal::PrepareForStrCat(arg1),
::tsl::errors::internal::PrepareForStrCat(arg2),
::tsl::errors::internal::PrepareForStrCat(arg3)));
}
template <typename Arg1, typename Arg2>
::absl::Status NotFound(Arg1 arg1, Arg2 arg2) {
return ::absl::Status(
absl::StatusCode::kNotFound,
::tsl::strings::StrCat(::tsl::errors::internal::PrepareForStrCat(arg1),
::tsl::errors::internal::PrepareForStrCat(arg2)));
}
template <typename Arg1>
::absl::Status NotFound(Arg1 arg1) {
return ::absl::Status(
absl::StatusCode::kNotFound,
::tsl::strings::StrCat(::tsl::errors::internal::PrepareForStrCat(arg1)));
}
template <typename... Args>
::absl::Status NotFoundWithPayloads(
const ::tsl::StringPiece& message,
const std::unordered_map<std::string, std::string>& payloads) {
return errors::Create(absl::StatusCode::kNotFound, message, payloads);
}
#endif
template <typename... Args>
absl::Status AlreadyExists(Args... args) {
return absl::Status(absl::StatusCode::kAlreadyExists,
::tsl::strings::StrCat(
::tsl::errors::internal::PrepareForStrCat(args)...));
}
template <typename... Args>
absl::Status AlreadyExistsWithPayloads(
const ::tsl::StringPiece& message,
const std::unordered_map<std::string, std::string>& payloads) {
return errors::Create(absl::StatusCode::kAlreadyExists, message, payloads);
}
template <typename... Args>
absl::Status ResourceExhausted(Args... args) {
return absl::Status(absl::StatusCode::kResourceExhausted,
::tsl::strings::StrCat(
::tsl::errors::internal::PrepareForStrCat(args)...));
}
template <typename... Args>
absl::Status ResourceExhaustedWithPayloads(
const ::tsl::StringPiece& message,
const std::unordered_map<std::string, std::string>& payloads) {
return errors::Create(absl::StatusCode::kResourceExhausted, message,
payloads);
}
template <typename... Args>
absl::Status Unavailable(Args... args) {
return absl::Status(absl::StatusCode::kUnavailable,
::tsl::strings::StrCat(
::tsl::errors::internal::PrepareForStrCat(args)...));
}
template <typename... Args>
absl::Status UnavailableWithPayloads(
const ::tsl::StringPiece& message,
const std::unordered_map<std::string, std::string>& payloads) {
return errors::Create(absl::StatusCode::kUnavailable, message, payloads);
}
template <typename... Args>
absl::Status FailedPrecondition(Args... args) {
return absl::Status(absl::StatusCode::kFailedPrecondition,
::tsl::strings::StrCat(
::tsl::errors::internal::PrepareForStrCat(args)...));
}
template <typename... Args>
absl::Status FailedPreconditionWithPayloads(
const ::tsl::StringPiece& message,
const std::unordered_map<std::string, std::string>& payloads) {
return errors::Create(absl::StatusCode::kFailedPrecondition, message,
payloads);
}
template <typename... Args>
absl::Status OutOfRange(Args... args) {
return absl::Status(absl::StatusCode::kOutOfRange,
::tsl::strings::StrCat(
::tsl::errors::internal::PrepareForStrCat(args)...));
}
template <typename... Args>
absl::Status OutOfRangeWithPayloads(
const ::tsl::StringPiece& message,
const std::unordered_map<std::string, std::string>& payloads) {
return errors::Create(absl::StatusCode::kOutOfRange, message, payloads);
}
template <typename... Args>
absl::Status Unimplemented(Args... args) {
return absl::Status(absl::StatusCode::kUnimplemented,
::tsl::strings::StrCat(
::tsl::errors::internal::PrepareForStrCat(args)...));
}
template <typename... Args>
absl::Status UnimplementedWithPayloads(
const ::tsl::StringPiece& message,
const std::unordered_map<std::string, std::string>& payloads) {
return errors::Create(absl::StatusCode::kUnimplemented, message, payloads);
}
template <typename... Args>
absl::Status Internal(Args... args) {
return absl::Status(absl::StatusCode::kInternal,
::tsl::strings::StrCat(
::tsl::errors::internal::PrepareForStrCat(args)...));
}
template <typename... Args>
absl::Status InternalWithPayloads(
const ::tsl::StringPiece& message,
const std::unordered_map<std::string, std::string>& payloads) {
return errors::Create(absl::StatusCode::kInternal, message, payloads);
}
template <typename... Args>
absl::Status Aborted(Args... args) {
return absl::Status(absl::StatusCode::kAborted,
::tsl::strings::StrCat(
::tsl::errors::internal::PrepareForStrCat(args)...));
}
template <typename... Args>
absl::Status AbortedWithPayloads(
const ::tsl::StringPiece& message,
const std::unordered_map<std::string, std::string>& payloads) {
return errors::Create(absl::StatusCode::kAborted, message, payloads);
}
template <typename... Args>
absl::Status DeadlineExceeded(Args... args) {
return absl::Status(absl::StatusCode::kDeadlineExceeded,
::tsl::strings::StrCat(
::tsl::errors::internal::PrepareForStrCat(args)...));
}
template <typename... Args>
absl::Status DeadlineExceededWithPayloads(
const ::tsl::StringPiece& message,
const std::unordered_map<std::string, std::string>& payloads) {
return errors::Create(absl::StatusCode::kDeadlineExceeded, message, payloads);
}
template <typename... Args>
absl::Status DataLoss(Args... args) {
return absl::Status(absl::StatusCode::kDataLoss,
::tsl::strings::StrCat(
::tsl::errors::internal::PrepareForStrCat(args)...));
}
template <typename... Args>
absl::Status DataLossWithPayloads(
const ::tsl::StringPiece& message,
const std::unordered_map<std::string, std::string>& payloads) {
return errors::Create(absl::StatusCode::kDataLoss, message, payloads);
}
template <typename... Args>
absl::Status Unknown(Args... args) {
return absl::Status(absl::StatusCode::kUnknown,
::tsl::strings::StrCat(
::tsl::errors::internal::PrepareForStrCat(args)...));
}
template <typename... Args>
absl::Status UnknownPayloads(
const ::tsl::StringPiece& message,
const std::unordered_map<std::string, std::string>& payloads) {
return errors::Create(absl::StatusCode::kUnknown, message, payloads);
}
template <typename... Args>
absl::Status PermissionDenied(Args... args) {
return absl::Status(absl::StatusCode::kPermissionDenied,
::tsl::strings::StrCat(
::tsl::errors::internal::PrepareForStrCat(args)...));
}
template <typename... Args>
absl::Status PermissionDeniedWithPayloads(
const ::tsl::StringPiece& message,
const std::unordered_map<std::string, std::string>& payloads) {
return errors::Create(absl::StatusCode::kPermissionDenied, message, payloads);
}
template <typename... Args>
absl::Status Unauthenticated(Args... args) {
return absl::Status(absl::StatusCode::kUnauthenticated,
::tsl::strings::StrCat(
::tsl::errors::internal::PrepareForStrCat(args)...));
}
template <typename... Args>
absl::Status UnauthenticatedWithPayloads(
const ::tsl::StringPiece& message,
const std::unordered_map<std::string, std::string>& payloads) {
return errors::Create(absl::StatusCode::kUnauthenticated, message, payloads);
}
bool IsAborted(const absl::Status& status);
bool IsAlreadyExists(const absl::Status& status);
bool IsCancelled(const absl::Status& status);
bool IsDataLoss(const absl::Status& status);
bool IsDeadlineExceeded(const absl::Status& status);
bool IsFailedPrecondition(const absl::Status& status);
bool IsInternal(const absl::Status& status);
bool IsInvalidArgument(const absl::Status& status);
bool IsNotFound(const absl::Status& status);
bool IsOutOfRange(const absl::Status& status);
bool IsPermissionDenied(const absl::Status& status);
bool IsResourceExhausted(const absl::Status& status);
bool IsUnauthenticated(const absl::Status& status);
bool IsUnavailable(const absl::Status& status);
bool IsUnimplemented(const absl::Status& status);
bool IsUnknown(const absl::Status& status);
inline std::string FormatNodeNameForError(absl::string_view name) {
return strings::StrCat("{{node ", name, "}}");
}
template <typename T>
std::string FormatNodeNamesForError(const T& names) {
return absl::StrJoin(
names, ", ", [](std::string* output, absl::string_view s) {
::tsl::strings::StrAppend(output, FormatNodeNameForError(s));
});
}
inline std::string FormatColocationNodeForError(absl::string_view name) {
return strings::StrCat("{{colocation_node ", name, "}}");
}
template <typename T, typename = std::enable_if_t<
!std::is_convertible_v<T, absl::string_view>>>
std::string FormatColocationNodeForError(const T& names) {
return absl::StrJoin(
names, ", ", [](std::string* output, absl::string_view s) {
::tsl::strings::StrAppend(output, FormatColocationNodeForError(s));
});
}
inline std::string FormatFunctionForError(absl::string_view name) {
return strings::StrCat("{{function_node ", name, "}}");
}
inline absl::Status ReplaceErrorFromNonCommunicationOps(
const absl::Status s, absl::string_view op_name) {
assert(::tsl::errors::IsUnavailable(s));
return absl::Status(
absl::StatusCode::kInternal,
strings::StrCat(
s.message(), "\nExecuting non-communication op <", op_name,
"> originally returned UnavailableError, and was replaced by "
"InternalError to avoid invoking TF network error handling logic."));
}
template <typename T>
std::string FormatOriginalNodeLocationForError(const T& node_names,
const T& func_names) {
std::vector<std::string> error_message;
for (int i = 0; i != node_names.size(); ++i) {
if (i != 0) {
error_message.push_back(", ");
}
if (i < func_names.size()) {
error_message.push_back(FormatFunctionForError(func_names[i]));
}
error_message.push_back(FormatNodeNameForError(node_names[i]));
}
return absl::StrJoin(error_message, "");
}
using ::tsl::error::OK;
}
}
#endif
#include "tsl/platform/errors.h"
#include <errno.h>
#include <string.h>
#include "tsl/platform/status.h"
#include "tsl/platform/strcat.h"
namespace tsl {
namespace errors {
namespace {
absl::StatusCode ErrnoToCode(int err_number) {
absl::StatusCode code;
switch (err_number) {
case 0:
code = absl::StatusCode::kOk;
break;
case EINVAL:
case ENAMETOOLONG:
case E2BIG:
case EDESTADDRREQ:
case EDOM:
case EFAULT:
case EILSEQ:
case ENOPROTOOPT:
case ENOSTR:
case ENOTSOCK:
case ENOTTY:
case EPROTOTYPE:
case ESPIPE:
code = absl::StatusCode::kInvalidArgument;
break;
case ETIMEDOUT:
case ETIME:
code = absl::StatusCode::kDeadlineExceeded;
break;
case ENODEV:
case ENOENT:
case ENXIO:
case ESRCH:
code = absl::StatusCode::kNotFound;
break;
case EEXIST:
case EADDRNOTAVAIL:
case EALREADY:
code = absl::StatusCode::kAlreadyExists;
break;
case EPERM:
case EACCES:
case EROFS:
code = absl::StatusCode::kPermissionDenied;
break;
case ENOTEMPTY:
case EISDIR:
case ENOTDIR:
case EADDRINUSE:
case EBADF:
case EBUSY:
case ECHILD:
case EISCONN:
#if !defined(_WIN32) && !defined(__HAIKU__)
case ENOTBLK:
#endif
case ENOTCONN:
case EPIPE:
#if !defined(_WIN32)
case ESHUTDOWN:
#endif
case ETXTBSY:
code = absl::StatusCode::kFailedPrecondition;
break;
case ENOSPC:
#if !defined(_WIN32)
case EDQUOT:
#endif
case EMFILE:
case EMLINK:
case ENFILE:
case ENOBUFS:
case ENODATA:
case ENOMEM:
case ENOSR:
#if !defined(_WIN32) && !defined(__HAIKU__)
case EUSERS:
#endif
code = absl::StatusCode::kResourceExhausted;
break;
case EFBIG:
case EOVERFLOW:
case ERANGE:
code = absl::StatusCode::kOutOfRange;
break;
case ENOSYS:
case ENOTSUP:
case EAFNOSUPPORT:
#if !defined(_WIN32)
case EPFNOSUPPORT:
#endif
case EPROTONOSUPPORT:
#if !defined(_WIN32) && !defined(__HAIKU__)
case ESOCKTNOSUPPORT:
#endif
case EXDEV:
code = absl::StatusCode::kUnimplemented;
break;
case EAGAIN:
case ECONNREFUSED:
case ECONNABORTED:
case ECONNRESET:
case EINTR:
#if !defined(_WIN32)
case EHOSTDOWN:
#endif
case EHOSTUNREACH:
case ENETDOWN:
case ENETRESET:
case ENETUNREACH:
case ENOLCK:
case ENOLINK:
#if !(defined(__APPLE__) || defined(__FreeBSD__) || defined(_WIN32) || \
defined(__HAIKU__))
case ENONET:
#endif
code = absl::StatusCode::kUnavailable;
break;
case EDEADLK:
#if !defined(_WIN32)
case ESTALE:
#endif
code = absl::StatusCode::kAborted;
break;
case ECANCELED:
code = absl::StatusCode::kCancelled;
break;
case EBADMSG:
case EIDRM:
case EINPROGRESS:
case EIO:
case ELOOP:
case ENOEXEC:
case ENOMSG:
case EPROTO:
#if !defined(_WIN32) && !defined(__HAIKU__)
case EREMOTE:
#endif
code = absl::StatusCode::kUnknown;
break;
default: {
code = absl::StatusCode::kUnknown;
break;
}
}
return code;
}
}
absl::Status IOError(const string& context, int err_number) {
auto code = ErrnoToCode(err_number);
return absl::Status(code,
strings::StrCat(context, "; ", strerror(err_number)));
}
bool IsAborted(const absl::Status& status) {
return status.code() == tsl::error::Code::ABORTED;
}
bool IsAlreadyExists(const absl::Status& status) {
return status.code() == tsl::error::Code::ALREADY_EXISTS;
}
bool IsCancelled(const absl::Status& status) {
return status.code() == tsl::error::Code::CANCELLED;
}
bool IsDataLoss(const absl::Status& status) {
return status.code() == tsl::error::Code::DATA_LOSS;
}
bool IsDeadlineExceeded(const absl::Status& status) {
return status.code() == tsl::error::Code::DEADLINE_EXCEEDED;
}
bool IsFailedPrecondition(const absl::Status& status) {
return status.code() == tsl::error::Code::FAILED_PRECONDITION;
}
bool IsInternal(const absl::Status& status) {
return status.code() == tsl::error::Code::INTERNAL;
}
bool IsInvalidArgument(const absl::Status& status) {
return status.code() == tsl::error::Code::INVALID_ARGUMENT;
}
bool IsNotFound(const absl::Status& status) {
return status.code() == tsl::error::Code::NOT_FOUND;
}
bool IsOutOfRange(const absl::Status& status) {
return status.code() == tsl::error::Code::OUT_OF_RANGE;
}
bool IsPermissionDenied(const absl::Status& status) {
r | #include "tsl/platform/errors.h"
#include "absl/status/status.h"
#include "tsl/platform/test.h"
namespace tsl {
TEST(AppendToMessageTest, PayloadsAreCopied) {
absl::Status status = errors::Aborted("Aborted Error Message");
status.SetPayload("payload_key", absl::Cord("payload_value"));
errors::AppendToMessage(&status, "Appended Message");
EXPECT_EQ(status.message(), "Aborted Error Message\n\tAppended Message");
EXPECT_EQ(status.GetPayload("payload_key"), absl::Cord("payload_value"));
}
TEST(Status, GetAllPayloads) {
absl::Status s_error(absl::StatusCode::kInternal, "Error message");
s_error.SetPayload("Error key", absl::Cord("foo"));
auto payloads_error_status = errors::GetPayloads(s_error);
ASSERT_EQ(payloads_error_status.size(), 1);
ASSERT_EQ(payloads_error_status["Error key"], "foo");
absl::Status s_ok = absl::Status();
auto payloads_ok_status = errors::GetPayloads(s_ok);
ASSERT_TRUE(payloads_ok_status.empty());
}
TEST(Status, OKStatusInsertPayloadsFromErrorStatus) {
absl::Status s_error(absl::StatusCode::kInternal, "Error message");
s_error.SetPayload("Error key", absl::Cord("foo"));
absl::Status s_ok = absl::Status();
errors::InsertPayloads(s_ok, errors::GetPayloads(s_error));
auto payloads_ok_status = errors::GetPayloads(s_ok);
ASSERT_TRUE(payloads_ok_status.empty());
}
TEST(Status, ErrorStatusInsertPayloadsFromOKStatus) {
absl::Status s_error(absl::StatusCode::kInternal, "Error message");
s_error.SetPayload("Error key", absl::Cord("foo"));
absl::Status s_ok = absl::Status();
errors::InsertPayloads(s_error, errors::GetPayloads(s_ok));
ASSERT_EQ(s_error.GetPayload("Error key"), "foo");
}
TEST(Status, ErrorStatusInsertPayloadsFromErrorStatus) {
absl::Status s_error1(absl::StatusCode::kInternal, "Error message");
s_error1.SetPayload("Error key 1", absl::Cord("foo"));
s_error1.SetPayload("Error key 2", absl::Cord("bar"));
absl::Status s_error2(absl::StatusCode::kInternal, "Error message");
s_error2.SetPayload("Error key", absl::Cord("bar"));
ASSERT_EQ(s_error2.GetPayload("Error key"), "bar");
errors::InsertPayloads(s_error2, errors::GetPayloads(s_error1));
ASSERT_EQ(s_error2.GetPayload("Error key 1"), "foo");
ASSERT_EQ(s_error2.GetPayload("Error key 2"), "bar");
auto payloads_error_status = errors::GetPayloads(s_error2);
ASSERT_EQ(payloads_error_status.size(), 3);
}
#if defined(PLATFORM_GOOGLE)
absl::Status GetError() {
return absl::InvalidArgumentError("An invalid argument error");
}
absl::Status PropagateError() {
TF_RETURN_IF_ERROR(GetError());
return absl::OkStatus();
}
absl::Status PropagateError2() {
TF_RETURN_IF_ERROR(PropagateError());
return absl::OkStatus();
}
TEST(Status, StackTracePropagation) {
absl::Status s = PropagateError2();
auto sources = s.GetSourceLocations();
ASSERT_EQ(sources.size(), 3);
for (int i = 0; i < 3; ++i) {
ASSERT_EQ(sources[i].file_name(),
"third_party/tensorflow/tsl/platform/errors_test.cc");
}
}
TEST(Status, SourceLocationsPreservedByAppend) {
absl::Status s = PropagateError2();
ASSERT_EQ(s.GetSourceLocations().size(), 3);
errors::AppendToMessage(&s, "A new message.");
ASSERT_EQ(s.GetSourceLocations().size(), 3);
}
TEST(Status, SourceLocationsPreservedByUpdate) {
absl::Status s = PropagateError2();
ASSERT_EQ(s.GetSourceLocations().size(), 3);
absl::Status s2 = errors::CreateWithUpdatedMessage(s, "New message.");
ASSERT_EQ(s2.GetSourceLocations().size(), 3);
}
#endif
} | 2,264 |
#ifndef TENSORFLOW_TSL_PLATFORM_RESOURCE_LOADER_H_
#define TENSORFLOW_TSL_PLATFORM_RESOURCE_LOADER_H_
#include <string>
namespace tsl {
std::string GetDataDependencyFilepath(const std::string& relative_path);
}
#endif
#include "tsl/platform/resource_loader.h"
#include <cstdlib>
#include <string>
#include "tsl/platform/logging.h"
#include "tsl/platform/path.h"
#include "tsl/platform/test.h"
namespace tsl {
std::string GetDataDependencyFilepath(const std::string& relative_path) {
const char* srcdir = std::getenv("TEST_SRCDIR");
if (!srcdir) {
LOG(FATAL) << "Environment variable TEST_SRCDIR unset!";
}
const char* workspace = std::getenv("TEST_WORKSPACE");
if (!workspace) {
LOG(FATAL) << "Environment variable TEST_WORKSPACE unset!";
}
return testing::kIsOpenSource
? io::JoinPath(srcdir, workspace, relative_path)
: io::JoinPath(srcdir, workspace, "third_party", relative_path);
}
} | #include "tensorflow/core/platform/resource_loader.h"
#include "tensorflow/core/platform/env.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/path.h"
#include "tensorflow/core/platform/status.h"
#include "tensorflow/core/platform/test.h"
namespace tensorflow {
namespace {
string DataDependencyPath() {
return io::JoinPath("tensorflow", "core", "platform", "resource_loader.h");
}
TEST(ResourceLoaderTest, FindsAndOpensFile) {
string filepath = GetDataDependencyFilepath(DataDependencyPath());
Status s = Env::Default()->FileExists(filepath);
EXPECT_TRUE(s.ok()) << "No file found at this location: " << filepath;
}
}
} | 2,265 |
#ifndef TENSORFLOW_TSL_PLATFORM_NUMBERS_H_
#define TENSORFLOW_TSL_PLATFORM_NUMBERS_H_
#include <cstdint>
#include <string>
#include "tsl/platform/stringpiece.h"
#include "tsl/platform/types.h"
namespace tsl {
namespace strings {
static const int kFastToBufferSize = 32;
size_t FastInt32ToBufferLeft(int32_t i, char* buffer);
size_t FastUInt32ToBufferLeft(uint32_t i, char* buffer);
size_t FastInt64ToBufferLeft(int64_t i, char* buffer);
size_t FastUInt64ToBufferLeft(uint64_t i, char* buffer);
size_t DoubleToBuffer(double value, char* buffer);
size_t FloatToBuffer(float value, char* buffer);
std::string FpToString(Fprint fp);
bool StringToFp(const std::string& s, Fprint* fp);
StringPiece Uint64ToHexString(uint64_t v, char* buf);
bool HexStringToUint64(const StringPiece& s, uint64_t* result);
bool safe_strto32(StringPiece str, int32_t* value);
bool safe_strtou32(StringPiece str, uint32_t* value);
bool safe_strto64(StringPiece str, int64_t* value);
bool safe_strtou64(StringPiece str, uint64_t* value);
bool safe_strtof(StringPiece str, float* value);
bool safe_strtod(StringPiece str, double* value);
inline bool ProtoParseNumeric(StringPiece s, int32_t* value) {
return safe_strto32(s, value);
}
inline bool ProtoParseNumeric(StringPiece s, uint32_t* value) {
return safe_strtou32(s, value);
}
inline bool ProtoParseNumeric(StringPiece s, int64_t* value) {
return safe_strto64(s, value);
}
inline bool ProtoParseNumeric(StringPiece s, uint64_t* value) {
return safe_strtou64(s, value);
}
inline bool ProtoParseNumeric(StringPiece s, float* value) {
return safe_strtof(s, value);
}
inline bool ProtoParseNumeric(StringPiece s, double* value) {
return safe_strtod(s, value);
}
template <typename T>
bool SafeStringToNumeric(StringPiece s, T* value) {
return ProtoParseNumeric(s, value);
}
std::string HumanReadableNum(int64_t value);
std::string HumanReadableNumBytes(int64_t num_bytes);
std::string HumanReadableElapsedTime(double seconds);
}
}
#endif
#include "tsl/platform/numbers.h"
#include <ctype.h>
#include <float.h>
#include <stdio.h>
#include <stdlib.h>
#include <algorithm>
#include <cinttypes>
#include <cmath>
#include <cstdint>
#include <locale>
#include <unordered_map>
#include "double-conversion/double-conversion.h"
#include "tsl/platform/str_util.h"
#include "tsl/platform/logging.h"
#include "tsl/platform/macros.h"
#include "tsl/platform/stringprintf.h"
#include "tsl/platform/types.h"
namespace tsl {
namespace {
template <typename T>
const std::unordered_map<std::string, T>* GetSpecialNumsSingleton() {
static const std::unordered_map<std::string, T>* special_nums =
CHECK_NOTNULL((new const std::unordered_map<std::string, T>{
{"inf", std::numeric_limits<T>::infinity()},
{"+inf", std::numeric_limits<T>::infinity()},
{"-inf", -std::numeric_limits<T>::infinity()},
{"infinity", std::numeric_limits<T>::infinity()},
{"+infinity", std::numeric_limits<T>::infinity()},
{"-infinity", -std::numeric_limits<T>::infinity()},
{"nan", std::numeric_limits<T>::quiet_NaN()},
{"+nan", std::numeric_limits<T>::quiet_NaN()},
{"-nan", -std::numeric_limits<T>::quiet_NaN()},
}));
return special_nums;
}
template <typename T>
T locale_independent_strtonum(const char* str, const char** endptr) {
auto special_nums = GetSpecialNumsSingleton<T>();
std::stringstream s(str);
std::string special_num_str;
s >> special_num_str;
for (size_t i = 0; i < special_num_str.length(); ++i) {
special_num_str[i] =
std::tolower(special_num_str[i], std::locale::classic());
}
auto entry = special_nums->find(special_num_str);
if (entry != special_nums->end()) {
*endptr = str + (s.eof() ? static_cast<std::iostream::pos_type>(strlen(str))
: s.tellg());
return entry->second;
} else {
if (special_num_str.compare(0, 2, "0x") == 0 ||
special_num_str.compare(0, 3, "-0x") == 0) {
return strtol(str, const_cast<char**>(endptr), 16);
}
}
s.str(str);
s.clear();
s.imbue(std::locale::classic());
T result;
s >> result;
if (s.fail()) {
if (result == std::numeric_limits<T>::max() ||
result == std::numeric_limits<T>::infinity()) {
result = std::numeric_limits<T>::infinity();
s.clear(s.rdstate() & ~std::ios::failbit);
} else if (result == -std::numeric_limits<T>::max() ||
result == -std::numeric_limits<T>::infinity()) {
result = -std::numeric_limits<T>::infinity();
s.clear(s.rdstate() & ~std::ios::failbit);
}
}
if (endptr) {
*endptr =
str +
(s.fail() ? static_cast<std::iostream::pos_type>(0)
: (s.eof() ? static_cast<std::iostream::pos_type>(strlen(str))
: s.tellg()));
}
return result;
}
static inline const double_conversion::StringToDoubleConverter&
StringToFloatConverter() {
static const double_conversion::StringToDoubleConverter converter(
double_conversion::StringToDoubleConverter::ALLOW_LEADING_SPACES |
double_conversion::StringToDoubleConverter::ALLOW_HEX |
double_conversion::StringToDoubleConverter::ALLOW_TRAILING_SPACES |
double_conversion::StringToDoubleConverter::ALLOW_CASE_INSENSIBILITY,
0., 0., "inf", "nan");
return converter;
}
}
namespace strings {
size_t FastInt32ToBufferLeft(int32_t i, char* buffer) {
uint32_t u = i;
size_t length = 0;
if (i < 0) {
*buffer++ = '-';
++length;
u = 0 - u;
}
length += FastUInt32ToBufferLeft(u, buffer);
return length;
}
size_t FastUInt32ToBufferLeft(uint32_t i, char* buffer) {
char* start = buffer;
do {
*buffer++ = ((i % 10) + '0');
i /= 10;
} while (i > 0);
*buffer = 0;
std::reverse(start, buffer);
return buffer - start;
}
size_t FastInt64ToBufferLeft(int64_t i, char* buffer) {
uint64_t u = i;
size_t length = 0;
if (i < 0) {
*buffer++ = '-';
++length;
u = 0 - u;
}
length += FastUInt64ToBufferLeft(u, buffer);
return length;
}
size_t FastUInt64ToBufferLeft(uint64_t i, char* buffer) {
char* start = buffer;
do {
*buffer++ = ((i % 10) + '0');
i /= 10;
} while (i > 0);
*buffer = 0;
std::reverse(start, buffer);
return buffer - start;
}
static const double kDoublePrecisionCheckMax = DBL_MAX / 1.000000000000001;
size_t DoubleToBuffer(double value, char* buffer) {
static_assert(DBL_DIG < 20, "DBL_DIG is too big");
if (std::isnan(value)) {
int snprintf_result = snprintf(buffer, kFastToBufferSize, "%snan",
std::signbit(value) ? "-" : "");
DCHECK(snprintf_result > 0 && snprintf_result < kFastToBufferSize);
return snprintf_result;
}
if (std::abs(value) <= kDoublePrecisionCheckMax) {
int snprintf_result =
snprintf(buffer, kFastToBufferSize, "%.*g", DBL_DIG, value);
DCHECK(snprintf_result > 0 && snprintf_result < kFastToBufferSize);
if (locale_independent_strtonum<double>(buffer, nullptr) == value) {
return snprintf_result;
}
}
int snprintf_result =
snprintf(buffer, kFastToBufferSize, "%.*g", DBL_DIG + 2, value);
DCHECK(snprintf_result > 0 && snprintf_result < kFastToBufferSize);
return snprintf_result;
}
namespace {
char SafeFirstChar(StringPiece str) {
if (str.empty()) return '\0';
return str[0];
}
void SkipSpaces(StringPiece* str) {
while (isspace(SafeFirstChar(*str))) str->remove_prefix(1);
}
}
bool safe_strto64(StringPiece str, int64_t* value) {
SkipSpaces(&str);
int64_t vlimit = kint64max;
int sign = 1;
if (absl::ConsumePrefix(&str, "-")) {
sign = -1;
vlimit = kint64min;
}
if (!isdigit(SafeFirstChar(str))) return false;
int64_t result = 0;
if (sign == 1) {
do {
int digit = SafeFirstChar(str) - '0';
if ((vlimit - digit) / 10 < result) {
return false;
}
result = result * 10 + digit;
str.remove_prefix(1);
} while (isdigit(SafeFirstChar(str)));
} else {
do {
int digit = SafeFirstChar(str) - '0';
if ((vlimit + digit) / 10 > result) {
return false;
}
result = result * 10 - digit;
str.remove_prefix(1);
} while (isdigit(SafeFirstChar(str)));
}
SkipSpaces(&str);
if (!str.empty()) return false;
*value = result;
return true;
}
bool safe_strtou64(StringPiece str, uint64_t* value) {
SkipSpaces(&str);
if (!isdigit(SafeFirstChar(str))) return false;
uint64_t result = 0;
do {
int digit = SafeFirstChar(str) - '0';
if ((kuint64max - digit) / 10 < result) {
return false;
}
result = result * 10 + digit;
str.remove_prefix(1);
} while (isdigit(SafeFirstChar(str)));
SkipSpaces(&str);
if (!str.empty()) return false;
*value = result;
return true;
}
bool safe_strto32(StringPiece str, int32_t* value) {
SkipSpaces(&str);
int64_t vmax = kint32max;
int sign = 1;
if (absl::ConsumePrefix(&str, "-")) {
sign = -1;
++vmax;
}
if (!isdigit(SafeFirstChar(str))) return false;
int64_t result = 0;
do {
result = result * 10 + SafeFirstChar(str) - '0';
if (result > vmax) {
return false;
}
str.remove_prefix(1);
} while (isdigit(SafeFirstChar(str)));
SkipSpaces(&str);
if (!str.empty()) return false;
*value = static_cast<int32_t>(result * sign);
return true;
}
bool safe_strtou32(StringPiece str, uint32_t* value) {
SkipSpaces(&str);
if (!isdigit(SafeFirstChar(str))) return false;
int64_t result = 0;
do {
result = result * 10 + SafeFirstChar(str) - '0';
if (result > kuint32max) {
return false;
}
str.remove_prefix(1);
} while (isdigit(SafeFirstChar(str)));
SkipSpaces(&str);
if (!str.empty()) return false;
*value = static_cast<uint32_t>(result);
return true;
}
bool safe_strtof(StringPiece str, float* value) {
int processed_characters_count = -1;
auto len = str.size();
if (len >= kFastToBufferSize) return false;
if (len > std::numeric_limits<int>::max()) return false;
*value = StringToFloatConverter().StringToFloat(
str.data(), static_cast<int>(len), &processed_characters_count);
return processed_characters_count > 0;
}
bool safe_strtod(StringPiece str, double* value) {
int processed_characters_count = -1;
auto len = str.size();
if (len >= kFastToBufferSize) return false;
if (len > std::numeric_limits<int>::max()) return false;
*value = StringToFloatConverter().StringToDouble(
str.data(), static_cast<int>(len), &processed_characters_count);
return processed_characters_count > 0;
}
size_t FloatToBuffer(float value, char* buffer) {
static_assert(FLT_DIG < 10, "FLT_DIG is too big");
if (std::isnan(value)) {
int snprintf_result = snprintf(buffer, kFastToBufferSize, "%snan",
std::signbit(value) ? "-" : "");
DCHECK(snprintf_result > 0 && snprintf_result < kFastToBufferSize);
return snprintf_result;
}
int snprintf_result =
snprintf(buffer, kFastToBufferSize, "%.*g", FLT_DIG, value);
DCHECK(snprintf_result > 0 && snprintf_result < kFastToBufferSize);
float parsed_value;
if (!safe_strtof(buffer, &parsed_value) || parsed_value != value) {
snprintf_result =
snprintf(buffer, kFastToBufferSize, "%.*g", FLT_DIG + 3, value);
DCHECK(snprintf_result > 0 && snprintf_result < kFastToBufferSize);
}
return snprintf_result;
}
std::string FpToString(Fprint fp) {
char buf[17];
snprintf(buf, sizeof(buf), "%016llx", static_cast<long long>(fp));
return std::string(buf);
}
bool StringToFp(const std::string& s, Fprint* fp) {
char junk;
uint64_t result;
if (sscanf(s.c_str(), "%" SCNx64 "%c", &result, &junk) == 1) {
*fp = result;
return true;
} else {
return false;
}
}
StringPiece Uint64ToHexString(uint64_t v, char* buf) {
static const char* hexdigits = "0123456789abcdef";
const int num_byte = 16;
buf[num_byte] = '\0';
for (int i = num_byte - 1; i >= 0; i--) {
buf[i] = hexdigits[v & 0xf];
v >>= 4;
}
return StringPiece(buf, num_byte);
}
bool HexStringToUint64(const StringPiece& s, uint64_t* result) {
uint64_t v = 0;
if (s.empty()) {
return false;
}
for (size_t i = 0; i < s.size(); i++) {
char c = s[i];
if (c >= '0' && c <= '9') {
v = (v << 4) + (c - '0');
} else if (c >= 'a' && c <= 'f') {
v = (v << 4) + 10 + (c - 'a');
} else if (c >= 'A' && c <= 'F') {
v = (v << 4) + 10 + (c - 'A');
} else {
return false;
}
}
*result = v;
return true;
}
std::string HumanReadableNum(int64_t value) {
std::string s;
if (value < 0) {
s += "-";
value = -value;
}
if (value < 1000) {
Appendf(&s, "%lld", static_cast<long long>(value));
} else if (value >= static_cast<int64_t>(1e15)) {
Appendf(&s, "%0.3G", static_cast<double>(value));
} else {
static const char units[] = "kMBT";
const char* unit = units;
while (value >= static_cast<int64_t>(1000000)) {
value /= static_cast<int64_t>(1000);
++unit;
CHECK(unit < units + TF_ARRAYSIZE(units));
}
Appendf(&s, "%.2f%c", value / 1000.0, *unit);
}
return s;
}
std::string HumanReadableNumBytes(int64_t num_bytes) {
if (num_bytes == kint64min) {
return "-8E";
}
const char* neg_str = (num_bytes < 0) ? "-" : "";
if (num_bytes < 0) {
num_bytes = -num_bytes;
}
if (num_bytes < 1024) {
char buf[8];
snprintf(buf, sizeof(buf), "%s%lldB", neg_str,
static_cast<long long>(num_bytes));
return std::string(buf);
}
static const char units[] = "KMGTPE";
const char* unit = units;
while (num_bytes >= static_cast<int64_t>(1024) * 1024) {
num_bytes /= 1024;
++unit;
CHECK(unit < units + TF_ARRAYSIZE(units));
}
char buf[16];
snprintf(buf, sizeof(buf), ((*unit == 'K') ? "%s%.1f%ciB" : "%s%.2f%ciB"),
neg_str, num_bytes / 1024.0, *unit);
return std::string(buf);
}
std::string HumanReadableElapsedTime(double seconds) {
std::string human_readable;
if (seconds < 0) {
human_readable = "-";
seconds = -seconds;
}
const double microseconds = seconds * 1.0e6;
if (microseconds < 999.5) {
strings::Appendf(&human_readable, "%0.3g us", microseconds);
return human_readable;
}
double milliseconds = seconds * 1e3;
if (milliseconds >= .995 && milliseconds < 1) {
milliseconds = 1.0;
}
if (milliseconds < 999.5) {
strings::Appendf(&human_readable, "%0.3g ms", milliseconds);
return human_readable;
}
if (seconds < 60.0) {
strings::Appendf(&human_readable, "%0.3g s", seconds);
return human_readable;
}
seconds /= 60.0;
if (seconds < 60.0) {
strings::Appendf(&human_readable, "%0.3g min", seconds);
return human_readable;
}
seconds /= 60.0;
if (seconds < 24.0) {
strings::Appendf(&human_readable, "%0.3g h", seconds);
return human_readable;
}
seconds /= 24.0;
if (seconds < 30.0) {
strings::Appendf(&human_readable, "%0.3g days", seconds);
return human_readable;
}
if (seconds < 365.2425) {
strings::Appendf(&human_readable, "%0.3g months", seconds / 30.436875);
return human_readable;
}
seconds /= 365.2425;
strings::Appendf(&human_readable, "%0.3g years", seconds);
return human_readable;
}
}
} | #include "tsl/platform/numbers.h"
#include <cmath>
#include <string>
#include "tsl/platform/test.h"
namespace tsl {
namespace strings {
TEST(FpToString, Ints) {
for (int s = 0; s < 64; s++) {
for (int delta = -1; delta <= 1; delta++) {
uint64 fp = (1ull << s) + delta;
string s = FpToString(fp);
uint64 fp2;
EXPECT_TRUE(StringToFp(s, &fp2));
EXPECT_EQ(fp, fp2);
}
}
Fprint dummy;
EXPECT_FALSE(StringToFp("", &dummy));
EXPECT_FALSE(StringToFp("xyz", &dummy));
EXPECT_FALSE(StringToFp("0000000000000000xyz", &dummy));
}
TEST(Uint64ToHexString, Ints) {
for (int s = 0; s < 64; s++) {
for (int delta = -1; delta <= 1; delta++) {
uint64 fp = (1ull << s) + delta;
char buf[kFastToBufferSize];
StringPiece s = Uint64ToHexString(fp, buf);
uint64 fp2;
EXPECT_TRUE(HexStringToUint64(s, &fp2));
EXPECT_EQ(fp, fp2) << s;
}
}
uint64 dummy;
EXPECT_FALSE(HexStringToUint64("", &dummy));
EXPECT_FALSE(HexStringToUint64("xyz", &dummy));
EXPECT_FALSE(HexStringToUint64("0000000000000000xyz", &dummy));
}
TEST(HumanReadableNum, Basic) {
EXPECT_EQ(HumanReadableNum(823), "823");
EXPECT_EQ(HumanReadableNum(1024), "1.02k");
EXPECT_EQ(HumanReadableNum(4000), "4.00k");
EXPECT_EQ(HumanReadableNum(999499), "999.50k");
EXPECT_EQ(HumanReadableNum(1000000), "1.00M");
EXPECT_EQ(HumanReadableNum(1048575), "1.05M");
EXPECT_EQ(HumanReadableNum(1048576), "1.05M");
EXPECT_EQ(HumanReadableNum(23956812342), "23.96B");
EXPECT_EQ(HumanReadableNum(123456789012345678), "1.23E+17");
}
TEST(HumanReadableNumBytes, Bytes) {
EXPECT_EQ("0B", HumanReadableNumBytes(0));
EXPECT_EQ("4B", HumanReadableNumBytes(4));
EXPECT_EQ("1023B", HumanReadableNumBytes(1023));
EXPECT_EQ("1.0KiB", HumanReadableNumBytes(1024));
EXPECT_EQ("1.0KiB", HumanReadableNumBytes(1025));
EXPECT_EQ("1.5KiB", HumanReadableNumBytes(1500));
EXPECT_EQ("1.9KiB", HumanReadableNumBytes(1927));
EXPECT_EQ("2.0KiB", HumanReadableNumBytes(2048));
EXPECT_EQ("1.00MiB", HumanReadableNumBytes(1 << 20));
EXPECT_EQ("11.77MiB", HumanReadableNumBytes(12345678));
EXPECT_EQ("1.00GiB", HumanReadableNumBytes(1 << 30));
EXPECT_EQ("1.00TiB", HumanReadableNumBytes(1LL << 40));
EXPECT_EQ("1.00PiB", HumanReadableNumBytes(1LL << 50));
EXPECT_EQ("1.00EiB", HumanReadableNumBytes(1LL << 60));
EXPECT_EQ("-1B", HumanReadableNumBytes(-1));
EXPECT_EQ("-4B", HumanReadableNumBytes(-4));
EXPECT_EQ("-1000B", HumanReadableNumBytes(-1000));
EXPECT_EQ("-11.77MiB", HumanReadableNumBytes(-12345678));
EXPECT_EQ("-8E", HumanReadableNumBytes(kint64min));
}
TEST(HumanReadableElapsedTime, Basic) {
EXPECT_EQ(HumanReadableElapsedTime(-10), "-10 s");
EXPECT_EQ(HumanReadableElapsedTime(-0.001), "-1 ms");
EXPECT_EQ(HumanReadableElapsedTime(-60.0), "-1 min");
EXPECT_EQ(HumanReadableElapsedTime(0.00000001), "0.01 us");
EXPECT_EQ(HumanReadableElapsedTime(0.0000012), "1.2 us");
EXPECT_EQ(HumanReadableElapsedTime(0.0012), "1.2 ms");
EXPECT_EQ(HumanReadableElapsedTime(0.12), "120 ms");
EXPECT_EQ(HumanReadableElapsedTime(1.12), "1.12 s");
EXPECT_EQ(HumanReadableElapsedTime(90.0), "1.5 min");
EXPECT_EQ(HumanReadableElapsedTime(600.0), "10 min");
EXPECT_EQ(HumanReadableElapsedTime(9000.0), "2.5 h");
EXPECT_EQ(HumanReadableElapsedTime(87480.0), "1.01 days");
EXPECT_EQ(HumanReadableElapsedTime(7776000.0), "2.96 months");
EXPECT_EQ(HumanReadableElapsedTime(78840000.0), "2.5 years");
EXPECT_EQ(HumanReadableElapsedTime(382386614.40), "12.1 years");
EXPECT_EQ(HumanReadableElapsedTime(DBL_MAX), "5.7e+300 years");
}
TEST(safe_strto32, Int32s) {
int32 result;
EXPECT_EQ(true, safe_strto32("1", &result));
EXPECT_EQ(1, result);
EXPECT_EQ(true, safe_strto32("123", &result));
EXPECT_EQ(123, result);
EXPECT_EQ(true, safe_strto32(" -123 ", &result));
EXPECT_EQ(-123, result);
EXPECT_EQ(true, safe_strto32("2147483647", &result));
EXPECT_EQ(2147483647, result);
EXPECT_EQ(true, safe_strto32("-2147483648", &result));
EXPECT_EQ(-2147483648, result);
EXPECT_EQ(false, safe_strto32(" 132as ", &result));
EXPECT_EQ(false, safe_strto32(" 132.2 ", &result));
EXPECT_EQ(false, safe_strto32(" -", &result));
EXPECT_EQ(false, safe_strto32("", &result));
EXPECT_EQ(false, safe_strto32(" ", &result));
EXPECT_EQ(false, safe_strto32("123 a", &result));
EXPECT_EQ(false, safe_strto32("2147483648", &result));
EXPECT_EQ(false, safe_strto32("-2147483649", &result));
EXPECT_EQ(true, safe_strto32(StringPiece("123", 1), &result));
EXPECT_EQ(1, result);
EXPECT_EQ(true, safe_strto32(StringPiece(" -123", 4), &result));
EXPECT_EQ(-12, result);
EXPECT_EQ(false, safe_strto32(StringPiece(nullptr, 0), &result));
}
TEST(safe_strtou32, UInt32s) {
uint32 result;
EXPECT_TRUE(safe_strtou32("0", &result));
EXPECT_EQ(0, result);
EXPECT_TRUE(safe_strtou32("1", &result));
EXPECT_EQ(1, result);
EXPECT_TRUE(safe_strtou32("123", &result));
EXPECT_EQ(123, result);
EXPECT_TRUE(safe_strtou32("4294967295", &result));
EXPECT_EQ(4294967295, result);
EXPECT_FALSE(safe_strtou32(" 132as ", &result));
EXPECT_FALSE(safe_strtou32(" 132.2 ", &result));
EXPECT_FALSE(safe_strtou32(" -", &result));
EXPECT_FALSE(safe_strtou32("", &result));
EXPECT_FALSE(safe_strtou32(" ", &result));
EXPECT_FALSE(safe_strtou32("123 a", &result));
EXPECT_FALSE(safe_strtou32("123 456", &result));
EXPECT_FALSE(safe_strtou32("4294967296", &result));
EXPECT_FALSE(safe_strtou32("-1", &result));
EXPECT_TRUE(safe_strtou32(StringPiece("123", 1), &result));
EXPECT_EQ(1, result);
EXPECT_TRUE(safe_strtou32(StringPiece(" 123", 3), &result));
EXPECT_EQ(12, result);
EXPECT_FALSE(safe_strtou32(StringPiece(nullptr, 0), &result));
}
TEST(safe_strto64, Int64s) {
int64 result;
EXPECT_EQ(true, safe_strto64("1", &result));
EXPECT_EQ(1, result);
EXPECT_EQ(true, safe_strto64("123", &result));
EXPECT_EQ(123, result);
EXPECT_EQ(true, safe_strto64(" -123 ", &result));
EXPECT_EQ(-123, result);
EXPECT_EQ(true, safe_strto64("9223372036854775807", &result));
EXPECT_EQ(9223372036854775807, result);
EXPECT_EQ(true, safe_strto64("-9223372036854775808", &result));
EXPECT_EQ(kint64min, result);
EXPECT_EQ(false, safe_strto64(" 132as ", &result));
EXPECT_EQ(false, safe_strto64(" 132.2 ", &result));
EXPECT_EQ(false, safe_strto64(" -", &result));
EXPECT_EQ(false, safe_strto64("", &result));
EXPECT_EQ(false, safe_strto64(" ", &result));
EXPECT_EQ(false, safe_strto64("123 a", &result));
EXPECT_EQ(false, safe_strto64("9223372036854775808", &result));
EXPECT_EQ(false, safe_strto64("-9223372036854775809", &result));
EXPECT_EQ(true, safe_strto64(StringPiece("123", 1), &result));
EXPECT_EQ(1, result);
EXPECT_EQ(true, safe_strto64(StringPiece(" -123", 4), &result));
EXPECT_EQ(-12, result);
EXPECT_EQ(false, safe_strto64(StringPiece(nullptr, 0), &result));
}
TEST(safe_strtou64, UInt64s) {
uint64 result;
EXPECT_TRUE(safe_strtou64("0", &result));
EXPECT_EQ(0, result);
EXPECT_TRUE(safe_strtou64("1", &result));
EXPECT_EQ(1, result);
EXPECT_TRUE(safe_strtou64("123", &result));
EXPECT_EQ(123, result);
EXPECT_TRUE(safe_strtou64(" 345 ", &result));
EXPECT_EQ(345, result);
EXPECT_TRUE(safe_strtou64("18446744073709551615", &result));
EXPECT_EQ(18446744073709551615UL, result);
EXPECT_FALSE(safe_strtou64(" 132.2 ", &result));
EXPECT_FALSE(safe_strtou64(" 132.2 ", &result));
EXPECT_FALSE(safe_strtou64(" -", &result));
EXPECT_FALSE(safe_strtou64("", &result));
EXPECT_FALSE(safe_strtou64(" ", &result));
EXPECT_FALSE(safe_strtou64("123 a", &result));
EXPECT_FALSE(safe_strtou64("123 456", &result));
EXPECT_FALSE(safe_strtou64("18446744073709551616", &result));
EXPECT_FALSE(safe_strtou64("-1", &result));
EXPECT_TRUE(safe_strtou64(StringPiece("123", 1), &result));
EXPECT_EQ(1, result);
EXPECT_TRUE(safe_strtou64(StringPiece(" 123", 3), &result));
EXPECT_EQ(12, result);
EXPECT_FALSE(safe_strtou64(StringPiece(nullptr, 0), &result));
}
TEST(safe_strtof, Float) {
float result = 0;
EXPECT_TRUE(safe_strtof("0.123456", &result));
EXPECT_EQ(0.123456f, result);
EXPECT_FALSE(safe_strtof("0.12345abc", &result));
EXPECT_TRUE(safe_strtof("1e39", &result));
EXPECT_EQ(std::numeric_limits<float>::infinity(), result);
EXPECT_TRUE(safe_strtof("-1e39", &result));
EXPECT_EQ(-std::numeric_limits<float>::infinity(), result);
EXPECT_TRUE(safe_strtof("1e-50", &result));
EXPECT_EQ(0, result);
EXPECT_TRUE(safe_strtof("0xF", &result));
EXPECT_EQ(0xF, result);
EXPECT_TRUE(safe_strtof("-0x2A", &result));
EXPECT_EQ(-42.0f, result);
EXPECT_TRUE(safe_strtof(" -0x2", &result));
EXPECT_EQ(-2.0f, result);
EXPECT_TRUE(safe_strtof("8 \t", &result));
EXPECT_EQ(8.0f, result);
EXPECT_TRUE(safe_strtof("\t20.0\t ", &result));
EXPECT_EQ(20.0f, result);
EXPECT_FALSE(safe_strtof("-infinity is awesome", &result));
char test_str[2 * kFastToBufferSize];
for (int i = 0; i < 2 * kFastToBufferSize; ++i) test_str[i] = 'a';
test_str[kFastToBufferSize + 1] = '\0';
EXPECT_FALSE(safe_strtof(test_str, &result));
EXPECT_TRUE(safe_strtof("-inf", &result));
EXPECT_EQ(-std::numeric_limits<float>::infinity(), result);
EXPECT_TRUE(safe_strtof("+inf", &result));
EXPECT_EQ(std::numeric_limits<float>::infinity(), result);
EXPECT_TRUE(safe_strtof("InF", &result));
EXPECT_EQ(std::numeric_limits<float>::infinity(), result);
EXPECT_TRUE(safe_strtof("-INF", &result));
EXPECT_EQ(-std::numeric_limits<float>::infinity(), result);
EXPECT_TRUE(safe_strtof("nan", &result));
EXPECT_TRUE(std::isnan(result));
EXPECT_TRUE(safe_strtof("-nan", &result));
EXPECT_TRUE(std::isnan(result));
EXPECT_TRUE(safe_strtof("-NaN", &result));
EXPECT_TRUE(std::isnan(result));
EXPECT_TRUE(safe_strtof("+NAN", &result));
EXPECT_TRUE(std::isnan(result));
}
TEST(safe_strtod, Double) {
double result = 0;
EXPECT_TRUE(safe_strtod("0.1234567890123", &result));
EXPECT_EQ(0.1234567890123, result);
EXPECT_FALSE(safe_strtod("0.1234567890123abc", &result));
char test_str[2 * kFastToBufferSize];
for (int i = 0; i < 2 * kFastToBufferSize; ++i) test_str[i] = 'a';
test_str[kFastToBufferSize + 1] = '\0';
EXPECT_FALSE(safe_strtod(test_str, &result));
EXPECT_TRUE(safe_strtod("1e310", &result));
EXPECT_EQ(std::numeric_limits<double>::infinity(), result);
EXPECT_TRUE(safe_strtod("-1e310", &result));
EXPECT_EQ(-std::numeric_limits<double>::infinity(), result);
EXPECT_TRUE(safe_strtod("1e-325", &result));
EXPECT_EQ(0, result);
EXPECT_TRUE(safe_strtod(" -0x1c", &result));
EXPECT_EQ(-28.0, result);
EXPECT_TRUE(safe_strtod("50 \t", &result));
EXPECT_EQ(50.0, result);
EXPECT_TRUE(safe_strtod("\t82.0\t ", &result));
EXPECT_EQ(82.0, result);
EXPECT_FALSE(safe_strtod("infinity", &result));
EXPECT_TRUE(safe_strtod("-inf", &result));
EXPECT_EQ(-std::numeric_limits<double>::infinity(), result);
EXPECT_TRUE(safe_strtod("+inf", &result));
EXPECT_EQ(std::numeric_limits<double>::infinity(), result);
EXPECT_TRUE(safe_strtod("InF", &result));
EXPECT_EQ(std::numeric_limits<double>::infinity(), result);
EXPECT_TRUE(safe_strtod("-INF", &result));
EXPECT_EQ(-std::numeric_limits<double>::infinity(), result);
EXPECT_TRUE(safe_strtod("nan", &result));
EXPECT_TRUE(std::isnan(result));
EXPECT_TRUE(safe_strtod("-nan", &result));
EXPECT_TRUE(std::isnan(result));
EXPECT_TRUE(safe_strtod("-NaN", &result));
EXPECT_TRUE(std::isnan(result));
EXPECT_TRUE(safe_strtod("+NAN", &result));
EXPECT_TRUE(std::isnan(result));
}
}
} | 2,266 |
#ifndef TENSORFLOW_TSL_PLATFORM_THREADPOOL_H_
#define TENSORFLOW_TSL_PLATFORM_THREADPOOL_H_
#include <functional>
#include <memory>
#include "absl/types/optional.h"
#include "tsl/platform/env.h"
#include "tsl/platform/macros.h"
#include "tsl/platform/threadpool_interface.h"
#include "tsl/platform/types.h"
namespace Eigen {
class Allocator;
class ThreadPoolInterface;
struct ThreadPoolDevice;
template <typename Environment>
class ThreadPoolTempl;
}
namespace tsl {
namespace thread {
struct EigenEnvironment;
class ThreadPool {
public:
enum class SchedulingStrategy {
kAdaptive,
kFixedBlockSize
};
class SchedulingParams {
public:
explicit SchedulingParams(SchedulingStrategy strategy,
absl::optional<int64_t> cost_per_unit,
absl::optional<int64_t> block_size)
: strategy_(strategy),
cost_per_unit_(cost_per_unit),
block_size_(block_size) {}
SchedulingStrategy strategy() const { return strategy_; }
absl::optional<int64_t> cost_per_unit() const { return cost_per_unit_; }
absl::optional<int64_t> block_size() const { return block_size_; }
private:
SchedulingStrategy strategy_;
absl::optional<int64_t> cost_per_unit_;
absl::optional<int64_t> block_size_;
};
ThreadPool(Env* env, const ThreadOptions& thread_options,
const std::string& name, int num_threads, bool low_latency_hint,
Eigen::Allocator* allocator = nullptr);
ThreadPool(Env* env, const std::string& name, int num_threads);
ThreadPool(Env* env, const ThreadOptions& thread_options,
const std::string& name, int num_threads);
explicit ThreadPool(thread::ThreadPoolInterface* user_threadpool);
~ThreadPool();
void Schedule(std::function<void()> fn);
void SetStealPartitions(
const std::vector<std::pair<unsigned, unsigned>>& partitions);
void ScheduleWithHint(std::function<void()> fn, int start, int limit);
int NumShardsUsedByFixedBlockSizeScheduling(const int64_t total,
const int64_t block_size);
int NumShardsUsedByTransformRangeConcurrently(const int64_t block_size,
const int64_t total);
void ParallelFor(int64_t total, int64_t cost_per_unit,
const std::function<void(int64_t, int64_t)>& fn);
void ParallelFor(int64_t total, const SchedulingParams& scheduling_params,
const std::function<void(int64_t, int64_t)>& fn);
void TransformRangeConcurrently(
const int64_t block_size, const int64_t total,
const std::function<void(int64_t, int64_t)>& fn);
void ParallelForWithWorkerId(
int64_t total, int64_t cost_per_unit,
const std::function<void(int64_t, int64_t, int)>& fn);
void ParallelForWithWorkerId(
int64_t total, const SchedulingParams& scheduling_params,
const std::function<void(int64_t, int64_t, int)>& fn);
int NumThreads() const;
int CurrentThreadId() const;
Eigen::ThreadPoolInterface* AsEigenThreadPool() const;
private:
void ParallelForFixedBlockSizeScheduling(
const int64_t total, const int64_t block_size,
const std::function<void(int64_t, int64_t)>& fn);
Eigen::ThreadPoolInterface* underlying_threadpool_;
std::unique_ptr<Eigen::ThreadPoolTempl<EigenEnvironment>> eigen_threadpool_;
std::unique_ptr<Eigen::ThreadPoolDevice> threadpool_device_;
ThreadPool(const ThreadPool&) = delete;
void operator=(const ThreadPool&) = delete;
};
}
}
#endif
#include "tsl/platform/threadpool.h"
#define EIGEN_USE_THREADS
#include "absl/types/optional.h"
#include "unsupported/Eigen/CXX11/Tensor"
#include "tsl/platform/blocking_counter.h"
#include "tsl/platform/context.h"
#include "tsl/platform/denormal.h"
#include "tsl/platform/logging.h"
#include "tsl/platform/mutex.h"
#include "tsl/platform/numa.h"
#include "tsl/platform/setround.h"
#include "tsl/platform/tracing.h"
#ifdef DNNL_AARCH64_USE_ACL
#include "tsl/platform/cpu_info.h"
#endif
#ifdef TENSORFLOW_THREADSCALING_EXPERIMENTAL
ABSL_FLAG(float, tensorflow_num_threads_scale_factor, 1.0,
"Allows to scale all Tensorflow ThreadPools. Total number of threads "
"in a given ThreadPool equals to num_threads * "
"tensorflow_num_threads_scale_factor. Default scale factor of 1 is a "
"no-op.");
#endif
namespace tsl {
namespace thread {
struct EigenEnvironment {
typedef Thread EnvThread;
struct TaskImpl {
std::function<void()> f;
Context context;
uint64 trace_id;
};
struct Task {
std::unique_ptr<TaskImpl> f;
};
Env* const env_;
const ThreadOptions thread_options_;
const string name_;
EigenEnvironment(Env* env, const ThreadOptions& thread_options,
const string& name)
: env_(env), thread_options_(thread_options), name_(name) {}
EnvThread* CreateThread(std::function<void()> f) {
return env_->StartThread(thread_options_, name_, [=]() {
port::ScopedFlushDenormal flush;
tsl::port::ScopedSetRound round(FE_TONEAREST);
if (thread_options_.numa_node != port::kNUMANoAffinity) {
port::NUMASetThreadNodeAffinity(thread_options_.numa_node);
}
f();
});
}
Task CreateTask(std::function<void()> f) {
uint64 id = 0;
if (tracing::EventCollector::IsEnabled()) {
id = tracing::GetUniqueArg();
tracing::RecordEvent(tracing::EventCategory::kScheduleClosure, id);
}
return Task{
std::unique_ptr<TaskImpl>(new TaskImpl{
std::move(f),
Context(ContextKind::kThread),
id,
}),
};
}
void ExecuteTask(const Task& t) {
WithContext wc(t.f->context);
tracing::ScopedRegion region(tracing::EventCategory::kRunClosure,
t.f->trace_id);
t.f->f();
}
};
ThreadPool::ThreadPool(Env* env, const string& name, int num_threads)
: ThreadPool(env, ThreadOptions(), name, num_threads, true, nullptr) {}
ThreadPool::ThreadPool(Env* env, const ThreadOptions& thread_options,
const string& name, int num_threads)
: ThreadPool(env, thread_options, name, num_threads, true, nullptr) {}
ThreadPool::ThreadPool(Env* env, const ThreadOptions& thread_options,
const string& name, int num_threads,
bool low_latency_hint, Eigen::Allocator* allocator) {
CHECK_GE(num_threads, 1);
#ifdef DNNL_AARCH64_USE_ACL
if (num_threads == tsl::port::NumTotalCPUs() && num_threads >= 16) {
num_threads = num_threads - 1;
}
#endif
#ifdef TENSORFLOW_THREADSCALING_EXPERIMENTAL
CHECK_GT(absl::GetFlag(FLAGS_tensorflow_num_threads_scale_factor), 0);
num_threads *= absl::GetFlag(FLAGS_tensorflow_num_threads_scale_factor);
if (num_threads < 1) num_threads = 1;
#endif
eigen_threadpool_.reset(new Eigen::ThreadPoolTempl<EigenEnvironment>(
num_threads, low_latency_hint,
EigenEnvironment(env, thread_options, "tf_" + name)));
underlying_threadpool_ = eigen_threadpool_.get();
threadpool_device_.reset(new Eigen::ThreadPoolDevice(underlying_threadpool_,
num_threads, allocator));
}
ThreadPool::ThreadPool(thread::ThreadPoolInterface* user_threadpool) {
underlying_threadpool_ = user_threadpool;
threadpool_device_.reset(new Eigen::ThreadPoolDevice(
underlying_threadpool_, underlying_threadpool_->NumThreads(), nullptr));
}
ThreadPool::~ThreadPool() {}
void ThreadPool::Schedule(std::function<void()> fn) {
CHECK(fn != nullptr);
underlying_threadpool_->Schedule(std::move(fn));
}
int ThreadPool::NumShardsUsedByFixedBlockSizeScheduling(
const int64_t total, const int64_t block_size) {
if (block_size <= 0 || total <= 1 || total <= block_size ||
NumThreads() == 1) {
return 1;
}
return (total + block_size - 1) / block_size;
}
int ThreadPool::NumShardsUsedByTransformRangeConcurrently(
const int64_t block_size, const int64_t total) {
return NumShardsUsedByFixedBlockSizeScheduling(total, block_size);
}
void ThreadPool::ParallelFor(int64_t total,
const SchedulingParams& scheduling_params,
const std::function<void(int64_t, int64_t)>& fn) {
switch (scheduling_params.strategy()) {
case SchedulingStrategy::kAdaptive: {
if (scheduling_params.cost_per_unit().has_value()) {
ParallelFor(total, *scheduling_params.cost_per_unit(), fn);
}
break;
}
case SchedulingStrategy::kFixedBlockSize: {
if (scheduling_params.block_size().has_value()) {
ParallelForFixedBlockSizeScheduling(
total, *scheduling_params.block_size(), fn);
}
break;
}
}
}
void ThreadPool::TransformRangeConcurrently(
const int64_t block_size, const int64_t total,
const std::function<void(int64_t, int64_t)>& fn) {
ParallelFor(total,
SchedulingParams(SchedulingStrategy::kFixedBlockSize,
absl::nullopt , block_size),
fn);
}
void ThreadPool::ParallelForFixedBlockSizeScheduling(
const int64_t total, const int64_t block_size,
const std::function<void(int64_t, int64_t)>& fn) {
const int num_shards_used =
NumShardsUsedByFixedBlockSizeScheduling(total, block_size);
if (num_shards_used == 1) {
fn(0, total);
return;
}
BlockingCounter counter(num_shards_used);
std::function<void(int64_t, int64_t)> handle_range =
[=, &handle_range, &counter, &fn](int64_t first, int64_t last) {
while (last - first > block_size) {
const int64_t mid = first + ((last - first) / 2 + block_size - 1) /
block_size * block_size;
Schedule([=, &handle_range]() { handle_range(mid, last); });
last = mid;
}
fn(first, last);
counter.DecrementCount();
};
if (num_shards_used <= NumThreads()) {
handle_range(0, total);
} else {
Schedule([=, &handle_range]() { handle_range(0, total); });
}
counter.Wait();
}
void ThreadPool::ParallelFor(int64_t total, int64_t cost_per_unit,
const std::function<void(int64_t, int64_t)>& fn) {
CHECK_GE(total, 0);
CHECK_EQ(total, (int64_t)(Eigen::Index)total);
threadpool_device_->parallelFor(
total, Eigen::TensorOpCost(0, 0, cost_per_unit),
[&fn](Eigen::Index first, Eigen::Index last) { fn(first, last); });
}
void ThreadPool::ParallelForWithWorkerId(
int64_t total, int64_t cost_per_unit,
const std::function<void(int64_t, int64_t, int)>& fn) {
CHECK_GE(total, 0);
CHECK_EQ(total, (int64_t)(Eigen::Index)total);
threadpool_device_->parallelFor(total,
Eigen::TensorOpCost(0, 0, cost_per_unit),
[this, &fn](int64_t start, int64_t limit) {
int id = CurrentThreadId() + 1;
fn(start, limit, id);
});
}
void ThreadPool::ParallelForWithWorkerId(
int64_t total, const SchedulingParams& scheduling_params,
const std::function<void(int64_t, int64_t, int)>& fn) {
ParallelFor(total, scheduling_params,
[this, &fn](int64_t start, int64_t limit) {
int id = CurrentThreadId() + 1;
fn(start, limit, id);
});
}
int ThreadPool::NumThreads() const {
return underlying_threadpool_->NumThreads();
}
int ThreadPool::CurrentThreadId() const {
return underlying_threadpool_->CurrentThreadId();
}
void ThreadPool::ScheduleWithHint(std::function<void()> fn, int start,
int limit) {
underlying_threadpool_->ScheduleWithHint(std::move(fn), start, limit);
}
void ThreadPool::SetStealPartitions(
const std::vector<std::pair<unsigned, unsigned>>& partitions) {
DCHECK(eigen_threadpool_ != nullptr);
eigen_threadpool_->SetStealPartitions(partitions);
}
Eigen::ThreadPoolInterface* ThreadPool::AsEigenThreadPool() const {
DCHECK(underlying_threadpool_ != nullptr);
return underlying_threadpool_;
}
}
} | #include "tensorflow/core/lib/core/threadpool.h"
#include <atomic>
#include <optional>
#include "absl/synchronization/barrier.h"
#include "absl/synchronization/blocking_counter.h"
#include "absl/types/optional.h"
#include "tensorflow/core/platform/context.h"
#include "tensorflow/core/platform/env.h"
#include "tensorflow/core/platform/mutex.h"
#include "tensorflow/core/platform/test.h"
#include "tensorflow/core/platform/test_benchmark.h"
namespace tensorflow {
namespace thread {
static const int kNumThreads = 30;
TEST(ThreadPool, Empty) {
for (int num_threads = 1; num_threads < kNumThreads; num_threads++) {
fprintf(stderr, "Testing with %d threads\n", num_threads);
ThreadPool pool(Env::Default(), "test", num_threads);
}
}
TEST(ThreadPool, DoWork) {
Context outer_context(ContextKind::kThread);
for (int num_threads = 1; num_threads < kNumThreads; num_threads++) {
fprintf(stderr, "Testing with %d threads\n", num_threads);
const int kWorkItems = 15;
std::atomic<bool> work[kWorkItems];
for (int i = 0; i < kWorkItems; i++) {
work[i] = false;
}
{
ThreadPool pool(Env::Default(), "test", num_threads);
for (int i = 0; i < kWorkItems; i++) {
pool.Schedule([&outer_context, &work, i]() {
Context inner_context(ContextKind::kThread);
ASSERT_EQ(outer_context, inner_context);
ASSERT_FALSE(work[i].exchange(true));
});
}
}
for (int i = 0; i < kWorkItems; i++) {
ASSERT_TRUE(work[i]);
}
}
}
void RunWithFixedBlockSize(int64_t block_size, int64_t total,
ThreadPool* threads) {
mutex mu;
int64_t num_shards = 0;
int64_t num_done_work = 0;
std::vector<std::atomic<bool>> work(total);
for (int i = 0; i < total; i++) {
work[i] = false;
}
threads->ParallelFor(
total,
ThreadPool::SchedulingParams(
ThreadPool::SchedulingStrategy::kFixedBlockSize ,
std::nullopt , block_size ),
[=, &mu, &num_shards, &num_done_work, &work](int64_t start, int64_t end) {
VLOG(1) << "Shard [" << start << "," << end << ")";
EXPECT_GE(start, 0);
EXPECT_LE(end, total);
mutex_lock l(mu);
++num_shards;
for (; start < end; ++start) {
EXPECT_FALSE(work[start].exchange(true));
++num_done_work;
}
});
EXPECT_EQ(num_done_work, total);
for (int i = 0; i < total; i++) {
ASSERT_TRUE(work[i]);
}
const int64_t num_workers = (total + block_size - 1) / block_size;
if (num_workers < threads->NumThreads()) {
EXPECT_LE(num_shards, 1 + num_workers);
}
}
TEST(ThreadPoolTest, ParallelForFixedBlockSizeScheduling) {
ThreadPool threads(Env::Default(), "test", 16);
for (auto block_size : {1, 7, 10, 64, 100, 256, 1000, 9999}) {
for (auto diff : {0, 1, 11, 102, 1003, 10005, 1000007}) {
const int64_t total = block_size + diff;
RunWithFixedBlockSize(block_size, total, &threads);
}
}
}
void RunWithFixedBlockSizeTransformRangeConcurrently(int64_t block_size,
int64_t total,
ThreadPool* threads) {
mutex mu;
int64_t num_shards = 0;
int64_t num_done_work = 0;
std::vector<std::atomic<bool>> work(total);
for (int i = 0; i < total; i++) {
work[i] = false;
}
threads->TransformRangeConcurrently(
block_size, total,
[=, &mu, &num_shards, &num_done_work, &work](int64_t start, int64_t end) {
VLOG(1) << "Shard [" << start << "," << end << ")";
EXPECT_GE(start, 0);
EXPECT_LE(end, total);
mutex_lock l(mu);
++num_shards;
for (; start < end; ++start) {
EXPECT_FALSE(work[start].exchange(true));
++num_done_work;
}
});
EXPECT_EQ(num_done_work, total);
for (int i = 0; i < total; i++) {
ASSERT_TRUE(work[i]);
}
const int64_t num_workers = (total + block_size - 1) / block_size;
if (num_workers < threads->NumThreads()) {
EXPECT_LE(num_shards, 1 + num_workers);
}
}
TEST(ThreadPoolTest, TransformRangeConcurrently) {
ThreadPool threads(Env::Default(), "test", 16);
for (auto block_size : {1, 7, 10, 64, 100, 256, 1000, 9999}) {
for (auto diff : {0, 1, 11, 102, 1003, 10005, 1000007}) {
const int64_t total = block_size + diff;
RunWithFixedBlockSizeTransformRangeConcurrently(block_size, total,
&threads);
}
}
}
TEST(ThreadPoolTest, NumShardsUsedByFixedBlockSizeScheduling) {
ThreadPool threads(Env::Default(), "test", 16);
EXPECT_EQ(1, threads.NumShardsUsedByFixedBlockSizeScheduling(
3 , 3 ));
EXPECT_EQ(2, threads.NumShardsUsedByFixedBlockSizeScheduling(
4 , 3 ));
EXPECT_EQ(2, threads.NumShardsUsedByFixedBlockSizeScheduling(
5 , 3 ));
EXPECT_EQ(2, threads.NumShardsUsedByFixedBlockSizeScheduling(
6 , 3 ));
EXPECT_EQ(3, threads.NumShardsUsedByFixedBlockSizeScheduling(
7 , 3 ));
EXPECT_EQ(7, threads.NumShardsUsedByFixedBlockSizeScheduling(
7 , 1 ));
EXPECT_EQ(1, threads.NumShardsUsedByFixedBlockSizeScheduling(
7 , 0 ));
}
TEST(ThreadPoolTest, NumShardsUsedByTransformRangeConcurrently) {
ThreadPool threads(Env::Default(), "test", 16);
EXPECT_EQ(1, threads.NumShardsUsedByTransformRangeConcurrently(
3 , 3 ));
EXPECT_EQ(2, threads.NumShardsUsedByTransformRangeConcurrently(
3 , 4 ));
EXPECT_EQ(2, threads.NumShardsUsedByTransformRangeConcurrently(
3 , 5 ));
EXPECT_EQ(2, threads.NumShardsUsedByTransformRangeConcurrently(
3 , 6 ));
EXPECT_EQ(3, threads.NumShardsUsedByTransformRangeConcurrently(
3 , 7 ));
EXPECT_EQ(7, threads.NumShardsUsedByTransformRangeConcurrently(
1 , 7 ));
EXPECT_EQ(1, threads.NumShardsUsedByTransformRangeConcurrently(
0 , 7 ));
}
void RunFixedBlockSizeShardingWithWorkerId(int64_t block_size, int64_t total,
ThreadPool* threads) {
mutex mu;
int64_t num_done_work = 0;
std::vector<std::atomic<bool>> work(total);
for (int i = 0; i < total; i++) {
work[i] = false;
}
const int64_t num_threads = threads->NumThreads();
std::vector<std::atomic<bool>> threads_running(num_threads + 1);
for (int i = 0; i < num_threads + 1; i++) {
threads_running[i] = false;
}
threads->ParallelForWithWorkerId(
total,
ThreadPool::SchedulingParams(
ThreadPool::SchedulingStrategy::kFixedBlockSize ,
std::nullopt , block_size ),
[=, &mu, &num_done_work, &work, &threads_running](int64_t start,
int64_t end, int id) {
VLOG(1) << "Shard [" << start << "," << end << ")";
EXPECT_GE(start, 0);
EXPECT_LE(end, total);
EXPECT_GE(id, 0);
EXPECT_LE(id, num_threads);
EXPECT_FALSE(threads_running[id].exchange(true));
mutex_lock l(mu);
for (; start < end; ++start) {
EXPECT_FALSE(work[start].exchange(true));
++num_done_work;
}
EXPECT_TRUE(threads_running[id].exchange(false));
});
EXPECT_EQ(num_done_work, total);
for (int i = 0; i < total; i++) {
EXPECT_TRUE(work[i]);
}
}
TEST(ThreadPoolTest, ParallelForFixedBlockSizeSchedulingWithWorkerId) {
for (int32_t num_threads : {1, 2, 3, 9, 16, 31}) {
ThreadPool threads(Env::Default(), "test", num_threads);
for (int64_t block_size : {1, 7, 10, 64, 100, 256, 1000}) {
for (int64_t diff : {0, 1, 11, 102, 1003}) {
const int64_t total = block_size + diff;
RunFixedBlockSizeShardingWithWorkerId(block_size, total, &threads);
}
}
}
}
TEST(ThreadPool, ParallelFor) {
Context outer_context(ContextKind::kThread);
int64_t kHugeCost = 1 << 30;
for (int num_threads = 1; num_threads < kNumThreads; num_threads++) {
fprintf(stderr, "Testing with %d threads\n", num_threads);
const int kWorkItems = 15;
std::atomic<bool> work[kWorkItems];
ThreadPool pool(Env::Default(), "test", num_threads);
for (int i = 0; i < kWorkItems; i++) {
work[i] = false;
}
pool.ParallelFor(kWorkItems, kHugeCost,
[&outer_context, &work](int64_t begin, int64_t end) {
Context inner_context(ContextKind::kThread);
ASSERT_EQ(outer_context, inner_context);
for (int64_t i = begin; i < end; ++i) {
ASSERT_FALSE(work[i].exchange(true));
}
});
for (int i = 0; i < kWorkItems; i++) {
ASSERT_TRUE(work[i]);
}
}
}
TEST(ThreadPool, ParallelForWithAdaptiveSchedulingStrategy) {
Context outer_context(ContextKind::kThread);
int64_t kHugeCost = 1 << 30;
for (int num_threads = 1; num_threads < kNumThreads; num_threads++) {
fprintf(stderr, "Testing with %d threads\n", num_threads);
const int kWorkItems = 15;
std::atomic<bool> work[kWorkItems];
ThreadPool pool(Env::Default(), "test", num_threads);
for (int i = 0; i < kWorkItems; i++) {
work[i] = false;
}
pool.ParallelFor(
kWorkItems,
ThreadPool::SchedulingParams(
ThreadPool::SchedulingStrategy::kAdaptive ,
kHugeCost , std::nullopt ),
[&outer_context, &work](int64_t begin, int64_t end) {
Context inner_context(ContextKind::kThread);
ASSERT_EQ(outer_context, inner_context);
for (int64_t i = begin; i < end; ++i) {
ASSERT_FALSE(work[i].exchange(true));
}
});
for (int i = 0; i < kWorkItems; i++) {
ASSERT_TRUE(work[i]);
}
}
}
TEST(ThreadPool, ParallelForWithWorkerId) {
int64_t kHugeCost = 1 << 30;
for (int num_threads = 1; num_threads < kNumThreads; num_threads++) {
fprintf(stderr, "Testing with %d threads\n", num_threads);
const int kWorkItems = 15;
std::atomic<bool> work[kWorkItems];
ThreadPool pool(Env::Default(), "test", num_threads);
for (int i = 0; i < kWorkItems; i++) {
work[i] = false;
}
std::atomic<bool> threads_running[kNumThreads + 1];
for (int i = 0; i < num_threads + 1; i++) {
threads_running[i] = false;
}
pool.ParallelForWithWorkerId(
kWorkItems, kHugeCost,
[&threads_running, &work](int64_t begin, int64_t end, int64_t id) {
ASSERT_LE(0, id);
ASSERT_LE(id, kNumThreads);
ASSERT_FALSE(threads_running[id].exchange(true));
for (int64_t i = begin; i < end; ++i) {
ASSERT_FALSE(work[i].exchange(true));
}
ASSERT_TRUE(threads_running[id].exchange(false));
threads_running[id] = false;
});
for (int i = 0; i < kWorkItems; i++) {
ASSERT_TRUE(work[i]);
}
for (int i = 0; i < num_threads + 1; i++) {
ASSERT_FALSE(threads_running[i]);
}
}
}
TEST(ThreadPool, Parallelism) {
ThreadPool pool(Env::Default(), "test", kNumThreads);
for (int iter = 0; iter < 2000; iter++) {
absl::Barrier barrier(kNumThreads);
absl::BlockingCounter counter(kNumThreads);
for (int t = 0; t < kNumThreads; ++t) {
pool.Schedule([&]() {
barrier.Block();
counter.DecrementCount();
});
}
counter.Wait();
}
}
static void BM_Sequential(::testing::benchmark::State& state) {
for (auto s : state) {
state.PauseTiming();
ThreadPool pool(Env::Default(), "test", kNumThreads);
int count = state.range(0);
mutex done_lock;
bool done_flag = false;
std::function<void()> work = [&pool, &count, &done_lock, &done_flag,
&work]() {
if (count--) {
pool.Schedule(work);
} else {
mutex_lock l(done_lock);
done_flag = true;
}
};
state.ResumeTiming();
work();
mutex_lock l(done_lock);
done_lock.Await(Condition(&done_flag));
}
}
BENCHMARK(BM_Sequential)->Arg(200)->Arg(300);
static void BM_Parallel(::testing::benchmark::State& state) {
ThreadPool pool(Env::Default(), "test", kNumThreads);
std::atomic_int_fast32_t count(state.max_iterations);
mutex done_lock;
bool done_flag = false;
for (auto s : state) {
pool.Schedule([&count, &done_lock, &done_flag]() {
if (count.fetch_sub(1) == 1) {
mutex_lock l(done_lock);
done_flag = true;
}
});
}
mutex_lock l(done_lock);
done_lock.Await(Condition(&done_flag));
}
BENCHMARK(BM_Parallel);
static void BM_ParallelFor(::testing::benchmark::State& state) {
int total = state.range(0);
int cost_per_unit = state.range(1);
ThreadPool pool(Env::Default(), "test", kNumThreads);
std::atomic_int_fast32_t count(state.max_iterations);
mutex done_lock;
bool done_flag = false;
for (auto s : state) {
pool.ParallelFor(
total, cost_per_unit,
[&count, &done_lock, &done_flag](int64_t begin, int64_t end) {
for (int64_t i = begin; i < end; ++i) {
if (count.fetch_sub(1) == 1) {
mutex_lock l(done_lock);
done_flag = true;
}
}
});
mutex_lock l(done_lock);
done_lock.Await(Condition(&done_flag));
}
}
BENCHMARK(BM_ParallelFor)
->ArgPair(1 << 10, 1)
->ArgPair(1 << 20, 1)
->ArgPair(1 << 10, 1 << 10)
->ArgPair(1 << 20, 1 << 10)
->ArgPair(1 << 10, 1 << 20)
->ArgPair(1 << 20, 1 << 20)
->ArgPair(1 << 10, 1 << 30)
->ArgPair(1 << 20, 1 << 30);
}
} | 2,267 |
#ifndef TENSORFLOW_TSL_PLATFORM_STR_UTIL_H_
#define TENSORFLOW_TSL_PLATFORM_STR_UTIL_H_
#include <cstdint>
#include <string>
#include <vector>
#include "absl/strings/str_join.h"
#include "absl/strings/str_split.h"
#include "tsl/platform/macros.h"
#include "tsl/platform/stringpiece.h"
#include "tsl/platform/types.h"
namespace tsl {
namespace str_util {
std::string CEscape(StringPiece src);
bool CUnescape(StringPiece source, std::string* dest, std::string* error);
void StripTrailingWhitespace(std::string* s);
size_t RemoveLeadingWhitespace(StringPiece* text);
size_t RemoveTrailingWhitespace(StringPiece* text);
size_t RemoveWhitespaceContext(StringPiece* text);
bool ConsumeLeadingDigits(StringPiece* s, uint64_t* val);
bool ConsumeNonWhitespace(StringPiece* s, StringPiece* val);
bool ConsumePrefix(StringPiece* s, StringPiece expected);
bool ConsumeSuffix(StringPiece* s, StringPiece expected);
TF_MUST_USE_RESULT StringPiece StripPrefix(StringPiece s, StringPiece expected);
TF_MUST_USE_RESULT StringPiece StripSuffix(StringPiece s, StringPiece expected);
std::string Lowercase(StringPiece s);
std::string Uppercase(StringPiece s);
void TitlecaseString(std::string* s, StringPiece delimiters);
std::string StringReplace(StringPiece s, StringPiece oldsub, StringPiece newsub,
bool replace_all);
template <typename T>
std::string Join(const T& s, const char* sep) {
return absl::StrJoin(s, sep);
}
template <typename T, typename Formatter>
std::string Join(const T& s, const char* sep, Formatter f) {
return absl::StrJoin(s, sep, f);
}
struct AllowEmpty {
bool operator()(StringPiece sp) const { return true; }
};
struct SkipEmpty {
bool operator()(StringPiece sp) const { return !sp.empty(); }
};
struct SkipWhitespace {
bool operator()(StringPiece sp) const {
return !absl::StripTrailingAsciiWhitespace(sp).empty();
}
};
inline std::vector<string> Split(StringPiece text, StringPiece delims) {
return text.empty() ? std::vector<string>()
: absl::StrSplit(text, absl::ByAnyChar(delims));
}
template <typename Predicate>
std::vector<string> Split(StringPiece text, StringPiece delims, Predicate p) {
return text.empty() ? std::vector<string>()
: absl::StrSplit(text, absl::ByAnyChar(delims), p);
}
inline std::vector<string> Split(StringPiece text, char delim) {
return text.empty() ? std::vector<string>() : absl::StrSplit(text, delim);
}
template <typename Predicate>
std::vector<string> Split(StringPiece text, char delim, Predicate p) {
return text.empty() ? std::vector<string>() : absl::StrSplit(text, delim, p);
}
bool StartsWith(StringPiece text, StringPiece prefix);
bool EndsWith(StringPiece text, StringPiece suffix);
bool StrContains(StringPiece haystack, StringPiece needle);
size_t Strnlen(const char* str, const size_t string_max_len);
std::string ArgDefCase(StringPiece s);
}
}
#endif
#include "tsl/platform/str_util.h"
#include <cctype>
#include <cstdint>
#include <string>
#include <vector>
#include "absl/strings/ascii.h"
#include "absl/strings/escaping.h"
#include "absl/strings/match.h"
#include "absl/strings/strip.h"
#include "tsl/platform/logging.h"
#include "tsl/platform/stringpiece.h"
namespace tsl {
namespace str_util {
string CEscape(StringPiece src) { return absl::CEscape(src); }
bool CUnescape(StringPiece source, string* dest, string* error) {
return absl::CUnescape(source, dest, error);
}
void StripTrailingWhitespace(string* s) {
absl::StripTrailingAsciiWhitespace(s);
}
size_t RemoveLeadingWhitespace(StringPiece* text) {
absl::string_view new_text = absl::StripLeadingAsciiWhitespace(*text);
size_t count = text->size() - new_text.size();
*text = new_text;
return count;
}
size_t RemoveTrailingWhitespace(StringPiece* text) {
absl::string_view new_text = absl::StripTrailingAsciiWhitespace(*text);
size_t count = text->size() - new_text.size();
*text = new_text;
return count;
}
size_t RemoveWhitespaceContext(StringPiece* text) {
absl::string_view new_text = absl::StripAsciiWhitespace(*text);
size_t count = text->size() - new_text.size();
*text = new_text;
return count;
}
bool ConsumeLeadingDigits(StringPiece* s, uint64_t* val) {
const char* p = s->data();
const char* limit = p + s->size();
uint64_t v = 0;
while (p < limit) {
const char c = *p;
if (c < '0' || c > '9') break;
uint64_t new_v = (v * 10) + (c - '0');
if (new_v / 8 < v) {
return false;
}
v = new_v;
p++;
}
if (p > s->data()) {
s->remove_prefix(p - s->data());
*val = v;
return true;
} else {
return false;
}
}
bool ConsumeNonWhitespace(StringPiece* s, StringPiece* val) {
const char* p = s->data();
const char* limit = p + s->size();
while (p < limit) {
const char c = *p;
if (isspace(c)) break;
p++;
}
const size_t n = p - s->data();
if (n > 0) {
*val = StringPiece(s->data(), n);
s->remove_prefix(n);
return true;
} else {
*val = StringPiece();
return false;
}
}
bool ConsumePrefix(StringPiece* s, StringPiece expected) {
return absl::ConsumePrefix(s, expected);
}
bool ConsumeSuffix(StringPiece* s, StringPiece expected) {
return absl::ConsumeSuffix(s, expected);
}
StringPiece StripPrefix(StringPiece s, StringPiece expected) {
return absl::StripPrefix(s, expected);
}
StringPiece StripSuffix(StringPiece s, StringPiece expected) {
return absl::StripSuffix(s, expected);
}
string Lowercase(StringPiece s) { return absl::AsciiStrToLower(s); }
string Uppercase(StringPiece s) { return absl::AsciiStrToUpper(s); }
void TitlecaseString(string* s, StringPiece delimiters) {
bool upper = true;
for (string::iterator ss = s->begin(); ss != s->end(); ++ss) {
if (upper) {
*ss = toupper(*ss);
}
upper = (delimiters.find(*ss) != StringPiece::npos);
}
}
string StringReplace(StringPiece s, StringPiece oldsub, StringPiece newsub,
bool replace_all) {
string res(s);
size_t pos = 0;
while ((pos = res.find(oldsub.data(), pos, oldsub.size())) != string::npos) {
res.replace(pos, oldsub.size(), newsub.data(), newsub.size());
pos += newsub.size();
if (oldsub.empty()) {
pos++;
}
if (!replace_all) {
break;
}
}
return res;
}
bool StartsWith(StringPiece text, StringPiece prefix) {
return absl::StartsWith(text, prefix);
}
bool EndsWith(StringPiece text, StringPiece suffix) {
return absl::EndsWith(text, suffix);
}
bool StrContains(StringPiece haystack, StringPiece needle) {
return absl::StrContains(haystack, needle);
}
size_t Strnlen(const char* str, const size_t string_max_len) {
size_t len = 0;
while (len < string_max_len && str[len] != '\0') {
++len;
}
return len;
}
string ArgDefCase(StringPiece s) {
const size_t n = s.size();
size_t extra_us = 0;
size_t to_skip = 0;
for (size_t i = 0; i < n; ++i) {
if (i == to_skip && !isalpha(s[i])) {
++to_skip;
continue;
}
if (isupper(s[i]) && i != to_skip && i > 0 && isalnum(s[i - 1])) {
++extra_us;
}
}
string result(n + extra_us - to_skip, '_');
for (size_t i = to_skip, j = 0; i < n; ++i, ++j) {
DCHECK_LT(j, result.size());
char c = s[i];
if (isalnum(c)) {
if (isupper(c)) {
if (i != to_skip) {
DCHECK_GT(j, 0);
if (result[j - 1] != '_') ++j;
}
result[j] = tolower(c);
} else {
result[j] = c;
}
}
}
return result;
}
}
} | #include "tsl/platform/str_util.h"
#include <vector>
#include "tsl/platform/test.h"
namespace tsl {
TEST(CEscape, Basic) {
EXPECT_EQ(str_util::CEscape("hello"), "hello");
EXPECT_EQ(str_util::CEscape("hello\n"), "hello\\n");
EXPECT_EQ(str_util::CEscape("hello\r"), "hello\\r");
EXPECT_EQ(str_util::CEscape("\t\r\"'"), "\\t\\r\\\"\\'");
EXPECT_EQ(str_util::CEscape("\320hi\200"), "\\320hi\\200");
}
string ExpectCUnescapeSuccess(StringPiece source) {
string dest;
string error;
EXPECT_TRUE(str_util::CUnescape(source, &dest, &error)) << error;
return dest;
}
TEST(CUnescape, Basic) {
EXPECT_EQ("hello", ExpectCUnescapeSuccess("hello"));
EXPECT_EQ("hello\n", ExpectCUnescapeSuccess("hello\\n"));
EXPECT_EQ("hello\r", ExpectCUnescapeSuccess("hello\\r"));
EXPECT_EQ("\t\r\"'", ExpectCUnescapeSuccess("\\t\\r\\\"\\'"));
EXPECT_EQ("\320hi\200", ExpectCUnescapeSuccess("\\320hi\\200"));
}
TEST(CUnescape, HandlesCopyOnWriteStrings) {
string dest = "hello";
string read = dest;
string error;
StringPiece source = "llohe";
EXPECT_TRUE(str_util::CUnescape(source, &dest, &error));
EXPECT_EQ("hello", read);
}
TEST(StripTrailingWhitespace, Basic) {
string test;
test = "hello";
str_util::StripTrailingWhitespace(&test);
EXPECT_EQ(test, "hello");
test = "foo ";
str_util::StripTrailingWhitespace(&test);
EXPECT_EQ(test, "foo");
test = " ";
str_util::StripTrailingWhitespace(&test);
EXPECT_EQ(test, "");
test = "";
str_util::StripTrailingWhitespace(&test);
EXPECT_EQ(test, "");
test = " abc\t";
str_util::StripTrailingWhitespace(&test);
EXPECT_EQ(test, " abc");
}
TEST(RemoveLeadingWhitespace, Basic) {
string text = " \t \n \r Quick\t";
StringPiece data(text);
EXPECT_EQ(str_util::RemoveLeadingWhitespace(&data), 11);
EXPECT_EQ(data, StringPiece("Quick\t"));
EXPECT_EQ(str_util::RemoveLeadingWhitespace(&data), 0);
EXPECT_EQ(data, StringPiece("Quick\t"));
}
TEST(RemoveLeadingWhitespace, TerminationHandling) {
string text = "\t";
StringPiece data(text);
EXPECT_EQ(str_util::RemoveLeadingWhitespace(&data), 1);
EXPECT_EQ(data, StringPiece(""));
EXPECT_EQ(str_util::RemoveLeadingWhitespace(&data), 0);
EXPECT_EQ(data, StringPiece(""));
}
TEST(RemoveTrailingWhitespace, Basic) {
string text = " \t \n \r Quick \t";
StringPiece data(text);
EXPECT_EQ(str_util::RemoveTrailingWhitespace(&data), 2);
EXPECT_EQ(data, StringPiece(" \t \n \r Quick"));
EXPECT_EQ(str_util::RemoveTrailingWhitespace(&data), 0);
EXPECT_EQ(data, StringPiece(" \t \n \r Quick"));
}
TEST(RemoveTrailingWhitespace, TerminationHandling) {
string text = "\t";
StringPiece data(text);
EXPECT_EQ(str_util::RemoveTrailingWhitespace(&data), 1);
EXPECT_EQ(data, StringPiece(""));
EXPECT_EQ(str_util::RemoveTrailingWhitespace(&data), 0);
EXPECT_EQ(data, StringPiece(""));
}
TEST(RemoveWhitespaceContext, Basic) {
string text = " \t \n \r Quick \t";
StringPiece data(text);
EXPECT_EQ(str_util::RemoveWhitespaceContext(&data), 13);
EXPECT_EQ(data, StringPiece("Quick"));
EXPECT_EQ(str_util::RemoveWhitespaceContext(&data), 0);
EXPECT_EQ(data, StringPiece("Quick"));
text = "";
data = text;
EXPECT_EQ(str_util::RemoveWhitespaceContext(&data), 0);
EXPECT_EQ(data, StringPiece(""));
}
void TestConsumeLeadingDigits(StringPiece s, int64_t expected,
StringPiece remaining) {
uint64 v;
StringPiece input(s);
if (str_util::ConsumeLeadingDigits(&input, &v)) {
EXPECT_EQ(v, static_cast<uint64>(expected));
EXPECT_EQ(input, remaining);
} else {
EXPECT_LT(expected, 0);
EXPECT_EQ(input, remaining);
}
}
TEST(ConsumeLeadingDigits, Basic) {
using str_util::ConsumeLeadingDigits;
TestConsumeLeadingDigits("123", 123, "");
TestConsumeLeadingDigits("a123", -1, "a123");
TestConsumeLeadingDigits("9_", 9, "_");
TestConsumeLeadingDigits("11111111111xyz", 11111111111ll, "xyz");
TestConsumeLeadingDigits("1111111111111111111111111111111xyz", -1,
"1111111111111111111111111111111xyz");
TestConsumeLeadingDigits("18446744073709551616xyz", -1,
"18446744073709551616xyz");
TestConsumeLeadingDigits("18446744073709551615xyz", 18446744073709551615ull,
"xyz");
TestConsumeLeadingDigits("184467440737095516159yz", -1,
"184467440737095516159yz");
}
void TestConsumeNonWhitespace(StringPiece s, StringPiece expected,
StringPiece remaining) {
StringPiece v;
StringPiece input(s);
if (str_util::ConsumeNonWhitespace(&input, &v)) {
EXPECT_EQ(v, expected);
EXPECT_EQ(input, remaining);
} else {
EXPECT_EQ(expected, "");
EXPECT_EQ(input, remaining);
}
}
TEST(ConsumeNonWhitespace, Basic) {
TestConsumeNonWhitespace("", "", "");
TestConsumeNonWhitespace(" ", "", " ");
TestConsumeNonWhitespace("abc", "abc", "");
TestConsumeNonWhitespace("abc ", "abc", " ");
}
TEST(ConsumePrefix, Basic) {
string s("abcdef");
StringPiece input(s);
EXPECT_FALSE(str_util::ConsumePrefix(&input, "abcdefg"));
EXPECT_EQ(input, "abcdef");
EXPECT_FALSE(str_util::ConsumePrefix(&input, "abce"));
EXPECT_EQ(input, "abcdef");
EXPECT_TRUE(str_util::ConsumePrefix(&input, ""));
EXPECT_EQ(input, "abcdef");
EXPECT_FALSE(str_util::ConsumePrefix(&input, "abcdeg"));
EXPECT_EQ(input, "abcdef");
EXPECT_TRUE(str_util::ConsumePrefix(&input, "abcdef"));
EXPECT_EQ(input, "");
input = s;
EXPECT_TRUE(str_util::ConsumePrefix(&input, "abcde"));
EXPECT_EQ(input, "f");
}
TEST(StripPrefix, Basic) {
EXPECT_EQ(str_util::StripPrefix("abcdef", "abcdefg"), "abcdef");
EXPECT_EQ(str_util::StripPrefix("abcdef", "abce"), "abcdef");
EXPECT_EQ(str_util::StripPrefix("abcdef", ""), "abcdef");
EXPECT_EQ(str_util::StripPrefix("abcdef", "abcdeg"), "abcdef");
EXPECT_EQ(str_util::StripPrefix("abcdef", "abcdef"), "");
EXPECT_EQ(str_util::StripPrefix("abcdef", "abcde"), "f");
}
TEST(JoinStrings, Basic) {
std::vector<string> s;
s = {"hi"};
EXPECT_EQ(str_util::Join(s, " "), "hi");
s = {"hi", "there", "strings"};
EXPECT_EQ(str_util::Join(s, " "), "hi there strings");
std::vector<StringPiece> sp;
sp = {"hi"};
EXPECT_EQ(str_util::Join(sp, ",,"), "hi");
sp = {"hi", "there", "strings"};
EXPECT_EQ(str_util::Join(sp, "--"), "hi--there--strings");
}
TEST(JoinStrings, Join3) {
std::vector<string> s;
s = {"hi"};
auto l1 = [](string* out, string s) { *out += s; };
EXPECT_EQ(str_util::Join(s, " ", l1), "hi");
s = {"hi", "there", "strings"};
auto l2 = [](string* out, string s) { *out += s[0]; };
EXPECT_EQ(str_util::Join(s, " ", l2), "h t s");
}
TEST(Split, Basic) {
EXPECT_TRUE(str_util::Split("", ',').empty());
EXPECT_EQ(str_util::Join(str_util::Split("a", ','), "|"), "a");
EXPECT_EQ(str_util::Join(str_util::Split(",", ','), "|"), "|");
EXPECT_EQ(str_util::Join(str_util::Split("a,b,c", ','), "|"), "a|b|c");
EXPECT_EQ(str_util::Join(str_util::Split("a,,,b,,c,", ','), "|"),
"a|||b||c|");
EXPECT_EQ(str_util::Join(str_util::Split("a!,!b,!c,", ",!"), "|"),
"a|||b||c|");
EXPECT_EQ(str_util::Join(
str_util::Split("a,,,b,,c,", ',', str_util::SkipEmpty()), "|"),
"a|b|c");
EXPECT_EQ(
str_util::Join(
str_util::Split("a, ,b,,c,", ',', str_util::SkipWhitespace()), "|"),
"a|b|c");
EXPECT_EQ(str_util::Join(str_util::Split("a. !b,;c,", ".,;!",
str_util::SkipWhitespace()),
"|"),
"a|b|c");
}
TEST(Lowercase, Basic) {
EXPECT_EQ("", str_util::Lowercase(""));
EXPECT_EQ("hello", str_util::Lowercase("hello"));
EXPECT_EQ("hello world", str_util::Lowercase("Hello World"));
}
TEST(Uppercase, Basic) {
EXPECT_EQ("", str_util::Uppercase(""));
EXPECT_EQ("HELLO", str_util::Uppercase("hello"));
EXPECT_EQ("HELLO WORLD", str_util::Uppercase("Hello World"));
}
TEST(SnakeCase, Basic) {
EXPECT_EQ("", str_util::ArgDefCase(""));
EXPECT_EQ("", str_util::ArgDefCase("!"));
EXPECT_EQ("", str_util::ArgDefCase("5"));
EXPECT_EQ("", str_util::ArgDefCase("!:"));
EXPECT_EQ("", str_util::ArgDefCase("5-5"));
EXPECT_EQ("", str_util::ArgDefCase("_!"));
EXPECT_EQ("", str_util::ArgDefCase("_5"));
EXPECT_EQ("a", str_util::ArgDefCase("_a"));
EXPECT_EQ("a", str_util::ArgDefCase("_A"));
EXPECT_EQ("i", str_util::ArgDefCase("I"));
EXPECT_EQ("i", str_util::ArgDefCase("i"));
EXPECT_EQ("i_", str_util::ArgDefCase("I%"));
EXPECT_EQ("i_", str_util::ArgDefCase("i%"));
EXPECT_EQ("i", str_util::ArgDefCase("%I"));
EXPECT_EQ("i", str_util::ArgDefCase("-i"));
EXPECT_EQ("i", str_util::ArgDefCase("3i"));
EXPECT_EQ("i", str_util::ArgDefCase("32i"));
EXPECT_EQ("i3", str_util::ArgDefCase("i3"));
EXPECT_EQ("i_a3", str_util::ArgDefCase("i_A3"));
EXPECT_EQ("i_i", str_util::ArgDefCase("II"));
EXPECT_EQ("i_i", str_util::ArgDefCase("I_I"));
EXPECT_EQ("i__i", str_util::ArgDefCase("I__I"));
EXPECT_EQ("i_i_32", str_util::ArgDefCase("II-32"));
EXPECT_EQ("ii_32", str_util::ArgDefCase("Ii-32"));
EXPECT_EQ("hi_there", str_util::ArgDefCase("HiThere"));
EXPECT_EQ("hi_hi", str_util::ArgDefCase("Hi!Hi"));
EXPECT_EQ("hi_hi", str_util::ArgDefCase("HiHi"));
EXPECT_EQ("hihi", str_util::ArgDefCase("Hihi"));
EXPECT_EQ("hi_hi", str_util::ArgDefCase("Hi_Hi"));
}
TEST(TitlecaseString, Basic) {
string s = "sparse_lookup";
str_util::TitlecaseString(&s, "_");
ASSERT_EQ(s, "Sparse_Lookup");
s = "sparse_lookup";
str_util::TitlecaseString(&s, " ");
ASSERT_EQ(s, "Sparse_lookup");
s = "dense";
str_util::TitlecaseString(&s, " ");
ASSERT_EQ(s, "Dense");
}
TEST(StringReplace, Basic) {
EXPECT_EQ("XYZ_XYZ_XYZ", str_util::StringReplace("ABC_ABC_ABC", "ABC", "XYZ",
true));
}
TEST(StringReplace, OnlyFirst) {
EXPECT_EQ("XYZ_ABC_ABC", str_util::StringReplace("ABC_ABC_ABC", "ABC", "XYZ",
false));
}
TEST(StringReplace, IncreaseLength) {
EXPECT_EQ("a b c",
str_util::StringReplace("abc", "b", " b ", true));
}
TEST(StringReplace, IncreaseLengthMultipleMatches) {
EXPECT_EQ("a b b c",
str_util::StringReplace("abbc", "b", " b ", true));
}
TEST(StringReplace, NoChange) {
EXPECT_EQ("abc",
str_util::StringReplace("abc", "d", "X", true));
}
TEST(StringReplace, EmptyStringReplaceFirst) {
EXPECT_EQ("", str_util::StringReplace("", "a", "X", false));
}
TEST(StringReplace, EmptyStringReplaceAll) {
EXPECT_EQ("", str_util::StringReplace("", "a", "X", true));
}
TEST(Strnlen, Basic) {
EXPECT_EQ(0, str_util::Strnlen("ab", 0));
EXPECT_EQ(1, str_util::Strnlen("a", 1));
EXPECT_EQ(2, str_util::Strnlen("abcd", 2));
EXPECT_EQ(3, str_util::Strnlen("abc", 10));
EXPECT_EQ(4, str_util::Strnlen("a \t\n", 10));
}
} | 2,268 |
#ifndef TENSORFLOW_TSL_PLATFORM_BASE64_H_
#define TENSORFLOW_TSL_PLATFORM_BASE64_H_
#include <string>
#include "tsl/platform/status.h"
#include "tsl/platform/stringpiece.h"
namespace tsl {
template <typename T>
absl::Status Base64Encode(StringPiece source, bool with_padding, T* encoded);
template <typename T>
absl::Status Base64Encode(StringPiece source,
T* encoded);
template <typename T>
absl::Status Base64Decode(StringPiece data, T* decoded);
extern template Status Base64Decode<std::string>(StringPiece data,
std::string* decoded);
extern template Status Base64Encode<std::string>(StringPiece source,
std::string* encoded);
extern template Status Base64Encode<std::string>(StringPiece source,
bool with_padding,
std::string* encoded);
extern template Status Base64Decode<tstring>(StringPiece data,
tstring* decoded);
extern template Status Base64Encode<tstring>(StringPiece source,
tstring* encoded);
extern template Status Base64Encode<tstring>(StringPiece source,
bool with_padding,
tstring* encoded);
}
#endif
#include "tsl/platform/base64.h"
#include <cstring>
#include <memory>
#include "tsl/platform/errors.h"
#include "tsl/platform/macros.h"
#include "tsl/platform/status.h"
#include "tsl/platform/stringpiece.h"
#include "tsl/platform/types.h"
namespace tsl {
namespace {
constexpr int8 kBase64Bytes[128] = {
-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, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, 0x3E, -1, -1,
0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, -1, -1,
-1, -1, -1, -1, -1, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06,
0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12,
0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, -1, -1, -1, -1, 0x3F,
-1, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x24,
0x25, 0x26, 0x27, 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F, 0x30,
0x31, 0x32, 0x33, -1, -1, -1, -1, -1};
constexpr char kBase64UrlSafeChars[65] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
constexpr char kPadChar = '=';
inline uint32 Convert(char x) {
const int8_t y = kBase64Bytes[x & 0x7F] | (x & 0x80);
const int32_t z = static_cast<int32>(y);
return static_cast<uint32>(z);
}
absl::Status DecodeThreeChars(const char* codes, char* result) {
const uint32 packed = (Convert(codes[0]) << 18) | (Convert(codes[1]) << 12) |
(Convert(codes[2]) << 6) | (Convert(codes[3]));
if (TF_PREDICT_FALSE((packed & 0xFF000000) != 0)) {
return errors::InvalidArgument("Invalid character found in base64.");
}
result[0] = static_cast<char>(packed >> 16);
result[1] = static_cast<char>(packed >> 8);
result[2] = static_cast<char>(packed);
return absl::OkStatus();
}
}
template <typename T>
absl::Status Base64Decode(StringPiece data, T* decoded) {
if (decoded == nullptr) {
return errors::Internal("'decoded' cannot be nullptr.");
}
if (data.empty()) {
decoded->clear();
return absl::OkStatus();
}
const size_t max_decoded_size = 3 * (data.size() / 4) + 3;
std::unique_ptr<char[]> buffer(new char[max_decoded_size]);
char* current = buffer.get();
if (current == nullptr) {
return errors::ResourceExhausted(
"Failed to allocate buffer for decoded string.");
}
const char* b64 = data.data();
const char* end = data.data() + data.size();
while (end - b64 > 4) {
TF_RETURN_IF_ERROR(DecodeThreeChars(b64, current));
b64 += 4;
current += 3;
}
if (end - b64 == 4) {
if (b64[2] == kPadChar && b64[3] == kPadChar) {
end -= 2;
}
if (b64[2] != kPadChar && b64[3] == kPadChar) {
end -= 1;
}
}
const int remain = static_cast<int>(end - b64);
if (TF_PREDICT_FALSE(remain == 1)) {
return errors::InvalidArgument(
"Base64 string length cannot be 1 modulo 4.");
}
char tail[4] = {kBase64UrlSafeChars[0], kBase64UrlSafeChars[0],
kBase64UrlSafeChars[0], kBase64UrlSafeChars[0]};
std::memcpy(tail, b64, remain * sizeof(*b64));
TF_RETURN_IF_ERROR(DecodeThreeChars(tail, current));
current += remain - 1;
decoded->assign(buffer.get(), current - buffer.get());
return absl::OkStatus();
}
template <typename T>
absl::Status Base64Encode(StringPiece source, T* encoded) {
return Base64Encode(source, false, encoded);
}
template <typename T>
absl::Status Base64Encode(StringPiece source, bool with_padding, T* encoded) {
const char* const base64_chars = kBase64UrlSafeChars;
if (encoded == nullptr) {
return errors::Internal("'encoded' cannot be nullptr.");
}
const size_t max_encoded_size = 4 * (source.size() / 3) + 4;
std::unique_ptr<char[]> buffer(new char[max_encoded_size]);
char* current = buffer.get();
if (current == nullptr) {
return errors::ResourceExhausted(
"Failed to allocate buffer for encoded string.");
}
const char* data = source.data();
const char* const end = source.data() + source.size();
while (end - data >= 3) {
*current++ = base64_chars[(data[0] >> 2) & 0x3F];
*current++ =
base64_chars[((data[0] & 0x03) << 4) | ((data[1] >> 4) & 0x0F)];
*current++ =
base64_chars[((data[1] & 0x0F) << 2) | ((data[2] >> 6) & 0x03)];
*current++ = base64_chars[data[2] & 0x3F];
data += 3;
}
if (end - data == 2) {
*current++ = base64_chars[(data[0] >> 2) & 0x3F];
*current++ =
base64_chars[((data[0] & 0x03) << 4) | ((data[1] >> 4) & 0x0F)];
*current++ = base64_chars[(data[1] & 0x0F) << 2];
if (with_padding) {
*current++ = kPadChar;
}
} else if (end - data == 1) {
*current++ = base64_chars[(data[0] >> 2) & 0x3F];
*current++ = base64_chars[(data[0] & 0x03) << 4];
if (with_padding) {
*current++ = kPadChar;
*current++ = kPadChar;
}
}
encoded->assign(buffer.get(), current - buffer.get());
return absl::OkStatus();
}
template Status Base64Decode<std::string>(StringPiece data,
std::string* decoded);
template Status Base64Encode<std::string>(StringPiece source,
std::string* encoded);
template Status Base64Encode<std::string>(StringPiece source, bool with_padding,
std::string* encoded);
template Status Base64Decode<tstring>(StringPiece data, tstring* decoded);
template Status Base64Encode<tstring>(StringPiece source, tstring* encoded);
template Status Base64Encode<tstring>(StringPiece source, bool with_padding,
tstring* encoded);
} | #include "tensorflow/core/lib/strings/base64.h"
#include "tensorflow/core/lib/core/status_test_util.h"
#include "tensorflow/core/platform/test.h"
namespace tensorflow {
TEST(Base64, EncodeDecode) {
const string original = "a simple test message!";
tstring encoded;
TF_EXPECT_OK(Base64Encode(original, &encoded));
EXPECT_EQ("YSBzaW1wbGUgdGVzdCBtZXNzYWdlIQ", encoded);
tstring decoded;
TF_EXPECT_OK(Base64Decode(encoded, &decoded));
EXPECT_EQ(original, decoded);
}
} | 2,269 |
#ifndef TENSORFLOW_TSL_PLATFORM_STRCAT_H_
#define TENSORFLOW_TSL_PLATFORM_STRCAT_H_
#include <string>
#include "tsl/platform/macros.h"
#include "tsl/platform/numbers.h"
#include "tsl/platform/stringpiece.h"
#include "tsl/platform/types.h"
namespace tsl {
namespace strings {
enum PadSpec {
kNoPad = 1,
kZeroPad2,
kZeroPad3,
kZeroPad4,
kZeroPad5,
kZeroPad6,
kZeroPad7,
kZeroPad8,
kZeroPad9,
kZeroPad10,
kZeroPad11,
kZeroPad12,
kZeroPad13,
kZeroPad14,
kZeroPad15,
kZeroPad16
};
struct Hex {
uint64 value;
enum PadSpec spec;
template <class Int>
explicit Hex(Int v, PadSpec s = kNoPad) : spec(s) {
static_assert(
sizeof(v) == 1 || sizeof(v) == 2 || sizeof(v) == 4 || sizeof(v) == 8,
"Unknown integer type");
value = sizeof(v) == 1 ? static_cast<uint8>(v)
: sizeof(v) == 2 ? static_cast<uint16>(v)
: sizeof(v) == 4 ? static_cast<uint32>(v)
: static_cast<uint64>(v);
}
};
class AlphaNum {
public:
AlphaNum(int i32)
: piece_(digits_, FastInt32ToBufferLeft(i32, digits_)) {}
AlphaNum(unsigned int u32)
: piece_(digits_, FastUInt32ToBufferLeft(u32, digits_)) {}
AlphaNum(long x)
: piece_(digits_, FastInt64ToBufferLeft(x, digits_)) {}
AlphaNum(unsigned long x)
: piece_(digits_, FastUInt64ToBufferLeft(x, digits_)) {}
AlphaNum(long long int i64)
: piece_(digits_, FastInt64ToBufferLeft(i64, digits_)) {}
AlphaNum(unsigned long long int u64)
: piece_(digits_, FastUInt64ToBufferLeft(u64, digits_)) {}
AlphaNum(float f)
: piece_(digits_, FloatToBuffer(f, digits_)) {}
AlphaNum(double f)
: piece_(digits_, DoubleToBuffer(f, digits_)) {}
AlphaNum(bfloat16 bf)
: piece_(digits_, FloatToBuffer(static_cast<float>(bf), digits_)) {}
AlphaNum(Hex hex);
AlphaNum(const char *c_str) : piece_(c_str) {}
AlphaNum(const StringPiece &pc) : piece_(pc) {}
AlphaNum(const std::string &str)
: piece_(str) {}
AlphaNum(const tstring &str)
: piece_(str) {}
template <typename A>
AlphaNum(const std::basic_string<char, std::char_traits<char>, A> &str)
: piece_(str) {}
StringPiece::size_type size() const { return piece_.size(); }
const char *data() const { return piece_.data(); }
StringPiece Piece() const { return piece_; }
private:
StringPiece piece_;
char digits_[kFastToBufferSize];
AlphaNum(char c);
AlphaNum(const AlphaNum &) = delete;
void operator=(const AlphaNum &) = delete;
};
std::string StrCat(const AlphaNum &a) TF_MUST_USE_RESULT;
std::string StrCat(const AlphaNum &a, const AlphaNum &b) TF_MUST_USE_RESULT;
std::string StrCat(const AlphaNum &a, const AlphaNum &b,
const AlphaNum &c) TF_MUST_USE_RESULT;
std::string StrCat(const AlphaNum &a, const AlphaNum &b, const AlphaNum &c,
const AlphaNum &d) TF_MUST_USE_RESULT;
namespace internal {
std::string CatPieces(std::initializer_list<StringPiece> pieces);
void AppendPieces(std::string *dest, std::initializer_list<StringPiece> pieces);
}
template <typename... AV>
std::string StrCat(const AlphaNum &a, const AlphaNum &b, const AlphaNum &c,
const AlphaNum &d, const AlphaNum &e,
const AV &...args) TF_MUST_USE_RESULT;
template <typename... AV>
std::string StrCat(const AlphaNum &a, const AlphaNum &b, const AlphaNum &c,
const AlphaNum &d, const AlphaNum &e, const AV &...args) {
return internal::CatPieces({a.Piece(), b.Piece(), c.Piece(), d.Piece(),
e.Piece(),
static_cast<const AlphaNum &>(args).Piece()...});
}
void StrAppend(std::string *dest, const AlphaNum &a);
void StrAppend(std::string *dest, const AlphaNum &a, const AlphaNum &b);
void StrAppend(std::string *dest, const AlphaNum &a, const AlphaNum &b,
const AlphaNum &c);
void StrAppend(std::string *dest, const AlphaNum &a, const AlphaNum &b,
const AlphaNum &c, const AlphaNum &d);
template <typename... AV>
inline void StrAppend(std::string *dest, const AlphaNum &a, const AlphaNum &b,
const AlphaNum &c, const AlphaNum &d, const AlphaNum &e,
const AV &...args) {
internal::AppendPieces(dest,
{a.Piece(), b.Piece(), c.Piece(), d.Piece(), e.Piece(),
static_cast<const AlphaNum &>(args).Piece()...});
}
}
}
#endif
#include "tsl/platform/strcat.h"
#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include "absl/meta/type_traits.h"
#include "tsl/platform/logging.h"
namespace tsl {
namespace strings {
AlphaNum::AlphaNum(Hex hex) {
char *const end = &digits_[kFastToBufferSize];
char *writer = end;
uint64 value = hex.value;
uint64 width = hex.spec;
uint64 mask = (static_cast<uint64>(1) << (width - 1) * 4) | value;
static const char hexdigits[] = "0123456789abcdef";
do {
*--writer = hexdigits[value & 0xF];
value >>= 4;
mask >>= 4;
} while (mask != 0);
piece_ = StringPiece(writer, end - writer);
}
static char *Append1(char *out, const AlphaNum &x) {
if (x.data() == nullptr) return out;
memcpy(out, x.data(), x.size());
return out + x.size();
}
static char *Append2(char *out, const AlphaNum &x1, const AlphaNum &x2) {
if (x1.data() != nullptr) {
memcpy(out, x1.data(), x1.size());
out += x1.size();
}
if (x2.data() == nullptr) return out;
memcpy(out, x2.data(), x2.size());
return out + x2.size();
}
static char *Append4(char *out, const AlphaNum &x1, const AlphaNum &x2,
const AlphaNum &x3, const AlphaNum &x4) {
if (x1.data() != nullptr) {
memcpy(out, x1.data(), x1.size());
out += x1.size();
}
if (x2.data() != nullptr) {
memcpy(out, x2.data(), x2.size());
out += x2.size();
}
if (x3.data() != nullptr) {
memcpy(out, x3.data(), x3.size());
out += x3.size();
}
if (x4.data() == nullptr) return out;
memcpy(out, x4.data(), x4.size());
return out + x4.size();
}
string StrCat(const AlphaNum &a) { return string(a.data(), a.size()); }
string StrCat(const AlphaNum &a, const AlphaNum &b) {
string result(a.size() + b.size(), '\0');
char *const begin = &*result.begin();
char *out = Append2(begin, a, b);
DCHECK_EQ(out, begin + result.size());
return result;
}
string StrCat(const AlphaNum &a, const AlphaNum &b, const AlphaNum &c) {
string result(a.size() + b.size() + c.size(), '\0');
char *const begin = &*result.begin();
char *out = Append2(begin, a, b);
out = Append1(out, c);
DCHECK_EQ(out, begin + result.size());
return result;
}
string StrCat(const AlphaNum &a, const AlphaNum &b, const AlphaNum &c,
const AlphaNum &d) {
string result(a.size() + b.size() + c.size() + d.size(), '\0');
char *const begin = &*result.begin();
char *out = Append4(begin, a, b, c, d);
DCHECK_EQ(out, begin + result.size());
return result;
}
namespace {
template <typename string_type, typename = void>
struct ResizeUninitializedTraits {
using HasMember = std::false_type;
static void Resize(string_type *s, size_t new_size) { s->resize(new_size); }
};
template <typename string_type>
struct ResizeUninitializedTraits<
string_type, absl::void_t<decltype(std::declval<string_type &>()
.__resize_default_init(237))> > {
using HasMember = std::true_type;
static void Resize(string_type *s, size_t new_size) {
s->__resize_default_init(new_size);
}
};
static inline void STLStringResizeUninitialized(string *s, size_t new_size) {
ResizeUninitializedTraits<string>::Resize(s, new_size);
}
template <typename string_type>
void STLStringReserveAmortized(string_type *s, size_t new_size) {
const size_t cap = s->capacity();
if (new_size > cap) {
s->reserve((std::max)(new_size, 2 * cap));
}
}
template <typename string_type>
void STLStringResizeUninitializedAmortized(string_type *s, size_t new_size) {
STLStringReserveAmortized(s, new_size);
STLStringResizeUninitialized(s, new_size);
}
}
namespace internal {
string CatPieces(std::initializer_list<StringPiece> pieces) {
size_t total_size = 0;
for (const StringPiece piece : pieces) total_size += piece.size();
string result(total_size, '\0');
char *const begin = &*result.begin();
char *out = begin;
for (const StringPiece piece : pieces) {
const size_t this_size = piece.size();
memcpy(out, piece.data(), this_size);
out += this_size;
}
DCHECK_EQ(out, begin + result.size());
return result;
}
#define DCHECK_NO_OVERLAP(dest, src) \
DCHECK_GE(uintptr_t((src).data() - (dest).data()), uintptr_t((dest).size()))
void AppendPieces(string *result, std::initializer_list<StringPiece> pieces) {
size_t old_size = result->size();
size_t total_size = old_size;
for (const StringPiece piece : pieces) {
DCHECK_NO_OVERLAP(*result, piece);
total_size += piece.size();
}
STLStringResizeUninitializedAmortized(result, total_size);
char *const begin = &*result->begin();
char *out = begin + old_size;
for (const StringPiece piece : pieces) {
const size_t this_size = piece.size();
memcpy(out, piece.data(), this_size);
out += this_size;
}
DCHECK_EQ(out, begin + result->size());
}
}
void StrAppend(string *result, const AlphaNum &a) {
DCHECK_NO_OVERLAP(*result, a);
result->append(a.data(), a.size());
}
void StrAppend(string *result, const AlphaNum &a, const AlphaNum &b) {
DCHECK_NO_OVERLAP(*result, a);
DCHECK_NO_OVERLAP(*result, b);
string::size_type old_size = result->size();
STLStringResizeUninitializedAmortized(result, old_size + a.size() + b.size());
char *const begin = &*result->begin();
char *out = Append2(begin + old_size, a, b);
DCHECK_EQ(out, begin + result->size());
}
void StrAppend(string *result, const AlphaNum &a, const AlphaNum &b,
const AlphaNum &c) {
DCHECK_NO_OVERLAP(*result, a);
DCHECK_NO_OVERLAP(*result, b);
DCHECK_NO_OVERLAP(*result, c);
string::size_type old_size = result->size();
STLStringResizeUninitializedAmortized(
result, old_size + a.size() + b.size() + c.size());
char *const begin = &*result->begin();
char *out = Append2(begin + old_size, a, b);
out = Append1(out, c);
DCHECK_EQ(out, begin + result->size());
}
void StrAppend(string *result, const AlphaNum &a, const AlphaNum &b,
const AlphaNum &c, const AlphaNum &d) {
DCHECK_NO_OVERLAP(*result, a);
DCHECK_NO_OVERLAP(*result, b);
DCHECK_NO_OVERLAP(*result, c);
DCHECK_NO_OVERLAP(*result, d);
string::size_type old_size = result->size();
STLStringResizeUninitializedAmortized(
result, old_size + a.size() + b.size() + c.size() + d.size());
char *const begin = &*result->begin();
char *out = Append4(begin + old_size, a, b, c, d);
DCHECK_EQ(out, begin + result->size());
}
}
} | #include "tsl/platform/strcat.h"
#include <string>
#include "absl/strings/string_view.h"
#include "tsl/platform/stringprintf.h"
#include "tsl/platform/test.h"
#include "tsl/platform/types.h"
#ifdef _MSC_VER
typedef ptrdiff_t ssize_t;
#endif
namespace tsl {
namespace strings {
TEST(StrCat, Ints) {
const int16_t s = -1;
const uint16 us = 2;
const int i = -3;
const unsigned int ui = 4;
const int32_t l = -5;
const uint32 ul = 6;
const int64_t ll = -7;
const uint64 ull = 8;
const ptrdiff_t ptrdiff = -9;
const size_t size = 10;
const ssize_t ssize = -11;
const intptr_t intptr = -12;
const uintptr_t uintptr = 13;
string answer;
answer = StrCat(s, us);
EXPECT_EQ(answer, "-12");
answer = StrCat(i, ui);
EXPECT_EQ(answer, "-34");
answer = StrCat(l, ul);
EXPECT_EQ(answer, "-56");
answer = StrCat(ll, ull);
EXPECT_EQ(answer, "-78");
answer = StrCat(ptrdiff, size);
EXPECT_EQ(answer, "-910");
answer = StrCat(ssize, intptr);
EXPECT_EQ(answer, "-11-12");
answer = StrCat(uintptr, 0);
EXPECT_EQ(answer, "130");
}
TEST(StrCat, Floats) {
const int s = 0;
const float f = 1.5f;
const double d = 1.5;
const bfloat16 bf(1.5f);
string answer;
answer = StrCat(s, f);
EXPECT_EQ(answer, "01.5");
answer = StrCat(s, d);
EXPECT_EQ(answer, "01.5");
answer = StrCat(s, bf);
EXPECT_EQ(answer, "01.5");
}
TEST(StrCat, Nulls) {
string result;
absl::string_view v;
string strs[] = {"Hello", "Cruel", "World"};
result = StrCat(v);
EXPECT_EQ(result, "");
result = StrCat(strs[0], v);
EXPECT_EQ(result, "Hello");
result = StrCat(v, strs[0]);
EXPECT_EQ(result, "Hello");
result = StrCat(v, strs[0], strs[1]);
EXPECT_EQ(result, "HelloCruel");
result = StrCat(strs[0], v, strs[1]);
EXPECT_EQ(result, "HelloCruel");
result = StrCat(strs[0], strs[1], v);
EXPECT_EQ(result, "HelloCruel");
result = StrCat(v, strs[0], strs[1], strs[2]);
EXPECT_EQ(result, "HelloCruelWorld");
result = StrCat(strs[0], v, strs[1], strs[2]);
EXPECT_EQ(result, "HelloCruelWorld");
result = StrCat(strs[0], strs[1], v, strs[2]);
EXPECT_EQ(result, "HelloCruelWorld");
result = StrCat(strs[0], strs[1], strs[2], v);
EXPECT_EQ(result, "HelloCruelWorld");
}
TEST(StrCat, Basics) {
string result;
string strs[] = {"Hello", "Cruel", "World"};
StringPiece pieces[] = {"Hello", "Cruel", "World"};
const char *c_strs[] = {"Hello", "Cruel", "World"};
int32 i32s[] = {'H', 'C', 'W'};
uint64 ui64s[] = {12345678910LL, 10987654321LL};
result = StrCat(false, true, 2, 3);
EXPECT_EQ(result, "0123");
result = StrCat(-1);
EXPECT_EQ(result, "-1");
result = StrCat(0.5);
EXPECT_EQ(result, "0.5");
result = StrCat(strs[1], pieces[2]);
EXPECT_EQ(result, "CruelWorld");
result = StrCat(strs[0], ", ", pieces[2]);
EXPECT_EQ(result, "Hello, World");
result = StrCat(strs[0], ", ", strs[1], " ", strs[2], "!");
EXPECT_EQ(result, "Hello, Cruel World!");
result = StrCat(pieces[0], ", ", pieces[1], " ", pieces[2]);
EXPECT_EQ(result, "Hello, Cruel World");
result = StrCat(c_strs[0], ", ", c_strs[1], " ", c_strs[2]);
EXPECT_EQ(result, "Hello, Cruel World");
result = StrCat("ASCII ", i32s[0], ", ", i32s[1], " ", i32s[2], "!");
EXPECT_EQ(result, "ASCII 72, 67 87!");
result = StrCat(ui64s[0], ", ", ui64s[1], "!");
EXPECT_EQ(result, "12345678910, 10987654321!");
string one = "1";
result = StrCat("And a ", one.size(), " and a ", &result[2] - &result[0],
" and a ", one, " 2 3 4", "!");
EXPECT_EQ(result, "And a 1 and a 2 and a 1 2 3 4!");
result = StrCat("To output a char by ASCII/numeric value, use +: ", '!' + 0);
EXPECT_EQ(result, "To output a char by ASCII/numeric value, use +: 33");
float f = 100000.5;
result = StrCat("A hundred K and a half is ", f);
EXPECT_EQ(result, "A hundred K and a half is 100000.5");
double d = f;
d *= d;
result = StrCat("A hundred K and a half squared is ", d);
EXPECT_EQ(result, "A hundred K and a half squared is 10000100000.25");
result = StrCat(1, 2, 333, 4444, 55555, 666666, 7777777, 88888888, 999999999);
EXPECT_EQ(result, "12333444455555666666777777788888888999999999");
}
TEST(StrCat, MaxArgs) {
string result;
result = StrCat(1, 2, 3, 4, 5, 6, 7, 8, 9, "a");
EXPECT_EQ(result, "123456789a");
result = StrCat(1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b");
EXPECT_EQ(result, "123456789ab");
result = StrCat(1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b", "c");
EXPECT_EQ(result, "123456789abc");
result = StrCat(1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b", "c", "d");
EXPECT_EQ(result, "123456789abcd");
result = StrCat(1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b", "c", "d", "e");
EXPECT_EQ(result, "123456789abcde");
result = StrCat(1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b", "c", "d", "e", "f");
EXPECT_EQ(result, "123456789abcdef");
result = StrCat(1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b", "c", "d", "e", "f", "g");
EXPECT_EQ(result, "123456789abcdefg");
result =
StrCat(1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b", "c", "d", "e", "f", "g", "h");
EXPECT_EQ(result, "123456789abcdefgh");
result = StrCat(1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b", "c", "d", "e", "f", "g",
"h", "i");
EXPECT_EQ(result, "123456789abcdefghi");
result = StrCat(1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b", "c", "d", "e", "f", "g",
"h", "i", "j");
EXPECT_EQ(result, "123456789abcdefghij");
result = StrCat(1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b", "c", "d", "e", "f", "g",
"h", "i", "j", "k");
EXPECT_EQ(result, "123456789abcdefghijk");
result = StrCat(1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b", "c", "d", "e", "f", "g",
"h", "i", "j", "k", "l");
EXPECT_EQ(result, "123456789abcdefghijkl");
result = StrCat(1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b", "c", "d", "e", "f", "g",
"h", "i", "j", "k", "l", "m");
EXPECT_EQ(result, "123456789abcdefghijklm");
result = StrCat(1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b", "c", "d", "e", "f", "g",
"h", "i", "j", "k", "l", "m", "n");
EXPECT_EQ(result, "123456789abcdefghijklmn");
result = StrCat(1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b", "c", "d", "e", "f", "g",
"h", "i", "j", "k", "l", "m", "n", "o");
EXPECT_EQ(result, "123456789abcdefghijklmno");
result = StrCat(1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b", "c", "d", "e", "f", "g",
"h", "i", "j", "k", "l", "m", "n", "o", "p");
EXPECT_EQ(result, "123456789abcdefghijklmnop");
result = StrCat(1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b", "c", "d", "e", "f", "g",
"h", "i", "j", "k", "l", "m", "n", "o", "p", "q");
EXPECT_EQ(result, "123456789abcdefghijklmnopq");
result = StrCat(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, "a", "b", "c", "d", "e", "f",
"g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r",
"s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D",
"E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P",
"Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z");
EXPECT_EQ(result,
"12345678910abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ");
}
TEST(StrAppend, Basics) {
string result = "existing text";
string strs[] = {"Hello", "Cruel", "World"};
StringPiece pieces[] = {"Hello", "Cruel", "World"};
const char *c_strs[] = {"Hello", "Cruel", "World"};
int32 i32s[] = {'H', 'C', 'W'};
uint64 ui64s[] = {12345678910LL, 10987654321LL};
string::size_type old_size = result.size();
StrAppend(&result, strs[0]);
EXPECT_EQ(result.substr(old_size), "Hello");
old_size = result.size();
StrAppend(&result, strs[1], pieces[2]);
EXPECT_EQ(result.substr(old_size), "CruelWorld");
old_size = result.size();
StrAppend(&result, strs[0], ", ", pieces[2]);
EXPECT_EQ(result.substr(old_size), "Hello, World");
old_size = result.size();
StrAppend(&result, strs[0], ", ", strs[1], " ", strs[2], "!");
EXPECT_EQ(result.substr(old_size), "Hello, Cruel World!");
old_size = result.size();
StrAppend(&result, pieces[0], ", ", pieces[1], " ", pieces[2]);
EXPECT_EQ(result.substr(old_size), "Hello, Cruel World");
old_size = result.size();
StrAppend(&result, c_strs[0], ", ", c_strs[1], " ", c_strs[2]);
EXPECT_EQ(result.substr(old_size), "Hello, Cruel World");
old_size = result.size();
StrAppend(&result, "ASCII ", i32s[0], ", ", i32s[1], " ", i32s[2], "!");
EXPECT_EQ(result.substr(old_size), "ASCII 72, 67 87!");
old_size = result.size();
StrAppend(&result, ui64s[0], ", ", ui64s[1], "!");
EXPECT_EQ(result.substr(old_size), "12345678910, 10987654321!");
string one = "1";
old_size = result.size();
StrAppend(&result, "And a ", one.size(), " and a ", &result[2] - &result[0],
" and a ", one, " 2 3 4", "!");
EXPECT_EQ(result.substr(old_size), "And a 1 and a 2 and a 1 2 3 4!");
old_size = result.size();
StrAppend(&result,
"To output a char by ASCII/numeric value, use +: ", '!' + 0);
EXPECT_EQ(result.substr(old_size),
"To output a char by ASCII/numeric value, use +: 33");
float f = 100000.5;
old_size = result.size();
StrAppend(&result, "A hundred K and a half is ", f);
EXPECT_EQ(result.substr(old_size), "A hundred K and a half is 100000.5");
double d = f;
d *= d;
old_size = result.size();
StrAppend(&result, "A hundred K and a half squared is ", d);
EXPECT_EQ(result.substr(old_size),
"A hundred K and a half squared is 10000100000.25");
old_size = result.size();
StrAppend(&result, 1, 22, 333, 4444, 55555, 666666, 7777777, 88888888, 9);
EXPECT_EQ(result.substr(old_size), "1223334444555556666667777777888888889");
old_size = result.size();
StrAppend(&result, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, "a", "b", "c", "d", "e",
"f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r",
"s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E",
"F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
"S", "T", "U", "V", "W", "X", "Y", "Z",
"No limit thanks to C++11's variadic templates");
EXPECT_EQ(result.substr(old_size),
"12345678910abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
"No limit thanks to C++11's variadic templates");
}
TEST(StrAppend, Death) {
string s = "self";
EXPECT_DEBUG_DEATH(StrAppend(&s, s.c_str() + 1), "Check failed:");
EXPECT_DEBUG_DEATH(StrAppend(&s, s), "Check failed:");
}
static void CheckHex64(uint64 v) {
string actual = StrCat(Hex(v, kZeroPad16));
string expected = Printf("%016llx", static_cast<unsigned long long>(v));
EXPECT_EQ(expected, actual) << " decimal value " << v;
actual = StrCat(Hex(v, kZeroPad8));
expected = Printf("%08llx", static_cast<unsigned long long>(v));
EXPECT_EQ(expected, actual) << " decimal value " << v;
actual = StrCat(Hex(v));
expected = Printf("%llx", static_cast<unsigned long long>(v));
EXPECT_EQ(expected, actual) << " decimal value " << v;
}
static void CheckHex32(uint32 v) {
string actual = StrCat(Hex(v, kZeroPad8));
string expected = Printf("%08x", v);
EXPECT_EQ(expected, actual) << " decimal value " << v;
actual = StrCat(Hex(v));
expected = Printf("%x", v);
EXPECT_EQ(expected, actual) << " decimal value " << v;
}
static void CheckHexSigned32(int32_t v) {
string actual = StrCat(Hex(v, kZeroPad8));
string expected = Printf("%08x", v);
EXPECT_EQ(expected, actual) << " decimal value " << v;
actual = StrCat(Hex(v));
expected = Printf("%x", v);
EXPECT_EQ(expected, actual) << " decimal value " << v;
}
static void TestFastPrints() {
for (int i = 0; i < 10000; i++) {
CheckHex64(i);
CheckHex32(i);
CheckHexSigned32(i);
CheckHexSigned32(-i);
}
CheckHex64(0x123456789abcdef0ull);
CheckHex32(0x12345678);
int8_t minus_one_8bit = -1;
EXPECT_EQ("ff", StrCat(Hex(minus_one_8bit)));
int16_t minus_one_16bit = -1;
EXPECT_EQ("ffff", StrCat(Hex(minus_one_16bit)));
}
TEST(Numbers, TestFunctionsMovedOverFromNumbersMain) { TestFastPrints(); }
}
} | 2,270 |
#ifndef TENSORFLOW_TSL_PLATFORM_HASH_H_
#define TENSORFLOW_TSL_PLATFORM_HASH_H_
#include <stddef.h>
#include <stdint.h>
#include <functional>
#include <string>
#include "tsl/platform/stringpiece.h"
#include "tsl/platform/types.h"
namespace tsl {
extern uint32 Hash32(const char* data, size_t n, uint32 seed);
extern uint64 Hash64(const char* data, size_t n, uint64 seed);
inline uint64 Hash64(const char* data, size_t n) {
return Hash64(data, n, 0xDECAFCAFFE);
}
inline uint64 Hash64(const char* data) { return Hash64(data, ::strlen(data)); }
inline uint64 Hash64(const std::string& str) {
return Hash64(str.data(), str.size());
}
inline uint64 Hash64(const tstring& str) {
return Hash64(str.data(), str.size());
}
inline uint64 Hash64Combine(uint64 a, uint64 b) {
return a ^ (b + 0x9e3779b97f4a7800ULL + (a << 10) + (a >> 4));
}
inline uint64 Hash64CombineUnordered(uint64 a, uint64 b) { return a + b; }
template <typename T, typename = void>
struct hash {
size_t operator()(const T& t) const { return std::hash<T>()(t); }
};
template <typename T>
struct hash<T, typename std::enable_if<std::is_enum<T>::value>::type> {
size_t operator()(T value) const {
return std::hash<uint64>()(static_cast<uint64>(value));
}
};
template <typename T>
struct hash<T*> {
size_t operator()(const T* t) const {
size_t k = static_cast<size_t>(reinterpret_cast<uintptr_t>(t));
return k + (k >> 6);
}
};
template <>
struct hash<string> {
size_t operator()(const string& s) const {
return static_cast<size_t>(Hash64(s));
}
};
template <>
struct hash<tstring> {
size_t operator()(const tstring& s) const {
return static_cast<size_t>(Hash64(s.data(), s.size()));
}
};
template <>
struct hash<StringPiece> {
size_t operator()(StringPiece sp) const {
return static_cast<size_t>(Hash64(sp.data(), sp.size()));
}
};
using StringPieceHasher = ::tsl::hash<StringPiece>;
template <typename T, typename U>
struct hash<std::pair<T, U>> {
size_t operator()(const std::pair<T, U>& p) const {
return Hash64Combine(hash<T>()(p.first), hash<U>()(p.second));
}
};
}
namespace std {
template <>
struct hash<tsl::tstring> {
size_t operator()(const tsl::tstring& s) const {
return static_cast<size_t>(tsl::Hash64(s.data(), s.size()));
}
};
}
#endif
#include "tsl/platform/hash.h"
#include <string.h>
#include "tsl/platform/macros.h"
#include "tsl/platform/raw_coding.h"
#include "tsl/platform/types.h"
namespace tsl {
static inline uint32 ByteAs32(char c) { return static_cast<uint32>(c) & 0xff; }
static inline uint64 ByteAs64(char c) { return static_cast<uint64>(c) & 0xff; }
uint32 Hash32(const char* data, size_t n, uint32 seed) {
const uint32 m = 0x5bd1e995;
const int r = 24;
uint32 h = seed ^ n;
while (n >= 4) {
uint32 k = core::DecodeFixed32(data);
k *= m;
k ^= k >> r;
k *= m;
h *= m;
h ^= k;
data += 4;
n -= 4;
}
switch (n) {
case 3:
h ^= ByteAs32(data[2]) << 16;
TF_FALLTHROUGH_INTENDED;
case 2:
h ^= ByteAs32(data[1]) << 8;
TF_FALLTHROUGH_INTENDED;
case 1:
h ^= ByteAs32(data[0]);
h *= m;
}
h ^= h >> 13;
h *= m;
h ^= h >> 15;
return h;
}
uint64 Hash64(const char* data, size_t n, uint64 seed) {
const uint64 m = 0xc6a4a7935bd1e995;
const int r = 47;
uint64 h = seed ^ (n * m);
while (n >= 8) {
uint64 k = core::DecodeFixed64(data);
data += 8;
n -= 8;
k *= m;
k ^= k >> r;
k *= m;
h ^= k;
h *= m;
}
switch (n) {
case 7:
h ^= ByteAs64(data[6]) << 48;
TF_FALLTHROUGH_INTENDED;
case 6:
h ^= ByteAs64(data[5]) << 40;
TF_FALLTHROUGH_INTENDED;
case 5:
h ^= ByteAs64(data[4]) << 32;
TF_FALLTHROUGH_INTENDED;
case 4:
h ^= ByteAs64(data[3]) << 24;
TF_FALLTHROUGH_INTENDED;
case 3:
h ^= ByteAs64(data[2]) << 16;
TF_FALLTHROUGH_INTENDED;
case 2:
h ^= ByteAs64(data[1]) << 8;
TF_FALLTHROUGH_INTENDED;
case 1:
h ^= ByteAs64(data[0]);
h *= m;
}
h ^= h >> r;
h *= m;
h ^= h >> r;
return h;
}
} | #include <map>
#include <unordered_map>
#include <vector>
#include "tsl/platform/hash.h"
#include "tsl/platform/logging.h"
#include "tsl/platform/test.h"
#include "tsl/platform/test_benchmark.h"
namespace tsl {
TEST(Hash, SignedUnsignedIssue) {
const unsigned char d1[1] = {0x62};
const unsigned char d2[2] = {0xc3, 0x97};
const unsigned char d3[3] = {0xe2, 0x99, 0xa5};
const unsigned char d4[4] = {0xe1, 0x80, 0xb9, 0x32};
const unsigned char d5[48] = {
0x01, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00,
0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x18, 0x28, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
};
struct Case {
uint32 hash32;
uint64 hash64;
const unsigned char* data;
size_t size;
uint32 seed;
};
for (Case c : std::vector<Case>{
{0x471a8188u, 0x4c61ea3eeda4cb87ull, nullptr, 0, 0xbc9f1d34},
{0xd615eba5u, 0x091309f7ef916c8aull, d1, sizeof(d1), 0xbc9f1d34},
{0x0c3cccdau, 0xa815bcdf1d1af01cull, d2, sizeof(d2), 0xbc9f1d34},
{0x3ba37e0eu, 0x02167564e4d06430ull, d3, sizeof(d3), 0xbc9f1d34},
{0x16174eb3u, 0x8f7ed82ffc21071full, d4, sizeof(d4), 0xbc9f1d34},
{0x98b1926cu, 0xce196580c97aff1eull, d5, sizeof(d5), 0x12345678},
}) {
EXPECT_EQ(c.hash32,
Hash32(reinterpret_cast<const char*>(c.data), c.size, c.seed));
EXPECT_EQ(c.hash64,
Hash64(reinterpret_cast<const char*>(c.data), c.size, c.seed));
for (int align = 1; align <= 7; align++) {
std::string input(align, 'x');
input.append(reinterpret_cast<const char*>(c.data), c.size);
EXPECT_EQ(c.hash32, Hash32(&input[align], c.size, c.seed));
EXPECT_EQ(c.hash64, Hash64(&input[align], c.size, c.seed));
}
}
}
TEST(Hash, HashPtrIsNotIdentityFunction) {
int* ptr = reinterpret_cast<int*>(0xcafe0000);
EXPECT_NE(hash<int*>()(ptr), size_t{0xcafe0000});
}
static void BM_Hash32(::testing::benchmark::State& state) {
int len = state.range(0);
std::string input(len, 'x');
uint32 h = 0;
for (auto s : state) {
h = Hash32(input.data(), len, 1);
}
state.SetBytesProcessed(state.iterations() * len);
VLOG(1) << h;
}
BENCHMARK(BM_Hash32)->Range(1, 1024);
TEST(StringPieceHasher, Equality) {
StringPieceHasher hasher;
StringPiece s1("foo");
StringPiece s2("bar");
StringPiece s3("baz");
StringPiece s4("zot");
EXPECT_TRUE(hasher(s1) != hasher(s2));
EXPECT_TRUE(hasher(s1) != hasher(s3));
EXPECT_TRUE(hasher(s1) != hasher(s4));
EXPECT_TRUE(hasher(s2) != hasher(s3));
EXPECT_TRUE(hasher(s2) != hasher(s4));
EXPECT_TRUE(hasher(s3) != hasher(s4));
EXPECT_TRUE(hasher(s1) == hasher(s1));
EXPECT_TRUE(hasher(s2) == hasher(s2));
EXPECT_TRUE(hasher(s3) == hasher(s3));
EXPECT_TRUE(hasher(s4) == hasher(s4));
}
TEST(StringPieceHasher, HashMap) {
string s1("foo");
string s2("bar");
string s3("baz");
StringPiece p1(s1);
StringPiece p2(s2);
StringPiece p3(s3);
std::unordered_map<StringPiece, int, StringPieceHasher> map;
map.insert(std::make_pair(p1, 0));
map.insert(std::make_pair(p2, 1));
map.insert(std::make_pair(p3, 2));
EXPECT_EQ(map.size(), 3);
bool found[3] = {false, false, false};
for (auto const& val : map) {
int x = val.second;
EXPECT_TRUE(x >= 0 && x < 3);
EXPECT_TRUE(!found[x]);
found[x] = true;
}
EXPECT_EQ(found[0], true);
EXPECT_EQ(found[1], true);
EXPECT_EQ(found[2], true);
auto new_iter = map.find("zot");
EXPECT_TRUE(new_iter == map.end());
new_iter = map.find("bar");
EXPECT_TRUE(new_iter != map.end());
map.erase(new_iter);
EXPECT_EQ(map.size(), 2);
found[0] = false;
found[1] = false;
found[2] = false;
for (const auto& iter : map) {
int x = iter.second;
EXPECT_TRUE(x >= 0 && x < 3);
EXPECT_TRUE(!found[x]);
found[x] = true;
}
EXPECT_EQ(found[0], true);
EXPECT_EQ(found[1], false);
EXPECT_EQ(found[2], true);
}
} | 2,271 |
#ifndef TENSORFLOW_TSL_PLATFORM_SETROUND_H_
#define TENSORFLOW_TSL_PLATFORM_SETROUND_H_
#if defined(__ANDROID_API__) && (__ANDROID_API__ < 21)
#define TF_BROKEN_CFENV
#endif
#if defined(TF_BROKEN_CFENV)
#include <fenv.h>
#else
#include <cfenv>
#endif
#include "tsl/platform/macros.h"
namespace tsl {
namespace port {
class ScopedSetRound {
public:
ScopedSetRound(int mode);
~ScopedSetRound();
private:
int original_mode_;
ScopedSetRound(const ScopedSetRound&) = delete;
void operator=(const ScopedSetRound&) = delete;
};
}
}
#endif
#include "tsl/platform/setround.h"
#include "tsl/platform/logging.h"
namespace tsl {
namespace port {
#if defined(TF_BROKEN_CFENV)
ScopedSetRound::ScopedSetRound(const int mode) : original_mode_(mode) {
DCHECK_EQ(mode, FE_TONEAREST);
}
ScopedSetRound::~ScopedSetRound() {}
#else
ScopedSetRound::ScopedSetRound(const int mode) {
original_mode_ = std::fegetround();
if (original_mode_ < 0) {
original_mode_ = FE_TONEAREST;
}
std::fesetround(mode);
}
ScopedSetRound::~ScopedSetRound() { std::fesetround(original_mode_); }
#endif
}
} | #include "tsl/platform/setround.h"
#include <cmath>
#include "tsl/platform/test.h"
#if !defined(__clang__) || !defined(__OPTIMIZE__)
namespace tsl {
namespace {
void CheckDownward() {
EXPECT_EQ(12, std::nearbyint(12.0));
EXPECT_EQ(12, std::nearbyint(12.1));
EXPECT_EQ(-13, std::nearbyint(-12.1));
EXPECT_EQ(12, std::nearbyint(12.5));
EXPECT_EQ(12, std::nearbyint(12.9));
EXPECT_EQ(-13, std::nearbyint(-12.9));
EXPECT_EQ(13, std::nearbyint(13.0));
}
void CheckToNearest() {
EXPECT_EQ(12, std::nearbyint(12.0));
EXPECT_EQ(12, std::nearbyint(12.1));
EXPECT_EQ(-12, std::nearbyint(-12.1));
EXPECT_EQ(12, std::nearbyint(12.5));
EXPECT_EQ(13, std::nearbyint(12.9));
EXPECT_EQ(-13, std::nearbyint(-12.9));
EXPECT_EQ(13, std::nearbyint(13.0));
}
void CheckTowardZero() {
EXPECT_EQ(12, std::nearbyint(12.0));
EXPECT_EQ(12, std::nearbyint(12.1));
EXPECT_EQ(-12, std::nearbyint(-12.1));
EXPECT_EQ(12, std::nearbyint(12.5));
EXPECT_EQ(12, std::nearbyint(12.9));
EXPECT_EQ(-12, std::nearbyint(-12.9));
EXPECT_EQ(13, std::nearbyint(13.0));
}
void CheckUpward() {
EXPECT_EQ(12, std::nearbyint(12.0));
EXPECT_EQ(13, std::nearbyint(12.1));
EXPECT_EQ(-12, std::nearbyint(-12.1));
EXPECT_EQ(13, std::nearbyint(12.5));
EXPECT_EQ(13, std::nearbyint(12.9));
EXPECT_EQ(-12, std::nearbyint(-12.9));
EXPECT_EQ(13, std::nearbyint(13.0));
}
TEST(SetScopedSetRound, Downward) {
port::ScopedSetRound round(FE_DOWNWARD);
CheckDownward();
}
TEST(SetScopedSetRound, ToNearest) {
port::ScopedSetRound round(FE_TONEAREST);
CheckToNearest();
}
TEST(SetScopedSetRound, TowardZero) {
port::ScopedSetRound round(FE_TOWARDZERO);
CheckTowardZero();
}
TEST(SetScopedSetRound, Upward) {
port::ScopedSetRound round(FE_UPWARD);
CheckUpward();
}
TEST(SetScopedSetRound, Scoped) {
std::fesetround(FE_TONEAREST);
CheckToNearest();
{
port::ScopedSetRound round(FE_UPWARD);
CheckUpward();
}
CheckToNearest();
}
}
}
#endif | 2,272 |
#ifndef TENSORFLOW_TSL_PLATFORM_PATH_H_
#define TENSORFLOW_TSL_PLATFORM_PATH_H_
#include <string>
#include "tsl/platform/stringpiece.h"
#include "tsl/platform/types.h"
namespace tsl {
namespace io {
namespace internal {
std::string JoinPathImpl(std::initializer_list<tsl::StringPiece> paths);
}
#ifndef SWIG
template <typename... T>
std::string JoinPath(const T&... args) {
return internal::JoinPathImpl({args...});
}
#endif
bool IsAbsolutePath(tsl::StringPiece path);
tsl::StringPiece Dirname(tsl::StringPiece path);
tsl::StringPiece Basename(tsl::StringPiece path);
tsl::StringPiece Extension(tsl::StringPiece path);
tsl::StringPiece BasenamePrefix(tsl::StringPiece path);
std::string CommonPathPrefix(absl::Span<std::string const> paths);
std::string CleanPath(tsl::StringPiece path);
void ParseURI(tsl::StringPiece uri, tsl::StringPiece* scheme,
tsl::StringPiece* host, tsl::StringPiece* path);
std::string CreateURI(tsl::StringPiece scheme, tsl::StringPiece host,
tsl::StringPiece path);
std::string GetTempFilename(const std::string& extension);
bool GetTestWorkspaceDir(std::string* dir);
bool GetTestUndeclaredOutputsDir(std::string* dir);
bool ResolveTestPrefixes(tsl::StringPiece path, std::string& resolved_path);
[[maybe_unused]] std::string& AppendDotExeIfWindows(std::string& path);
}
}
#endif
#include "tsl/platform/path.h"
#include <errno.h>
#include <fcntl.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#if defined(PLATFORM_WINDOWS)
#include <windows.h>
#else
#include <unistd.h>
#endif
#include <string>
#include <vector>
#include "absl/algorithm/container.h"
#include "tsl/platform/logging.h"
#include "tsl/platform/mutex.h"
#include "tsl/platform/scanner.h"
#include "tsl/platform/str_util.h"
#include "tsl/platform/strcat.h"
#include "tsl/platform/stringpiece.h"
#include "tsl/platform/types.h"
namespace tsl {
namespace io {
namespace internal {
namespace {
const char kPathSep[] = "/";
}
string JoinPathImpl(std::initializer_list<StringPiece> paths) {
string result;
for (StringPiece path : paths) {
if (path.empty()) continue;
if (result.empty()) {
result = string(path);
continue;
}
if (IsAbsolutePath(path)) path = path.substr(1);
if (result[result.size() - 1] == kPathSep[0]) {
strings::StrAppend(&result, path);
} else {
strings::StrAppend(&result, kPathSep, path);
}
}
return result;
}
std::pair<StringPiece, StringPiece> SplitPath(StringPiece uri) {
StringPiece scheme, host, path;
ParseURI(uri, &scheme, &host, &path);
auto pos = path.rfind('/');
#ifdef PLATFORM_WINDOWS
if (pos == StringPiece::npos) pos = path.rfind('\\');
#endif
if (pos == StringPiece::npos)
return std::make_pair(StringPiece(uri.data(), host.end() - uri.begin()),
path);
if (pos == 0)
return std::make_pair(
StringPiece(uri.data(), path.begin() + 1 - uri.begin()),
StringPiece(path.data() + 1, path.size() - 1));
return std::make_pair(
StringPiece(uri.data(), path.begin() + pos - uri.begin()),
StringPiece(path.data() + pos + 1, path.size() - (pos + 1)));
}
std::pair<StringPiece, StringPiece> SplitBasename(StringPiece path) {
path = Basename(path);
auto pos = path.rfind('.');
if (pos == StringPiece::npos)
return std::make_pair(path, StringPiece(path.data() + path.size(), 0));
return std::make_pair(
StringPiece(path.data(), pos),
StringPiece(path.data() + pos + 1, path.size() - (pos + 1)));
}
}
bool IsAbsolutePath(StringPiece path) {
return !path.empty() && path[0] == '/';
}
StringPiece Dirname(StringPiece path) {
return internal::SplitPath(path).first;
}
StringPiece Basename(StringPiece path) {
return internal::SplitPath(path).second;
}
StringPiece Extension(StringPiece path) {
return internal::SplitBasename(path).second;
}
StringPiece BasenamePrefix(StringPiece path) {
return internal::SplitBasename(path).first;
}
string CleanPath(StringPiece unclean_path) {
string path(unclean_path);
const char* src = path.c_str();
string::iterator dst = path.begin();
const bool is_absolute_path = *src == '/';
if (is_absolute_path) {
*dst++ = *src++;
while (*src == '/') ++src;
}
string::const_iterator backtrack_limit = dst;
while (*src) {
bool parsed = false;
if (src[0] == '.') {
if (src[1] == '/' || !src[1]) {
if (*++src) {
++src;
}
parsed = true;
} else if (src[1] == '.' && (src[2] == '/' || !src[2])) {
src += 2;
if (dst != backtrack_limit) {
for (--dst; dst != backtrack_limit && dst[-1] != '/'; --dst) {
}
} else if (!is_absolute_path) {
src -= 2;
*dst++ = *src++;
*dst++ = *src++;
if (*src) {
*dst++ = *src;
}
backtrack_limit = dst;
}
if (*src) {
++src;
}
parsed = true;
}
}
if (!parsed) {
while (*src && *src != '/') {
*dst++ = *src++;
}
if (*src) {
*dst++ = *src++;
}
}
while (*src == '/') {
++src;
}
}
string::difference_type path_length = dst - path.begin();
if (path_length != 0) {
if (path_length > 1 && path[path_length - 1] == '/') {
--path_length;
}
path.resize(path_length);
} else {
path.assign(1, '.');
}
return path;
}
void ParseURI(StringPiece uri, StringPiece* scheme, StringPiece* host,
StringPiece* path) {
if (!strings::Scanner(uri)
.One(strings::Scanner::LETTER)
.Many(strings::Scanner::LETTER_DIGIT_DOT)
.StopCapture()
.OneLiteral(":
.GetResult(&uri, scheme)) {
*scheme = StringPiece(uri.data(), 0);
*host = StringPiece(uri.data(), 0);
*path = uri;
return;
}
if (!strings::Scanner(uri).ScanUntil('/').GetResult(&uri, host)) {
*host = uri;
*path = StringPiece();
return;
}
*path = uri;
}
string CreateURI(StringPiece scheme, StringPiece host, StringPiece path) {
if (scheme.empty()) {
return string(path);
}
return strings::StrCat(scheme, ":
}
int64_t UniqueId() {
static mutex mu(LINKER_INITIALIZED);
static int64_t id = 0;
mutex_lock l(mu);
return ++id;
}
string CommonPathPrefix(absl::Span<const string> paths) {
if (paths.empty()) return "";
size_t min_filename_size =
absl::c_min_element(paths, [](const string& a, const string& b) {
return a.size() < b.size();
})->size();
if (min_filename_size == 0) return "";
size_t common_prefix_size = [&] {
for (size_t prefix_size = 0; prefix_size < min_filename_size;
prefix_size++) {
char c = paths[0][prefix_size];
for (int f = 1; f < paths.size(); f++) {
if (paths[f][prefix_size] != c) {
return prefix_size;
}
}
}
return min_filename_size;
}();
size_t rpos = absl::string_view(paths[0])
.substr(0, common_prefix_size)
.rfind(internal::kPathSep);
return rpos == std::string::npos
? ""
: std::string(absl::string_view(paths[0]).substr(0, rpos + 1));
}
string GetTempFilename(const string& extension) {
#if defined(__ANDROID__)
LOG(FATAL) << "GetTempFilename is not implemented in this platform.";
#elif defined(PLATFORM_WINDOWS)
char temp_dir[_MAX_PATH];
DWORD retval;
retval = GetTempPath(_MAX_PATH, temp_dir);
if (retval > _MAX_PATH || retval == 0) {
LOG(FATAL) << "Cannot get the directory for temporary files.";
}
char temp_file_name[_MAX_PATH];
retval = GetTempFileName(temp_dir, "", UniqueId(), temp_file_name);
if (retval > _MAX_PATH || retval == 0) {
LOG(FATAL) << "Cannot get a temporary file in: " << temp_dir;
}
string full_tmp_file_name(temp_file_name);
full_tmp_file_name.append(extension);
return full_tmp_file_name;
#else
for (const char* dir : std::vector<const char*>(
{getenv("TEST_TMPDIR"), getenv("TMPDIR"), getenv("TMP"), "/tmp"})) {
if (!dir || !dir[0]) {
continue;
}
struct stat statbuf;
if (!stat(dir, &statbuf) && S_ISDIR(statbuf.st_mode)) {
string tmp_filepath;
int fd;
if (extension.length()) {
tmp_filepath = io::JoinPath(
dir, strings::StrCat("tmp_file_tensorflow_", UniqueId(), "_XXXXXX.",
extension));
fd = mkstemps(&tmp_filepath[0], extension.length() + 1);
} else {
tmp_filepath = io::JoinPath(
dir,
strings::StrCat("tmp_file_tensorflow_", UniqueId(), "_XXXXXX"));
fd = mkstemp(&tmp_filepath[0]);
}
if (fd < 0) {
LOG(FATAL) << "Failed to create temp file.";
} else {
if (close(fd) < 0) {
LOG(ERROR) << "close() failed: " << strerror(errno);
}
return tmp_filepath;
}
}
}
LOG(FATAL) << "No temp directory found.";
std::abort();
#endif
}
namespace {
bool StartsWithSegment(tsl::StringPiece path, tsl::StringPiece segment) {
return tsl::str_util::StartsWith(path, segment) &&
(path.size() == segment.size() ||
path.at(segment.size()) == internal::kPathSep[0]);
}
}
bool GetTestWorkspaceDir(string* dir) {
const char* srcdir = getenv("TEST_SRCDIR");
if (srcdir == nullptr) {
return false;
}
const char* workspace = getenv("TEST_WORKSPACE");
if (workspace == nullptr) {
return false;
}
if (dir != nullptr) {
*dir = tsl::io::JoinPath(srcdir, workspace);
}
return true;
}
bool GetTestUndeclaredOutputsDir(string* dir) {
const char* outputs_dir = getenv("TEST_UNDECLARED_OUTPUTS_DIR");
if (outputs_dir == nullptr) {
return false;
}
if (dir != nullptr) {
*dir = outputs_dir;
}
return true;
}
bool ResolveTestPrefixes(tsl::StringPiece path, string& resolved_path) {
constexpr tsl::StringPiece kTestWorkspaceSegment = "TEST_WORKSPACE";
constexpr tsl::StringPiece kOutputDirSegment = "TEST_UNDECLARED_OUTPUTS_DIR";
if (StartsWithSegment(path, kTestWorkspaceSegment)) {
if (!GetTestWorkspaceDir(&resolved_path)) {
return false;
}
resolved_path += path.substr(kTestWorkspaceSegment.size());
return true;
} else if (StartsWithSegment(path, kOutputDirSegment)) {
if (!GetTestUndeclaredOutputsDir(&resolved_path)) {
return false;
}
resolved_path += path.substr(kOutputDirSegment.size());
return true;
} else {
resolved_path = path;
return true;
}
}
[[maybe_unused]] std::string& AppendDotExeIfWindows(std::string& path) {
#ifdef PLATFORM_WINDOWS
path.append(".exe");
#endif
return path;
}
}
} | #include "tsl/platform/path.h"
#include <string>
#include "tsl/platform/env.h"
#include "tsl/platform/stringpiece.h"
#include "tsl/platform/test.h"
namespace tsl {
namespace io {
TEST(PathTest, JoinPath) {
EXPECT_EQ("/foo/bar", JoinPath("/foo", "bar"));
EXPECT_EQ("foo/bar", JoinPath("foo", "bar"));
EXPECT_EQ("foo/bar", JoinPath("foo", "/bar"));
EXPECT_EQ("/foo/bar", JoinPath("/foo", "/bar"));
EXPECT_EQ("/bar", JoinPath("", "/bar"));
EXPECT_EQ("bar", JoinPath("", "bar"));
EXPECT_EQ("/foo", JoinPath("/foo", ""));
EXPECT_EQ("/foo/bar/baz/blah/blink/biz",
JoinPath("/foo/bar/baz/", "/blah/blink/biz"));
EXPECT_EQ("/foo/bar/baz/blah", JoinPath("/foo", "bar", "baz", "blah"));
}
TEST(PathTest, IsAbsolutePath) {
EXPECT_FALSE(IsAbsolutePath(""));
EXPECT_FALSE(IsAbsolutePath("../foo"));
EXPECT_FALSE(IsAbsolutePath("foo"));
EXPECT_FALSE(IsAbsolutePath("./foo"));
EXPECT_FALSE(IsAbsolutePath("foo/bar/baz/"));
EXPECT_TRUE(IsAbsolutePath("/foo"));
EXPECT_TRUE(IsAbsolutePath("/foo/bar/../baz"));
}
TEST(PathTest, Dirname) {
EXPECT_EQ("hdfs:
Dirname("hdfs:
EXPECT_EQ("/hello", Dirname("/hello/"));
EXPECT_EQ("/", Dirname("/hello"));
EXPECT_EQ("hello", Dirname("hello/world"));
EXPECT_EQ("hello", Dirname("hello/"));
EXPECT_EQ("", Dirname("world"));
EXPECT_EQ("/", Dirname("/"));
EXPECT_EQ("", Dirname(""));
}
TEST(PathTest, Basename) {
EXPECT_EQ("", Basename("/hello/"));
EXPECT_EQ("hello", Basename("/hello"));
EXPECT_EQ("world", Basename("hello/world"));
EXPECT_EQ("", Basename("hello/"));
EXPECT_EQ("world", Basename("world"));
EXPECT_EQ("", Basename("/"));
EXPECT_EQ("", Basename(""));
}
TEST(PathTest, Extension) {
EXPECT_EQ("gif", Extension("foo.gif"));
EXPECT_EQ("", Extension("foo."));
EXPECT_EQ("", Extension(""));
EXPECT_EQ("", Extension("/"));
EXPECT_EQ("", Extension("foo"));
EXPECT_EQ("", Extension("foo/"));
EXPECT_EQ("gif", Extension("/a/path/to/foo.gif"));
EXPECT_EQ("html", Extension("/a/path.bar/to/foo.html"));
EXPECT_EQ("", Extension("/a/path.bar/to/foo"));
EXPECT_EQ("baz", Extension("/a/path.bar/to/foo.bar.baz"));
}
TEST(PathTest, CleanPath) {
EXPECT_EQ(".", CleanPath(""));
EXPECT_EQ("x", CleanPath("x"));
EXPECT_EQ("/a/b/c/d", CleanPath("/a/b/c/d"));
EXPECT_EQ("/a/b/c/dtrue);
tsl::setenv("TEST_WORKSPACE", "my/workspace", true);
EXPECT_TRUE(GetTestWorkspaceDir(&dir));
EXPECT_EQ(dir, "/repo/src/my/workspace");
EXPECT_TRUE(GetTestWorkspaceDir(nullptr));
dir = kOriginalValue;
tsl::unsetenv("TEST_SRCDIR");
tsl::setenv("TEST_WORKSPACE", "my/workspace", true);
EXPECT_FALSE(GetTestWorkspaceDir(&dir));
EXPECT_EQ(dir, kOriginalValue);
EXPECT_FALSE(GetTestWorkspaceDir(nullptr));
dir = kOriginalValue;
tsl::setenv("TEST_SRCDIR", "/repo/src", true);
tsl::unsetenv("TEST_WORKSPACE");
EXPECT_FALSE(GetTestWorkspaceDir(&dir));
EXPECT_EQ(dir, kOriginalValue);
EXPECT_FALSE(GetTestWorkspaceDir(nullptr));
dir = kOriginalValue;
tsl::unsetenv("TEST_SRCDIR");
tsl::unsetenv("TEST_WORKSPACE");
EXPECT_FALSE(GetTestWorkspaceDir(&dir));
EXPECT_EQ(dir, kOriginalValue);
EXPECT_FALSE(GetTestWorkspaceDir(nullptr));
}
TEST(PathTest, GetTestUndeclaredOutputsDir) {
constexpr tsl::StringPiece kOriginalValue = "original value";
std::string dir;
dir = kOriginalValue;
tsl::setenv("TEST_UNDECLARED_OUTPUTS_DIR", "/test/outputs",
true);
EXPECT_TRUE(GetTestUndeclaredOutputsDir(&dir));
EXPECT_EQ(dir, "/test/outputs");
EXPECT_TRUE(GetTestUndeclaredOutputsDir(nullptr));
dir = kOriginalValue;
tsl::unsetenv("TEST_UNDECLARED_OUTPUTS_DIR");
EXPECT_FALSE(GetTestUndeclaredOutputsDir(&dir));
EXPECT_EQ(dir, kOriginalValue);
EXPECT_FALSE(GetTestUndeclaredOutputsDir(nullptr));
}
TEST(PathTest, ResolveTestPrefixesKeepsThePathUnchanged) {
constexpr tsl::StringPiece kOriginalValue = "original value";
std::string resolved_path;
resolved_path = kOriginalValue;
EXPECT_TRUE(ResolveTestPrefixes("", resolved_path));
EXPECT_EQ(resolved_path, "");
resolved_path = kOriginalValue;
EXPECT_TRUE(ResolveTestPrefixes("/", resolved_path));
EXPECT_EQ(resolved_path, "/");
resolved_path = kOriginalValue;
EXPECT_TRUE(ResolveTestPrefixes("alpha/beta", resolved_path));
EXPECT_EQ(resolved_path, "alpha/beta");
resolved_path = kOriginalValue;
EXPECT_TRUE(ResolveTestPrefixes("/alpha/beta", resolved_path));
EXPECT_EQ(resolved_path, "/alpha/beta");
}
TEST(PathTest, ResolveTestPrefixesCanResolveTestWorkspace) {
constexpr tsl::StringPiece kOriginalValue = "original value";
std::string resolved_path;
tsl::setenv("TEST_SRCDIR", "/repo/src", true);
tsl::setenv("TEST_WORKSPACE", "my/workspace", true);
resolved_path = kOriginalValue;
EXPECT_TRUE(ResolveTestPrefixes("TEST_WORKSPACE", resolved_path));
EXPECT_EQ(resolved_path, "/repo/src/my/workspace");
resolved_path = kOriginalValue;
EXPECT_TRUE(ResolveTestPrefixes("TEST_WORKSPACE/", resolved_path));
EXPECT_EQ(resolved_path, "/repo/src/my/workspace/");
resolved_path = kOriginalValue;
EXPECT_TRUE(ResolveTestPrefixes("TEST_WORKSPACE/a/b", resolved_path));
EXPECT_EQ(resolved_path, "/repo/src/my/workspace/a/b");
resolved_path = kOriginalValue;
EXPECT_TRUE(ResolveTestPrefixes("TEST_WORKSPACEE", resolved_path));
EXPECT_EQ(resolved_path, "TEST_WORKSPACEE");
resolved_path = kOriginalValue;
EXPECT_TRUE(ResolveTestPrefixes("/TEST_WORKSPACE", resolved_path));
EXPECT_EQ(resolved_path, "/TEST_WORKSPACE");
}
TEST(PathTest, ResolveTestPrefixesCannotResolveTestWorkspace) {
constexpr tsl::StringPiece kOriginalValue = "original value";
std::string resolved_path;
tsl::unsetenv("TEST_SRCDIR");
tsl::unsetenv("TEST_WORKSPACE");
resolved_path = kOriginalValue;
EXPECT_FALSE(ResolveTestPrefixes("TEST_WORKSPACE", resolved_path));
EXPECT_EQ(resolved_path, kOriginalValue);
}
TEST(PathTest, ResolveTestPrefixesCanResolveTestUndeclaredOutputsDir) {
constexpr tsl::StringPiece kOriginalValue = "original value";
std::string resolved_path;
tsl::setenv("TEST_UNDECLARED_OUTPUTS_DIR", "/test/outputs",
true);
resolved_path = kOriginalValue;
EXPECT_TRUE(
ResolveTestPrefixes("TEST_UNDECLARED_OUTPUTS_DIR", resolved_path));
EXPECT_EQ(resolved_path, "/test/outputs");
resolved_path = kOriginalValue;
EXPECT_TRUE(
ResolveTestPrefixes("TEST_UNDECLARED_OUTPUTS_DIR/", resolved_path));
EXPECT_EQ(resolved_path, "/test/outputs/");
resolved_path = kOriginalValue;
EXPECT_TRUE(
ResolveTestPrefixes("TEST_UNDECLARED_OUTPUTS_DIR/a/b", resolved_path));
EXPECT_EQ(resolved_path, "/test/outputs/a/b");
resolved_path = kOriginalValue;
EXPECT_TRUE(
ResolveTestPrefixes("TEST_UNDECLARED_OUTPUTS_DIRR", resolved_path));
EXPECT_EQ(resolved_path, "TEST_UNDECLARED_OUTPUTS_DIRR");
resolved_path = kOriginalValue;
EXPECT_TRUE(
ResolveTestPrefixes("/TEST_UNDECLARED_OUTPUTS_DIR", resolved_path));
EXPECT_EQ(resolved_path, "/TEST_UNDECLARED_OUTPUTS_DIR");
}
TEST(PathTest, ResolveTestPrefixesCannotResolveTestUndeclaredOutputsDir) {
constexpr tsl::StringPiece kOriginalValue = "original value";
std::string resolved_path;
tsl::unsetenv("TEST_UNDECLARED_OUTPUTS_DIR");
resolved_path = kOriginalValue;
EXPECT_FALSE(
ResolveTestPrefixes("TEST_UNDECLARED_OUTPUTS_DIR", resolved_path));
EXPECT_EQ(resolved_path, kOriginalValue);
}
}
} | 2,273 |
#ifndef TENSORFLOW_TSL_PLATFORM_DEFAULT_STATUS_H_
#define TENSORFLOW_TSL_PLATFORM_DEFAULT_STATUS_H_
#define MAYBE_ADD_SOURCE_LOCATION(status) \
{}
#define ADD_SOURCE_LOCATION(status) status
#endif
#include "tsl/platform/status.h"
#include <stdio.h>
#include <deque>
#include <functional>
#include <memory>
#include <ostream>
#include <sstream>
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>
#include "absl/base/call_once.h"
#include "absl/functional/function_ref.h"
#include "absl/status/status.h"
#include "absl/strings/cord.h"
#include "absl/strings/escaping.h"
#include "absl/strings/match.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_join.h"
#include "absl/strings/str_replace.h"
#include "absl/strings/str_split.h"
#include "absl/strings/string_view.h"
#include "absl/types/optional.h"
#include "tsl/platform/mutex.h"
#include "tsl/platform/stack_frame.h"
#include "tsl/platform/stacktrace.h"
#include "tsl/platform/str_util.h"
#include "tsl/platform/strcat.h"
#include "tsl/platform/stringprintf.h"
#include "tsl/protobuf/error_codes.pb.h"
namespace tsl {
namespace {
class StatusLogSink : public TFLogSink {
public:
static StatusLogSink* GetInstance() {
static StatusLogSink* sink = new StatusLogSink();
return sink;
}
void enable() {
absl::call_once(flag_, [this] {
num_messages_ = 5;
if (const char* num_msgs_str =
getenv("TF_WORKER_NUM_FORWARDED_LOG_MESSAGES")) {
if (!absl::SimpleAtoi(num_msgs_str, &num_messages_)) {
LOG(WARNING) << "Failed to parse env variable "
"TF_WORKER_NUM_WARNING_ERROR_LOG_IN_STATUS="
<< num_msgs_str << " as int. Using the default value "
<< num_messages_ << ".";
}
}
if (num_messages_ > 0) {
TFAddLogSink(this);
}
});
}
void GetMessages(std::vector<std::string>* logs) TF_LOCKS_EXCLUDED(mu_) {
mutex_lock lock(mu_);
for (auto& msg : messages_) {
logs->push_back(msg);
}
}
void Send(const TFLogEntry& entry) override TF_LOCKS_EXCLUDED(mu_) {
if (entry.log_severity() < absl::LogSeverity::kWarning) return;
mutex_lock lock(mu_);
messages_.emplace_back(entry.ToString());
if (messages_.size() > static_cast<size_t>(num_messages_)) {
messages_.pop_front();
}
}
private:
mutex mu_;
absl::once_flag flag_;
int num_messages_ = 0;
std::deque<std::string> messages_ TF_GUARDED_BY(mu_);
};
}
namespace errors {
static constexpr const char kStackTraceProtoUrl[] =
"type.googleapis.com/tensorflow.StackTracePayload";
void SetStackTrace(absl::Status& status, std::vector<StackFrame> stack_trace) {
std::vector<std::string> items;
items.reserve(stack_trace.size());
for (StackFrame& frame : stack_trace) {
items.push_back(
absl::StrCat(absl::StrReplaceAll(frame.file_name, {{"\n", ""}}), "\n",
frame.line_number, "\n",
absl::StrReplaceAll(frame.function_name, {{"\n", ""}})));
}
status.SetPayload(kStackTraceProtoUrl,
absl::Cord(absl::StrJoin(items, "\n")));
}
std::vector<StackFrame> GetStackTrace(const absl::Status& status) {
std::vector<StackFrame> stack_trace;
absl::optional<absl::Cord> maybe_serialized_payload =
status.GetPayload(kStackTraceProtoUrl);
if (maybe_serialized_payload.has_value()) {
std::vector<std::string> split =
absl::StrSplit(maybe_serialized_payload.value().Flatten(), '\n');
assert(split.size() % 3 == 0);
for (int i = 0; i < split.size() / 3; ++i) {
const int idx = 3 * i;
int line_number = -1;
CHECK(absl::SimpleAtoi(split[idx + 1], &line_number));
stack_trace.emplace_back(std::move(split[idx]), line_number,
std::move(split[idx + 2]));
}
}
return stack_trace;
}
}
#ifdef _WIN32
const char* NullTerminatedMessage(const absl::Status& status) {
return absl::StatusMessageAsCStr(status);
}
#endif
std::string* TfCheckOpHelperOutOfLine(const absl::Status& v, const char* msg) {
std::stringstream ss;
ss << "Non-OK-status: " << msg << "\nStatus: " << v;
return new std::string(ss.str());
}
StatusGroup::StatusGroup() {}
StatusGroup::StatusGroup(std::initializer_list<absl::Status> statuses) {
for (const absl::Status& s : statuses) {
Update(s);
}
}
static constexpr const char kDerivedStatusProtoUrl[] =
"type.googleapis.com/tensorflow.DerivedStatus";
absl::Status StatusGroup::MakeDerived(const absl::Status& s) {
if (IsDerived(s)) {
return s;
} else {
absl::Status derived(s);
derived.SetPayload(kDerivedStatusProtoUrl, absl::Cord(""));
return derived;
}
}
bool StatusGroup::IsDerived(const absl::Status& s) {
return s.GetPayload(kDerivedStatusProtoUrl).has_value();
}
void StatusGroup::ConfigureLogHistory() {
StatusLogSink::GetInstance()->enable();
}
void StatusGroup::Update(const absl::Status& s) {
if (s.ok()) {
++num_ok_;
} else {
ok_ = false;
if (IsDerived(s)) {
derived_.insert(s);
} else {
non_derived_.insert(s);
}
}
}
static constexpr int kMaxAggregatedStatusMessageSize = 8 * 1024;
static constexpr int kMaxAttachedLogMessageSize = 512;
std::unordered_map<std::string, absl::Cord> StatusGroup::GetPayloads() const {
std::unordered_map<std::string, absl::Cord> payloads;
auto capture_payload = [&payloads](absl::string_view key,
const absl::Cord& value) {
payloads[std::string(key)] = value;
};
for (const auto& status : derived_) {
status.ForEachPayload(capture_payload);
}
for (const auto& status : non_derived_) {
status.ForEachPayload(capture_payload);
}
payloads.erase(kDerivedStatusProtoUrl);
return payloads;
}
absl::Status MakeStatus(
absl::StatusCode code, absl::string_view message,
const std::unordered_map<std::string, absl::Cord>& payloads) {
absl::Status status(code, message);
for (const auto& payload : payloads) {
status.SetPayload(payload.first, payload.second);
}
return status;
}
std::string MakeString(const absl::Status& status) {
return absl::StrCat(absl::StatusCodeToString(status.code()), ": ",
status.message());
}
absl::Status StatusGroup::as_summary_status() const {
if (ok_) {
return absl::OkStatus();
}
auto get_recent_logs = [this]() -> std::string {
if (!recent_logs_.empty()) {
std::vector<std::string> fmt;
fmt.push_back("\nRecent warning and error logs:");
for (auto& log : recent_logs_) {
fmt.push_back(" " + log.substr(0, kMaxAttachedLogMessageSize));
}
return absl::StrJoin(fmt, "\n");
} else {
return "";
}
};
if (non_derived_.size() == 1) {
return MakeStatus(
non_derived_.begin()->code(),
strings::StrCat(non_derived_.begin()->message(), get_recent_logs()),
GetPayloads());
}
if (!non_derived_.empty()) {
std::vector<std::string> fmt;
fmt.push_back(
strings::Printf("%zu root error(s) found.", non_derived_.size()));
int index = 0;
auto code = absl::StatusCode::kCancelled;
for (const auto& s : non_derived_) {
if (code == absl::StatusCode::kCancelled &&
s.code() != absl::StatusCode::kCancelled) {
code = s.code();
}
fmt.emplace_back(strings::StrCat(" (", index, ") ", MakeString(s)));
++index;
}
fmt.push_back(strings::Printf("%zu successful operations.", num_ok_));
fmt.push_back(
strings::Printf("%zu derived errors ignored.", derived_.size()));
std::string error_msg =
absl::StrJoin(fmt, "\n").substr(0, kMaxAggregatedStatusMessageSize);
return MakeStatus(code, strings::StrCat(error_msg, get_recent_logs()),
GetPayloads());
} else {
return MakeDerived(MakeStatus(derived_.begin()->code(),
derived_.begin()->message(), GetPayloads()));
}
}
absl::Status StatusGroup::as_concatenated_status() const {
if (ok_) {
return absl::OkStatus();
}
if (non_derived_.size() == 1) {
return MakeStatus(non_derived_.begin()->code(),
non_derived_.begin()->message(), GetPayloads());
}
if (!non_derived_.empty()) {
std::vector<string> fmt;
fmt.emplace_back("\n=====================");
for (const auto& s : non_derived_) {
fmt.emplace_back(MakeString(s));
}
fmt.emplace_back("=====================\n");
return MakeStatus(
non_derived_.begin()->code(),
absl::StrJoin(fmt, "\n").substr(0, kMaxAggregatedStatusMessageSize),
GetPayloads());
} else {
return MakeDerived(MakeStatus(derived_.begin()->code(),
derived_.begin()->message(), GetPayloads()));
}
}
void StatusGroup::AttachLogMessages() {
recent_logs_.clear();
StatusLogSink::GetInstance()->GetMessages(&recent_logs_);
}
} | #include "tsl/platform/status.h"
#include <unordered_map>
#include <vector>
#include "absl/status/status.h"
#include "absl/strings/cord.h"
#include "absl/strings/str_format.h"
#include "tsl/platform/errors.h"
#include "tsl/platform/stack_frame.h"
#include "tsl/platform/status_matchers.h"
#include "tsl/platform/status_to_from_proto.h"
#include "tsl/platform/test.h"
#include "tsl/protobuf/error_codes.pb.h"
#include "tsl/protobuf/status.pb.h"
namespace tsl {
namespace {
using ::testing::IsEmpty;
using ::tsl::testing::IsOk;
using ::tsl::testing::StatusIs;
TEST(ToStringTest, PayloadsArePrinted) {
absl::Status status = errors::Aborted("Aborted Error Message");
status.SetPayload("payload_key", absl::Cord(absl::StrFormat(
"payload_value %c%c%c", 1, 2, 3)));
EXPECT_EQ(status.ToString(),
"ABORTED: Aborted Error Message [payload_key='payload_value "
"\\x01\\x02\\x03']");
}
TEST(ToStringTest, MatchesAbslStatus) {
absl::Status status = errors::Aborted("Aborted Error Message");
status.SetPayload("payload_key", absl::Cord(absl::StrFormat(
"payload_value %c%c%c", 1, 2, 3)));
absl::Status absl_status =
absl::Status(absl::StatusCode::kAborted, status.message());
absl_status.SetPayload("payload_key", absl::Cord(absl::StrFormat(
"payload_value %c%c%c", 1, 2, 3)));
EXPECT_EQ(status.ToString(), absl_status.ToString());
}
TEST(StackTrace, SerializeAndDeserializeCorrectly) {
absl::Status status = errors::Aborted("Aborted Error Message");
std::vector<StackFrame> stack_trace;
stack_trace.push_back(StackFrame("filename_1", 33, "func_name_1"));
stack_trace.push_back(StackFrame("filename_2", 66, "func_name_2"));
errors::SetStackTrace(status, stack_trace);
std::vector<StackFrame> deserialized = errors::GetStackTrace(status);
EXPECT_EQ(stack_trace.size(), deserialized.size());
for (size_t i = 0; i < stack_trace.size(); ++i) {
EXPECT_EQ(stack_trace[i], deserialized[i]);
}
}
TEST(StatusGroupTest, DeterministicOrderWithoutPayloads) {
absl::Status status_a = errors::Aborted("Status A");
absl::Status status_b = errors::Aborted("Status B");
absl::Status status_c = errors::Aborted("Status C");
absl::Status combined =
StatusGroup({status_a, status_b, status_c}).as_summary_status();
EXPECT_EQ(combined,
StatusGroup({status_a, status_b, status_c}).as_summary_status());
EXPECT_EQ(combined,
StatusGroup({status_a, status_c, status_b}).as_summary_status());
EXPECT_EQ(combined,
StatusGroup({status_b, status_a, status_c}).as_summary_status());
EXPECT_EQ(combined,
StatusGroup({status_b, status_c, status_a}).as_summary_status());
EXPECT_EQ(combined,
StatusGroup({status_c, status_a, status_b}).as_summary_status());
EXPECT_EQ(combined,
StatusGroup({status_c, status_b, status_a}).as_summary_status());
}
TEST(StatusGroupTest, DeterministicOrderWithPayloads) {
absl::Status status_a = errors::Aborted("Status A");
status_a.SetPayload("payload_key", absl::Cord("payload_value_a"));
absl::Status status_b = errors::Aborted("Status B");
status_b.SetPayload("payload_key", absl::Cord("payload_value_b"));
absl::Status status_c = errors::Aborted("Status C");
status_c.SetPayload("payload_key", absl::Cord("payload_value_c"));
absl::Status combined =
StatusGroup({status_a, status_b, status_c}).as_summary_status();
ASSERT_TRUE(combined.GetPayload("payload_key").has_value());
std::string payload(combined.GetPayload("payload_key").value());
EXPECT_EQ(payload, StatusGroup({status_a, status_b, status_c})
.as_summary_status()
.GetPayload("payload_key"));
EXPECT_EQ(payload, StatusGroup({status_a, status_c, status_b})
.as_summary_status()
.GetPayload("payload_key"));
EXPECT_EQ(payload, StatusGroup({status_b, status_a, status_c})
.as_summary_status()
.GetPayload("payload_key"));
EXPECT_EQ(payload, StatusGroup({status_b, status_c, status_a})
.as_summary_status()
.GetPayload("payload_key"));
EXPECT_EQ(payload, StatusGroup({status_c, status_a, status_b})
.as_summary_status()
.GetPayload("payload_key"));
EXPECT_EQ(payload, StatusGroup({status_c, status_b, status_a})
.as_summary_status()
.GetPayload("payload_key"));
}
TEST(StatusGroupTest, PayloadsMergedProperly) {
absl::Status status_a = errors::Aborted("Status A");
status_a.SetPayload("payload_key_a",
absl::Cord(std::string("payload_value_a")));
absl::Status status_b = errors::Aborted("Status B");
status_b.SetPayload("payload_key_b",
absl::Cord(std::string("payload_value_b")));
absl::Status status_c = errors::Aborted("Status C");
status_c.SetPayload("payload_key_c",
absl::Cord(std::string("payload_value_c")));
absl::Status derived_status_c =
StatusGroup::MakeDerived(errors::Aborted("Status C"));
derived_status_c.SetPayload(
"payload_key_c", absl::Cord(std::string("derived_payload_value_c")));
StatusGroup status_group({status_a, status_b, status_c, derived_status_c});
EXPECT_THAT(status_group.GetPayloads(), ::testing::SizeIs(3));
absl::Status combined = status_group.as_summary_status();
EXPECT_EQ(combined.GetPayload("payload_key_a"), "payload_value_a");
EXPECT_EQ(combined.GetPayload("payload_key_b"), "payload_value_b");
EXPECT_EQ(combined.GetPayload("payload_key_c"), "payload_value_c");
}
TEST(Status, ErrorStatusForEachPayloadIteratesOverAll) {
absl::Status s(absl::StatusCode::kInternal, "Error message");
s.SetPayload("key1", absl::Cord("value1"));
s.SetPayload("key2", absl::Cord("value2"));
s.SetPayload("key3", absl::Cord("value3"));
std::unordered_map<std::string, absl::Cord> payloads;
s.ForEachPayload([&payloads](StringPiece key, const absl::Cord& value) {
payloads[std::string(key)] = value;
});
EXPECT_EQ(payloads.size(), 3);
EXPECT_EQ(payloads["key1"], "value1");
EXPECT_EQ(payloads["key2"], "value2");
EXPECT_EQ(payloads["key3"], "value3");
}
TEST(Status, OkStatusForEachPayloadNoIteration) {
absl::Status s = absl::OkStatus();
s.SetPayload("key1", absl::Cord("value1"));
s.SetPayload("key2", absl::Cord("value2"));
s.SetPayload("key3", absl::Cord("value3"));
std::unordered_map<std::string, absl::Cord> payloads;
s.ForEachPayload([&payloads](StringPiece key, const absl::Cord& value) {
payloads[std::string(key)] = value;
});
EXPECT_EQ(payloads.size(), 0);
}
TEST(Status, SaveOKStatusToProto) {
tensorflow::StatusProto status_proto = StatusToProto(absl::OkStatus());
EXPECT_EQ(status_proto.code(), error::OK);
EXPECT_THAT(status_proto.message(), IsEmpty());
}
TEST(Status, SaveErrorStatusToProto) {
tensorflow::StatusProto status_proto =
StatusToProto(errors::NotFound("Not found"));
EXPECT_EQ(status_proto.code(), error::NOT_FOUND);
EXPECT_EQ(status_proto.message(), "Not found");
}
TEST(Status, SaveEmptyStatusToProto) {
tensorflow::StatusProto status_proto = StatusToProto(absl::Status());
EXPECT_EQ(status_proto.code(), error::OK);
EXPECT_THAT(status_proto.message(), IsEmpty());
}
TEST(Status, MakeOKStatusFromProto) {
tensorflow::StatusProto status_proto;
status_proto.set_code(error::OK);
EXPECT_THAT(StatusFromProto(status_proto), IsOk());
}
TEST(Status, MakeErrorStatusFromProto) {
tensorflow::StatusProto status_proto;
status_proto.set_code(error::INVALID_ARGUMENT);
status_proto.set_message("Invalid argument");
EXPECT_THAT(StatusFromProto(status_proto),
StatusIs(error::INVALID_ARGUMENT, "Invalid argument"));
}
TEST(Status, MakeStatusFromEmptyProto) {
EXPECT_THAT(StatusFromProto(tensorflow::StatusProto()), IsOk());
}
}
} | 2,274 |
#ifndef TENSORFLOW_TSL_PLATFORM_CLOUD_GCS_THROTTLE_H_
#define TENSORFLOW_TSL_PLATFORM_CLOUD_GCS_THROTTLE_H_
#include "tsl/platform/env.h"
namespace tsl {
struct GcsThrottleConfig {
bool enabled = false;
int64_t token_rate =
100000;
int64_t bucket_size = 10000000;
int64_t tokens_per_request = 100;
int64_t initial_tokens = 0;
};
class GcsThrottle {
public:
explicit GcsThrottle(EnvTime* env_time = nullptr);
bool AdmitRequest();
void RecordResponse(size_t num_bytes);
void SetConfig(GcsThrottleConfig config);
inline int64_t available_tokens() TF_LOCKS_EXCLUDED(mu_) {
mutex_lock l(mu_);
UpdateState();
return available_tokens_;
}
bool is_enabled() TF_LOCKS_EXCLUDED(mu_) {
mutex_lock l(mu_);
return config_.enabled;
}
private:
void UpdateState() TF_EXCLUSIVE_LOCKS_REQUIRED(mu_);
inline uint64 request_bytes_to_tokens(size_t num_bytes) {
return num_bytes >> 10;
}
mutex mu_;
uint64 last_updated_secs_ TF_GUARDED_BY(mu_) = 0;
int64_t available_tokens_ TF_GUARDED_BY(mu_) = 0;
EnvTime* const env_time_;
GcsThrottleConfig config_ TF_GUARDED_BY(mu_);
};
}
#endif
#include "tsl/platform/cloud/gcs_throttle.h"
#include <algorithm>
namespace tsl {
namespace {
EnvTime* get_default_env_time() {
static EnvTime* default_env_time = new EnvTime;
return default_env_time;
}
}
GcsThrottle::GcsThrottle(EnvTime* env_time)
: last_updated_secs_(env_time ? env_time->GetOverridableNowSeconds()
: EnvTime::NowSeconds()),
available_tokens_(0),
env_time_(env_time ? env_time : get_default_env_time()) {}
bool GcsThrottle::AdmitRequest() {
mutex_lock l(mu_);
UpdateState();
if (available_tokens_ < config_.tokens_per_request) {
return false || !config_.enabled;
}
available_tokens_ -= config_.tokens_per_request;
return true;
}
void GcsThrottle::RecordResponse(size_t num_bytes) {
mutex_lock l(mu_);
UpdateState();
available_tokens_ -= request_bytes_to_tokens(num_bytes);
}
void GcsThrottle::SetConfig(GcsThrottleConfig config) {
mutex_lock l(mu_);
config_ = config;
available_tokens_ = config.initial_tokens;
last_updated_secs_ = env_time_->GetOverridableNowSeconds();
}
void GcsThrottle::UpdateState() {
int64_t now = env_time_->GetOverridableNowSeconds();
uint64 delta_secs =
std::max(int64_t{0}, now - static_cast<int64_t>(last_updated_secs_));
available_tokens_ += delta_secs * config_.token_rate;
available_tokens_ = std::min(available_tokens_, config_.bucket_size);
last_updated_secs_ = now;
}
} | #include "tsl/platform/cloud/gcs_throttle.h"
#include "tsl/lib/core/status_test_util.h"
#include "tsl/platform/str_util.h"
#include "tsl/platform/test.h"
namespace tsl {
namespace {
class TestTime : public EnvTime {
public:
uint64 GetOverridableNowNanos() const override {
return now_micros_ * kMicrosToNanos;
}
void SetTime(uint64 now_micros) { now_micros_ = now_micros; }
void AdvanceSeconds(int64_t secs) { now_micros_ += secs * kSecondsToMicros; }
private:
uint64 now_micros_ = 1234567890000000ULL;
};
class GcsThrottleTest : public ::testing::Test {
protected:
GcsThrottleTest() : throttle_(&time_) {
config_.enabled = true;
throttle_.SetConfig(config_);
}
GcsThrottleConfig config_;
TestTime time_;
GcsThrottle throttle_;
};
TEST_F(GcsThrottleTest, ReplenishTokens) {
EXPECT_EQ(0, throttle_.available_tokens());
time_.AdvanceSeconds(1);
EXPECT_EQ(100000, throttle_.available_tokens());
time_.AdvanceSeconds(2);
EXPECT_EQ(300000, throttle_.available_tokens());
}
TEST_F(GcsThrottleTest, RejectRequest) {
EXPECT_EQ(0, throttle_.available_tokens());
time_.AdvanceSeconds(1);
EXPECT_TRUE(throttle_.AdmitRequest());
EXPECT_EQ(99900, throttle_.available_tokens());
for (int i = 1; i < 1000; i++) {
EXPECT_TRUE(throttle_.AdmitRequest());
}
EXPECT_FALSE(throttle_.AdmitRequest());
}
TEST_F(GcsThrottleTest, MarkResponses) {
time_.AdvanceSeconds(1);
EXPECT_TRUE(throttle_.AdmitRequest());
throttle_.RecordResponse(128000000);
EXPECT_EQ(-25100, throttle_.available_tokens());
EXPECT_FALSE(throttle_.AdmitRequest());
time_.AdvanceSeconds(1);
EXPECT_TRUE(throttle_.AdmitRequest())
<< "Available tokens: " << throttle_.available_tokens();
}
TEST_F(GcsThrottleTest, Skippingtime_) {
EXPECT_EQ(0, throttle_.available_tokens());
time_.AdvanceSeconds(90);
EXPECT_EQ(9000000, throttle_.available_tokens());
}
TEST_F(GcsThrottleTest, BucketLimit) {
time_.AdvanceSeconds(120);
EXPECT_EQ(10000000, throttle_.available_tokens());
}
TEST_F(GcsThrottleTest, ReverseTime) {
time_.AdvanceSeconds(1);
EXPECT_EQ(100000, throttle_.available_tokens());
time_.AdvanceSeconds(-3600);
EXPECT_EQ(100000, throttle_.available_tokens());
time_.AdvanceSeconds(1);
EXPECT_EQ(200000, throttle_.available_tokens());
}
TEST(GcsThrottleDisabledTest, Disabled) {
TestTime time;
GcsThrottle throttle(&time);
ASSERT_FALSE(throttle.is_enabled());
EXPECT_EQ(0, throttle.available_tokens());
time.AdvanceSeconds(1);
EXPECT_EQ(100000, throttle.available_tokens());
EXPECT_TRUE(throttle.AdmitRequest());
EXPECT_EQ(99900, throttle.available_tokens());
time.AdvanceSeconds(1);
EXPECT_EQ(199900, throttle.available_tokens());
throttle.RecordResponse(128000000);
EXPECT_LT(0, throttle.available_tokens());
EXPECT_TRUE(throttle.AdmitRequest());
}
}
} | 2,275 |
#ifndef TENSORFLOW_TSL_PLATFORM_CLOUD_CURL_HTTP_REQUEST_H_
#define TENSORFLOW_TSL_PLATFORM_CLOUD_CURL_HTTP_REQUEST_H_
#include <string>
#include <unordered_map>
#include <vector>
#include <curl/curl.h>
#include "tsl/platform/cloud/http_request.h"
#include "tsl/platform/env.h"
#include "tsl/platform/errors.h"
#include "tsl/platform/macros.h"
#include "tsl/platform/protobuf.h"
#include "tsl/platform/status.h"
#include "tsl/platform/stringpiece.h"
#include "tsl/platform/types.h"
namespace tsl {
class LibCurl;
class CurlHttpRequest : public HttpRequest {
public:
class Factory : public HttpRequest::Factory {
public:
virtual ~Factory() {}
virtual HttpRequest* Create() { return new CurlHttpRequest(); }
};
CurlHttpRequest();
explicit CurlHttpRequest(LibCurl* libcurl)
: CurlHttpRequest(libcurl, Env::Default()) {}
CurlHttpRequest(LibCurl* libcurl, Env* env);
~CurlHttpRequest() override;
void SetUri(const string& uri) override;
void SetRange(uint64 start, uint64 end) override;
void AddHeader(const string& name, const string& value) override;
void AddResolveOverride(const string& hostname, int64_t port,
const string& ip_addr) override;
void AddAuthBearerHeader(const string& auth_token) override;
void SetRequestStats(RequestStats* stats) override;
void SetDeleteRequest() override;
Status SetPutFromFile(const string& body_filepath, size_t offset) override;
void SetPutEmptyBody() override;
void SetPostFromBuffer(const char* buffer, size_t size) override;
void SetPostEmptyBody() override;
void SetResultBuffer(std::vector<char>* out_buffer) override;
void SetResultBufferDirect(char* buffer, size_t size) override;
bool IsDirectResponse() const;
size_t GetResultBufferDirectBytesTransferred() override;
string GetResponseHeader(const string& name) const override;
uint64 GetResponseCode() const override;
Status Send() override;
string EscapeString(const string& str) override;
void SetTimeouts(uint32 connection, uint32 inactivity, uint32 total) override;
private:
static size_t WriteCallback(const void* ptr, size_t size, size_t nmemb,
void* userdata);
static size_t WriteCallbackDirect(const void* ptr, size_t size, size_t nmemb,
void* userdata);
static size_t ReadCallback(void* ptr, size_t size, size_t nmemb,
FILE* userdata);
static size_t HeaderCallback(const void* ptr, size_t size, size_t nmemb,
void* this_object);
static int ProgressCallback(void* this_object, curl_off_t dltotal,
curl_off_t dlnow, curl_off_t ultotal,
curl_off_t ulnow);
void CheckMethodNotSet() const;
void CheckNotSent() const;
StringPiece GetResponse() const;
Status CURLcodeToStatus(CURLcode code, const char* error_buffer);
LibCurl* libcurl_;
Env* env_;
FILE* put_body_ = nullptr;
StringPiece post_body_buffer_;
size_t post_body_read_ = 0;
std::vector<char>* response_buffer_ = nullptr;
struct DirectResponseState {
char* buffer_;
size_t buffer_size_;
size_t bytes_transferred_;
size_t bytes_received_;
};
DirectResponseState direct_response_ = {};
CURL* curl_ = nullptr;
curl_slist* curl_headers_ = nullptr;
curl_slist* resolve_list_ = nullptr;
RequestStats* stats_ = nullptr;
std::vector<char> default_response_buffer_;
std::unordered_map<string, string> response_headers_;
uint64 response_code_ = 0;
uint64 last_progress_timestamp_ = 0;
curl_off_t last_progress_bytes_ = 0;
uint32 inactivity_timeout_secs_ = 60;
uint32 connect_timeout_secs_ = 120;
uint32 request_timeout_secs_ = 3600;
bool is_uri_set_ = false;
bool is_method_set_ = false;
bool is_sent_ = false;
string uri_;
RequestMethod method_ = RequestMethod::kGet;
const size_t response_to_error_limit_ = 500;
CurlHttpRequest(const CurlHttpRequest&) = delete;
void operator=(const CurlHttpRequest&) = delete;
};
class LibCurl {
public:
virtual ~LibCurl() {}
virtual CURL* curl_easy_init() = 0;
virtual CURLcode curl_easy_setopt(CURL* curl, CURLoption option,
uint64 param) TF_MUST_USE_RESULT = 0;
virtual CURLcode curl_easy_setopt(CURL* curl, CURLoption option,
const char* param) TF_MUST_USE_RESULT = 0;
virtual CURLcode curl_easy_setopt(CURL* curl, CURLoption option,
void* param) TF_MUST_USE_RESULT = 0;
virtual CURLcode curl_easy_setopt(
CURL* curl, CURLoption option,
size_t (*param)(void*, size_t, size_t, FILE*)) TF_MUST_USE_RESULT = 0;
virtual CURLcode curl_easy_setopt(CURL* curl, CURLoption option,
size_t (*param)(const void*, size_t, size_t,
void*))
TF_MUST_USE_RESULT = 0;
virtual CURLcode curl_easy_setopt(
CURL* curl, CURLoption option,
int (*param)(void* clientp, curl_off_t dltotal, curl_off_t dlnow,
curl_off_t ultotal,
curl_off_t ulnow)) TF_MUST_USE_RESULT = 0;
virtual CURLcode curl_easy_perform(CURL* curl) TF_MUST_USE_RESULT = 0;
virtual CURLcode curl_easy_getinfo(CURL* curl, CURLINFO info,
uint64* value) TF_MUST_USE_RESULT = 0;
virtual CURLcode curl_easy_getinfo(CURL* curl, CURLINFO info,
double* value) TF_MUST_USE_RESULT = 0;
virtual void curl_easy_cleanup(CURL* curl) = 0;
virtual curl_slist* curl_slist_append(curl_slist* list, const char* str) = 0;
virtual void curl_slist_free_all(curl_slist* list) = 0;
virtual char* curl_easy_escape(CURL* curl, const char* str, int length) = 0;
virtual void curl_free(void* p) = 0;
};
}
#endif
#include "tsl/platform/cloud/curl_http_request.h"
#include <algorithm>
#include "xla/tsl/util/env_var.h"
#include "tsl/lib/gtl/map_util.h"
#include "tsl/platform/errors.h"
#include "tsl/platform/macros.h"
#include "tsl/platform/scanner.h"
#include "tsl/platform/str_util.h"
#include "tsl/platform/types.h"
#define CHECK_CURL_OK(expr) CHECK_EQ(expr, CURLE_OK)
namespace tsl {
namespace {
constexpr uint64 kVerboseOutput = 0;
class LibCurlProxy : public LibCurl {
public:
static LibCurlProxy* Load() {
static LibCurlProxy* libcurl = []() -> LibCurlProxy* {
curl_global_init(CURL_GLOBAL_ALL);
return new LibCurlProxy;
}();
return libcurl;
}
CURL* curl_easy_init() override { return ::curl_easy_init(); }
CURLcode curl_easy_setopt(CURL* curl, CURLoption option,
uint64 param) override {
return ::curl_easy_setopt(curl, option, param);
}
CURLcode curl_easy_setopt(CURL* curl, CURLoption option,
const char* param) override {
return ::curl_easy_setopt(curl, option, param);
}
CURLcode curl_easy_setopt(CURL* curl, CURLoption option,
void* param) override {
return ::curl_easy_setopt(curl, option, param);
}
CURLcode curl_easy_setopt(CURL* curl, CURLoption option,
size_t (*param)(void*, size_t, size_t,
FILE*)) override {
return ::curl_easy_setopt(curl, option, param);
}
CURLcode curl_easy_setopt(CURL* curl, CURLoption option,
size_t (*param)(const void*, size_t, size_t,
void*)) override {
return ::curl_easy_setopt(curl, option, param);
}
CURLcode curl_easy_setopt(CURL* curl, CURLoption option,
int (*param)(void* clientp, curl_off_t dltotal,
curl_off_t dlnow, curl_off_t ultotal,
curl_off_t ulnow)) override {
return ::curl_easy_setopt(curl, option, param);
}
CURLcode curl_easy_perform(CURL* curl) override {
return ::curl_easy_perform(curl);
}
CURLcode curl_easy_getinfo(CURL* curl, CURLINFO info,
uint64* value) override {
return ::curl_easy_getinfo(curl, info, value);
}
CURLcode curl_easy_getinfo(CURL* curl, CURLINFO info,
double* value) override {
return ::curl_easy_getinfo(curl, info, value);
}
void curl_easy_cleanup(CURL* curl) override {
return ::curl_easy_cleanup(curl);
}
char* curl_easy_escape(CURL* curl, const char* str, int length) override {
return ::curl_easy_escape(curl, str, length);
}
curl_slist* curl_slist_append(curl_slist* list, const char* str) override {
return ::curl_slist_append(list, str);
}
void curl_slist_free_all(curl_slist* list) override {
return ::curl_slist_free_all(list);
}
void curl_free(void* p) override { ::curl_free(p); }
};
}
CurlHttpRequest::CurlHttpRequest() : CurlHttpRequest(LibCurlProxy::Load()) {}
CurlHttpRequest::CurlHttpRequest(LibCurl* libcurl, Env* env)
: libcurl_(libcurl), env_(env) {
default_response_buffer_.reserve(CURL_MAX_WRITE_SIZE);
curl_ = libcurl_->curl_easy_init();
CHECK(curl_ != nullptr) << "Couldn't initialize a curl session.";
std::string value = "";
TF_CHECK_OK(ReadStringFromEnvVar("CURL_CA_BUNDLE", "", &value));
if (!value.empty()) {
CHECK_CURL_OK(
libcurl_->curl_easy_setopt(curl_, CURLOPT_CAINFO, value.c_str()));
}
CHECK_CURL_OK(
libcurl_->curl_easy_setopt(curl_, CURLOPT_VERBOSE, kVerboseOutput));
CHECK_CURL_OK(libcurl_->curl_easy_setopt(curl_, CURLOPT_USERAGENT, "TSL"));
CHECK_CURL_OK(libcurl_->curl_easy_setopt(curl_, CURLOPT_NOSIGNAL, 1L));
CHECK_CURL_OK(libcurl_->curl_easy_setopt(curl_, CURLOPT_HTTP_VERSION,
CURL_HTTP_VERSION_1_1));
CHECK_CURL_OK(
libcurl_->curl_easy_setopt(curl_, CURLOPT_NOPROGRESS, uint64{0}));
CHECK_CURL_OK(libcurl_->curl_easy_setopt(curl_, CURLOPT_XFERINFODATA, this));
CHECK_CURL_OK(libcurl_->curl_easy_setopt(curl_, CURLOPT_XFERINFOFUNCTION,
&CurlHttpRequest::ProgressCallback));
SetResultBuffer(&default_response_buffer_);
}
CurlHttpRequest::~CurlHttpRequest() {
if (curl_headers_) {
libcurl_->curl_slist_free_all(curl_headers_);
}
if (resolve_list_) {
libcurl_->curl_slist_free_all(resolve_list_);
}
if (put_body_) {
if (fclose(put_body_) != 0) {
LOG(ERROR) << "fclose() failed: " << strerror(errno);
}
}
if (curl_) {
libcurl_->curl_easy_cleanup(curl_);
}
}
string CurlHttpRequest::EscapeString(const string& str) {
char* out_char_str = libcurl_->curl_easy_escape(curl_, str.c_str(), 0);
string out_str(out_char_str);
libcurl_->curl_free(out_char_str);
return out_str;
}
void CurlHttpRequest::SetUri(const string& uri) {
CheckNotSent();
is_uri_set_ = true;
uri_ = uri;
CHECK_CURL_OK(libcurl_->curl_easy_setopt(curl_, CURLOPT_URL, uri.c_str()));
}
void CurlHttpRequest::SetRange(uint64 start, uint64 end) {
CheckNotSent();
CHECK_CURL_OK(libcurl_->curl_easy_setopt(
curl_, CURLOPT_RANGE, strings::StrCat(start, "-", end).c_str()));
}
void CurlHttpRequest::AddHeader(const string& name, const string& value) {
CheckNotSent();
curl_headers_ = libcurl_->curl_slist_append(
curl_headers_, strings::StrCat(name, ": ", value).c_str());
}
void CurlHttpRequest::AddResolveOverride(const string& hostname, int64_t port,
const string& ip_addr) {
CheckNotSent();
resolve_list_ = libcurl_->curl_slist_append(
resolve_list_,
strings::StrCat(hostname, ":", port, ":", ip_addr).c_str());
}
void CurlHttpRequest::AddAuthBearerHeader(const string& auth_token) {
CheckNotSent();
if (!auth_token.empty()) {
AddHeader("Authorization", strings::StrCat("Bearer ", auth_token));
}
}
void CurlHttpRequest::SetRequestStats(RequestStats* stats) {
CheckNotSent();
CHECK(stats_ == nullptr) << "SetRequestStats already called";
stats_ = stats;
}
void CurlHttpRequest::SetDeleteRequest() {
CheckNotSent();
CheckMethodNotSet();
is_method_set_ = true;
method_ = RequestMethod::kDelete;
CHECK_CURL_OK(
libcurl_->curl_easy_setopt(curl_, CURLOPT_CUSTOMREQUEST, "DELETE"));
}
Status CurlHttpRequest::SetPutFromFile(const string& body_filepath,
size_t offset) {
CheckNotSent();
CheckMethodNotSet();
is_method_set_ = true;
method_ = RequestMethod::kPut;
if (put_body_) {
if (fclose(put_body_) != 0) {
LOG(ERROR) << "fclose() failed: " << strerror(errno);
}
}
put_body_ = fopen(body_filepath.c_str(), "r");
if (!put_body_) {
return errors::InvalidArgument("Couldn't open the specified file: " +
body_filepath);
}
fseek(put_body_, 0, SEEK_END);
const auto size = ftell(put_body_) - offset;
fseek(put_body_, offset, SEEK_SET);
curl_headers_ = libcurl_->curl_slist_append(
curl_headers_, strings::StrCat("Content-Length: ", size).c_str());
CHECK_CURL_OK(libcurl_->curl_easy_setopt(curl_, CURLOPT_PUT, 1));
CHECK_CURL_OK(libcurl_->curl_easy_setopt(curl_, CURLOPT_READDATA,
reinterpret_cast<void*>(put_body_)));
return OkStatus();
}
void CurlHttpRequest::SetPutEmptyBody() {
CheckNotSent();
CheckMethodNotSet();
is_method_set_ = true;
method_ = RequestMethod::kPut;
CHECK_CURL_OK(libcurl_->curl_easy_setopt(curl_, CURLOPT_PUT, 1));
AddHeader("Content-Length", "0");
AddHeader("Transfer-Encoding", "identity");
CHECK_CURL_OK(libcurl_->curl_easy_setopt(curl_, CURLOPT_READDATA,
reinterpret_cast<void*>(this)));
CHECK_CURL_OK(libcurl_->curl_easy_setopt(curl_, CURLOPT_READFUNCTION,
&CurlHttpRequest::ReadCallback));
}
void CurlHttpRequest::SetPostFromBuffer(const char* buffer, size_t size) {
CheckNotSent();
CheckMethodNotSet();
is_method_set_ = true;
method_ = RequestMethod::kPost;
curl_headers_ = libcurl_->curl_slist_append(
curl_headers_, strings::StrCat("Content-Length: ", size).c_str());
CHECK_CURL_OK(libcurl_->curl_easy_setopt(curl_, CURLOPT_POST, 1));
CHECK_CURL_OK(libcurl_->curl_easy_setopt(curl_, CURLOPT_READDATA,
reinterpret_cast<void*>(this)));
CHECK_CURL_OK(libcurl_->curl_easy_setopt(curl_, CURLOPT_READFUNCTION,
&CurlHttpRequest::ReadCallback));
post_body_buffer_ = StringPiece(buffer, size);
}
void CurlHttpRequest::SetPostEmptyBody() {
CheckNotSent();
CheckMethodNotSet();
is_method_set_ = true;
method_ = RequestMethod::kPost;
CHECK_CURL_OK(libcurl_->curl_easy_setopt(curl_, CURLOPT_POST, 1));
AddHeader("Content-Length", "0");
AddHeader("Transfer-Encoding", "identity");
CHECK_CURL_OK(libcurl_->curl_easy_setopt(curl_, CURLOPT_READDATA,
reinterpret_cast<void*>(this)));
CHECK_CURL_OK(libcurl_->curl_easy_setopt(curl_, CURLOPT_READFUNCTION,
&CurlHttpRequest::ReadCallback));
}
void CurlHttpRequest::SetResultBuffer(std::vector<char>* out_buffer) {
CheckNotSent();
CHECK(out_buffer != nullptr);
out_buffer->clear();
response_buffer_ = out_buffer;
CHECK_CURL_OK(libcurl_->curl_easy_setopt(curl_, CURLOPT_WRITEDATA,
reinterpret_cast<void*>(this)));
CHECK_CURL_OK(libcurl_->curl_easy_setopt(curl_, CURLOPT_WRITEFUNCTION,
&CurlHttpRequest::WriteCallback));
}
void CurlHttpRequest::SetResultBufferDirect(char* buffer, size_t size) {
CHECK(buffer != nullptr);
CheckNotSent();
direct_response_ = DirectResponseState{buffer, size, 0, 0};
CHECK_CURL_OK(libcurl_->curl_easy_setopt(curl_, CURLOPT_WRITEDATA,
reinterpret_cast<void*>(this)));
CHECK_CURL_OK(libcurl_->curl_easy_setopt(
curl_, CURLOPT_WRITEFUNCTION, &CurlHttpRequest::WriteCallbackDirect));
}
bool CurlHttpRequest::IsDirectResponse() const {
return direct_response_.buffer_ != nullptr;
}
size_t CurlHttpRequest::WriteCallbackDirect(const void* ptr, size_t size,
size_t nmemb, void* userdata) {
CHECK(ptr != nullptr);
auto that = reinterpret_cast<CurlHttpRequest*>(userdata);
DirectResponseState* state = &that->direct_response_;
CHECK(state->buffer_ != nullptr);
CHECK(state->bytes_transferred_ <= state->buffer_size_);
size_t curl_bytes_received = size * nmemb;
size_t user_buffer_bytes_available =
state->buffer_size_ - state->bytes_transferred_;
size_t bytes_to_copy =
std::min<size_t>(curl_bytes_received, user_buffer_bytes_available);
memcpy(&state->buffer_[state->bytes_transferred_], ptr, bytes_to_copy);
state->bytes_transferred_ += bytes_to_copy;
state->bytes_received_ += curl_bytes_received;
return bytes_to_copy;
}
size_t CurlHttpRequest::GetResultBufferDirectBytesTransferred() {
CHECK(direct_response_.buffer_ != nullptr);
return direct_response_.bytes_transferred_;
}
void CurlHttpRequest::SetTimeouts(uint32 connection, uint32 inactivity,
uint32 total) {
CheckNotSent();
connect_timeout_secs_ = connection;
inactivity_timeout_secs_ = inactivity;
request_timeout_secs_ = total;
}
size_t CurlHttpRequest::WriteCallback(const void* ptr, size_t size,
size_t nmemb, void* this_object) {
CHECK(ptr);
auto that = reinterpret_cast<CurlHttpRequest*>(this_object);
CHECK(that->response_buffer_);
const size_t bytes_to_copy = size * nmemb;
that->response_buffer_->insert(
that->response_buffer_->end(), reinterpret_cast<const char*>(ptr),
reinterpret_cast<const char*>(ptr) + bytes_to_copy);
return bytes_to_copy;
}
size_t CurlHttpRequest::ReadCallback(void* ptr, size_t size, size_t nmemb,
FILE* this_object) {
CHECK(ptr);
auto that = reinterpret_cast<CurlHttpRequest*>(this_object);
CHECK(that->post_body_read_ <= that->post_body_buffer_.size());
const size_t bytes_to_copy = std::min(
size * nmemb, that->post_body_buffer_.size() - that->post_body_read_);
memcpy(ptr, that->post_body_buffer_.data() + that->post_body_read_,
bytes_to_copy);
that->post_body_read_ += bytes_to_copy;
return bytes_to_copy;
}
size_t CurlHttpRequest::HeaderCallback(const void* ptr, size_t size,
size_t nmemb, void* this_object) {
CHECK(ptr);
auto that = reinterpret_cast<CurlHttpRequest*>(this_object);
StringPiece header(reinterpret_cast<const char*>(ptr), size * nmemb);
StringPiece name, value;
if (strings::Scanner(header)
.ScanEscapedUntil(':')
.StopCapture()
.OneLiteral(": ")
.GetResult(&value, &name)) {
string str_value(value);
absl::StripTrailingAsciiWhitespace(&str_value);
that->response_headers_[string(name)] = str_value;
}
return size * nmemb;
}
Status CurlHttpRequest::Send() {
CheckNotSent();
CHECK(is_uri_set_) << "URI has not been set.";
is_sent_ = true;
if (curl_headers_) {
CHECK_CURL_OK(
libcurl_->curl_easy_setopt(curl_, CURLOPT_HTTPHEADER, curl_headers_));
}
if (resolve_list_) {
CHECK_CURL_OK(
libcurl_->curl_easy_setopt(curl_, CURLOPT_RESOLVE, resolve_list_));
}
CHECK_CURL_OK(libcurl_->curl_easy_setopt(curl_, CURLOPT_HEADERDATA,
reinterpret_cast<void*>(this)));
CHECK_CURL_OK(libcurl_->curl_easy_setopt(curl_, CURLOPT_HEADERFUNCTION,
&CurlHttpRequest::HeaderCallback));
CHECK_CURL_OK(libcurl_->curl_easy_setopt(curl_, CURLOPT_TIMEOUT,
request_timeout_secs_));
CHECK_CURL_OK(libcurl_->curl_easy_setopt(curl_, CURLOPT_CONNECTTIMEOUT,
connect_timeout_secs_));
char error_buffer[CURL_ERROR_SIZE] = {0};
CHECK_CURL_OK(
libcurl_->curl_easy_setopt(curl_, CURLOPT_ERRORBUFFER, error_buffer));
if (stats_ != nullptr) {
stats_->RecordRequest(this, uri_, method_);
}
const CURLcode curl_result = libcurl_->curl_easy_perform(curl_);
TF_RETURN_IF_ERROR(CURLcodeToStatus(curl_result, error_buffer));
double written_size = 0;
CHECK_CURL_OK(libcurl_->curl_easy_getinfo(curl_, CURLINFO_SIZE_DOWNLOAD,
&written_size));
CHECK_CURL_OK(libcurl_->curl_easy_getinfo(curl_, CURLINFO_RESPONSE_CODE,
&response_code_));
auto get_error_message = [this]() -> string {
string error_message = strings::StrCat(
"Error executing an HTTP request: HTTP response code ", response_code_);
StringPiece body = GetResponse();
if (!body.empty()) {
return strings::StrCat(
error_message, " with body '",
body.substr(0, std::min(body.size(), response_to_error_limit_)), "'");
}
return error_message;
};
Status result;
switch (response_code_) {
case 200:
case 201:
case 204:
case 206:
result = OkStatus();
break;
case 416:
response_buffer_->clear();
if (IsDirectResponse()) {
direct_response_.bytes_transferred_ = 0;
}
result = OkStatus();
break;
case 400:
case 406:
case 411:
case 414:
result = errors::InvalidArgument(get_error_message());
break;
case 401:
case 403:
case 407:
result = errors::PermissionDenied(get_error_message());
break;
case 404:
case 410:
result = errors::NotFound(get_error_message());
break;
case 302:
case 303:
case 304:
case 307:
case 412:
case 413:
result = errors::FailedPrecondition(get_error_message());
break;
case 308:
case 409:
case 429:
case 500:
case 502:
case 503:
default:
result = errors::Unavailable(get_error_message());
break;
}
if (!result.ok()) {
response_buffer_->clear();
}
if (stats_ != nullptr) {
stats_->RecordResponse(this, uri_, method_, result);
}
return result;
}
void CurlHttpRequest::CheckMethodNotSet() const {
CHECK(!is_method_set_) << "HTTP method has been already set.";
}
void CurlHttpRequest::CheckNotSent() const {
CHECK(!is_sent_) << "The request has already been sent.";
}
StringPiece CurlHttpRequest::GetResponse() const {
StringPiece response;
if (IsDirectResponse()) {
response = StringPiece(direct_response_.buffer_,
direct_response_.bytes_transferred_);
} else {
response = StringPiece(response_buffer_->data(), response_buffer_->size());
}
return response;
}
string CurlHttpRequest::GetResponseHeader(const string& name) const {
const auto& header = response_headers_.find(name);
return header != response_headers_.end() ? header->second : "";
}
uint64 CurlHttpRequest::GetResponseCode() const { return response_code_; }
int CurlHttpRequest::ProgressCallback(void* this_object, curl_off_t dltotal,
curl_off_t dlnow, curl_off_t ultotal,
curl_off_t ulnow) {
auto that = reinterpret_cast<CurlHttpRequest*>(this_object);
const auto now = that->env_->NowSeconds();
const auto current_progress = dlnow + ulnow;
if (that->last_progress_timestamp_ == 0 ||
current_progress > that->last_progress_bytes_) {
that->last_progress_timestamp_ = now;
that->last_progress_bytes_ = current_progress;
return 0;
}
if (now - that->last_progress_timestamp_ > that->inactivity_timeout_secs_) {
double lookup_time = -1;
const auto lookup_time_status = that->libcurl_->curl_easy_getinfo(
that->curl_, CURLINFO_NAMELOOKUP_TIME, &lookup_time);
double connect_time = -1 | #include "tsl/platform/cloud/curl_http_request.h"
#include <fstream>
#include <string>
#include "absl/status/status.h"
#include "tsl/lib/core/status_test_util.h"
#include "tsl/platform/mem.h"
#include "tsl/platform/path.h"
#include "tsl/platform/test.h"
namespace tsl {
namespace {
const string kTestContent = "random original scratch content";
class FakeEnv : public EnvWrapper {
public:
FakeEnv() : EnvWrapper(Env::Default()) {}
uint64 NowSeconds() const override { return now_; }
uint64 now_ = 10000;
};
class FakeLibCurl : public LibCurl {
public:
FakeLibCurl(const string& response_content, uint64 response_code)
: response_content_(response_content), response_code_(response_code) {}
FakeLibCurl(const string& response_content, uint64 response_code,
std::vector<std::tuple<uint64, curl_off_t>> progress_ticks,
FakeEnv* env)
: response_content_(response_content),
response_code_(response_code),
progress_ticks_(std::move(progress_ticks)),
env_(env) {}
FakeLibCurl(const string& response_content, uint64 response_code,
const std::vector<string>& response_headers)
: response_content_(response_content),
response_code_(response_code),
response_headers_(response_headers) {}
CURL* curl_easy_init() override {
is_initialized_ = true;
return reinterpret_cast<CURL*>(this);
}
CURLcode curl_easy_setopt(CURL* curl, CURLoption option,
uint64 param) override {
switch (option) {
case CURLOPT_POST:
is_post_ = param;
break;
case CURLOPT_PUT:
is_put_ = param;
break;
default:
break;
}
return CURLE_OK;
}
CURLcode curl_easy_setopt(CURL* curl, CURLoption option,
const char* param) override {
return curl_easy_setopt(curl, option,
reinterpret_cast<void*>(const_cast<char*>(param)));
}
CURLcode curl_easy_setopt(CURL* curl, CURLoption option,
void* param) override {
switch (option) {
case CURLOPT_URL:
url_ = reinterpret_cast<char*>(param);
break;
case CURLOPT_RANGE:
range_ = reinterpret_cast<char*>(param);
break;
case CURLOPT_CUSTOMREQUEST:
custom_request_ = reinterpret_cast<char*>(param);
break;
case CURLOPT_HTTPHEADER:
headers_ = reinterpret_cast<std::vector<string>*>(param);
break;
case CURLOPT_ERRORBUFFER:
error_buffer_ = reinterpret_cast<char*>(param);
break;
case CURLOPT_CAINFO:
ca_info_ = reinterpret_cast<char*>(param);
break;
case CURLOPT_WRITEDATA:
write_data_ = reinterpret_cast<FILE*>(param);
break;
case CURLOPT_HEADERDATA:
header_data_ = reinterpret_cast<FILE*>(param);
break;
case CURLOPT_READDATA:
read_data_ = reinterpret_cast<FILE*>(param);
break;
case CURLOPT_XFERINFODATA:
progress_data_ = param;
break;
default:
break;
}
return CURLE_OK;
}
CURLcode curl_easy_setopt(CURL* curl, CURLoption option,
size_t (*param)(void*, size_t, size_t,
FILE*)) override {
read_callback_ = param;
return CURLE_OK;
}
CURLcode curl_easy_setopt(CURL* curl, CURLoption option,
size_t (*param)(const void*, size_t, size_t,
void*)) override {
switch (option) {
case CURLOPT_WRITEFUNCTION:
write_callback_ = param;
break;
case CURLOPT_HEADERFUNCTION:
header_callback_ = param;
break;
default:
break;
}
return CURLE_OK;
}
CURLcode curl_easy_setopt(CURL* curl, CURLoption option,
int (*param)(void* clientp, curl_off_t dltotal,
curl_off_t dlnow, curl_off_t ultotal,
curl_off_t ulnow)) override {
progress_callback_ = param;
return CURLE_OK;
}
CURLcode curl_easy_perform(CURL* curl) override {
if (is_post_ || is_put_) {
char buffer[3];
int bytes_read;
posted_content_ = "";
do {
bytes_read = read_callback_(buffer, 1, sizeof(buffer), read_data_);
posted_content_ =
strings::StrCat(posted_content_, StringPiece(buffer, bytes_read));
} while (bytes_read > 0);
}
if (write_data_ || write_callback_) {
size_t bytes_handled = write_callback_(
response_content_.c_str(), 1, response_content_.size(), write_data_);
if (bytes_handled != response_content_.size()) {
curl_easy_perform_result_ = CURLE_WRITE_ERROR;
}
}
for (const auto& header : response_headers_) {
header_callback_(header.c_str(), 1, header.size(), header_data_);
}
if (error_buffer_) {
strncpy(error_buffer_, curl_easy_perform_error_message_.c_str(),
curl_easy_perform_error_message_.size() + 1);
}
for (const auto& tick : progress_ticks_) {
env_->now_ = std::get<0>(tick);
if (progress_callback_(progress_data_, 0, std::get<1>(tick), 0, 0)) {
return CURLE_ABORTED_BY_CALLBACK;
}
}
return curl_easy_perform_result_;
}
CURLcode curl_easy_getinfo(CURL* curl, CURLINFO info,
uint64* value) override {
switch (info) {
case CURLINFO_RESPONSE_CODE:
*value = response_code_;
break;
default:
break;
}
return CURLE_OK;
}
CURLcode curl_easy_getinfo(CURL* curl, CURLINFO info,
double* value) override {
switch (info) {
case CURLINFO_SIZE_DOWNLOAD:
*value = response_content_.size();
break;
default:
break;
}
return CURLE_OK;
}
void curl_easy_cleanup(CURL* curl) override { is_cleaned_up_ = true; }
curl_slist* curl_slist_append(curl_slist* list, const char* str) override {
std::vector<string>* v = list ? reinterpret_cast<std::vector<string>*>(list)
: new std::vector<string>();
v->push_back(str);
return reinterpret_cast<curl_slist*>(v);
}
char* curl_easy_escape(CURL* curl, const char* str, int length) override {
const string victim = "/";
const string encoded = "%2F";
string temp_str = str;
std::string::size_type n = 0;
while ((n = temp_str.find(victim, n)) != std::string::npos) {
temp_str.replace(n, victim.size(), encoded);
n += encoded.size();
}
char* out_char_str = reinterpret_cast<char*>(
port::Malloc(sizeof(char) * temp_str.size() + 1));
std::copy(temp_str.begin(), temp_str.end(), out_char_str);
out_char_str[temp_str.size()] = '\0';
return out_char_str;
}
void curl_slist_free_all(curl_slist* list) override {
delete reinterpret_cast<std::vector<string>*>(list);
}
void curl_free(void* p) override { port::Free(p); }
string response_content_;
uint64 response_code_;
std::vector<string> response_headers_;
string url_;
string range_;
string custom_request_;
string ca_info_;
char* error_buffer_ = nullptr;
bool is_initialized_ = false;
bool is_cleaned_up_ = false;
std::vector<string>* headers_ = nullptr;
bool is_post_ = false;
bool is_put_ = false;
void* write_data_ = nullptr;
size_t (*write_callback_)(const void* ptr, size_t size, size_t nmemb,
void* userdata) = nullptr;
void* header_data_ = nullptr;
size_t (*header_callback_)(const void* ptr, size_t size, size_t nmemb,
void* userdata) = nullptr;
FILE* read_data_ = nullptr;
size_t (*read_callback_)(void* ptr, size_t size, size_t nmemb,
FILE* userdata) = &fread;
int (*progress_callback_)(void* clientp, curl_off_t dltotal, curl_off_t dlnow,
curl_off_t ultotal, curl_off_t ulnow) = nullptr;
void* progress_data_ = nullptr;
string posted_content_;
CURLcode curl_easy_perform_result_ = CURLE_OK;
string curl_easy_perform_error_message_;
std::vector<std::tuple<uint64, curl_off_t>> progress_ticks_;
FakeEnv* env_ = nullptr;
};
TEST(CurlHttpRequestTest, GetRequest) {
FakeLibCurl libcurl("get response", 200);
CurlHttpRequest http_request(&libcurl);
std::vector<char> scratch;
scratch.insert(scratch.begin(), kTestContent.begin(), kTestContent.end());
scratch.reserve(100);
http_request.SetUri("http:
http_request.AddAuthBearerHeader("fake-bearer");
http_request.SetRange(100, 199);
http_request.SetResultBuffer(&scratch);
TF_EXPECT_OK(http_request.Send());
EXPECT_EQ("get response", string(scratch.begin(), scratch.end()));
EXPECT_TRUE(libcurl.is_initialized_);
EXPECT_EQ("http:
EXPECT_EQ("100-199", libcurl.range_);
EXPECT_EQ("", libcurl.custom_request_);
EXPECT_EQ("", libcurl.ca_info_);
EXPECT_EQ(1, libcurl.headers_->size());
EXPECT_EQ("Authorization: Bearer fake-bearer", (*libcurl.headers_)[0]);
EXPECT_FALSE(libcurl.is_post_);
EXPECT_EQ(200, http_request.GetResponseCode());
}
TEST(CurlHttpRequestTest, GetRequest_Direct) {
FakeLibCurl libcurl("get response", 200);
CurlHttpRequest http_request(&libcurl);
std::vector<char> scratch(100, 0);
http_request.SetUri("http:
http_request.AddAuthBearerHeader("fake-bearer");
http_request.SetRange(100, 199);
http_request.SetResultBufferDirect(scratch.data(), scratch.capacity());
TF_EXPECT_OK(http_request.Send());
string expected_response = "get response";
size_t response_bytes_transferred =
http_request.GetResultBufferDirectBytesTransferred();
EXPECT_EQ(expected_response.size(), response_bytes_transferred);
EXPECT_EQ(
"get response",
string(scratch.begin(), scratch.begin() + response_bytes_transferred));
EXPECT_TRUE(libcurl.is_initialized_);
EXPECT_EQ("http:
EXPECT_EQ("100-199", libcurl.range_);
EXPECT_EQ("", libcurl.custom_request_);
EXPECT_EQ("", libcurl.ca_info_);
EXPECT_EQ(1, libcurl.headers_->size());
EXPECT_EQ("Authorization: Bearer fake-bearer", (*libcurl.headers_)[0]);
EXPECT_FALSE(libcurl.is_post_);
EXPECT_EQ(200, http_request.GetResponseCode());
}
TEST(CurlHttpRequestTest, GetRequest_CustomCaInfoFlag) {
static char set_var[] = "CURL_CA_BUNDLE=test";
putenv(set_var);
FakeLibCurl libcurl("get response", 200);
CurlHttpRequest http_request(&libcurl);
std::vector<char> scratch;
scratch.insert(scratch.begin(), kTestContent.begin(), kTestContent.end());
scratch.reserve(100);
http_request.SetUri("http:
http_request.AddAuthBearerHeader("fake-bearer");
http_request.SetRange(100, 199);
http_request.SetResultBuffer(&scratch);
TF_EXPECT_OK(http_request.Send());
EXPECT_EQ("get response", string(scratch.begin(), scratch.end()));
EXPECT_TRUE(libcurl.is_initialized_);
EXPECT_EQ("http:
EXPECT_EQ("100-199", libcurl.range_);
EXPECT_EQ("", libcurl.custom_request_);
EXPECT_EQ("test", libcurl.ca_info_);
EXPECT_EQ(1, libcurl.headers_->size());
EXPECT_EQ("Authorization: Bearer fake-bearer", (*libcurl.headers_)[0]);
EXPECT_FALSE(libcurl.is_post_);
EXPECT_EQ(200, http_request.GetResponseCode());
}
TEST(CurlHttpRequestTest, GetRequest_Direct_ResponseTooLarge) {
FakeLibCurl libcurl("get response", 200);
CurlHttpRequest http_request(&libcurl);
std::vector<char> scratch(5, 0);
http_request.SetUri("http:
http_request.SetResultBufferDirect(scratch.data(), scratch.size());
const Status& status = http_request.Send();
EXPECT_EQ(error::FAILED_PRECONDITION, status.code());
EXPECT_EQ(
"Error executing an HTTP request: libcurl code 23 meaning "
"'Failed writing received data to disk/application', error details: "
"Received 12 response bytes for a 5-byte buffer",
status.message());
EXPECT_EQ(5, http_request.GetResultBufferDirectBytesTransferred());
EXPECT_EQ("get r", string(scratch.begin(), scratch.begin() + 5));
}
TEST(CurlHttpRequestTest, GetRequest_Direct_RangeOutOfBound) {
FakeLibCurl libcurl("get response", 416);
CurlHttpRequest http_request(&libcurl);
const string initialScratch = "abcde";
std::vector<char> scratch;
scratch.insert(scratch.end(), initialScratch.begin(), initialScratch.end());
http_request.SetUri("http:
http_request.SetRange(0, 4);
http_request.SetResultBufferDirect(scratch.data(), scratch.size());
TF_EXPECT_OK(http_request.Send());
EXPECT_EQ(416, http_request.GetResponseCode());
EXPECT_EQ(0, http_request.GetResultBufferDirectBytesTransferred());
EXPECT_EQ("get r", string(scratch.begin(), scratch.end()));
}
TEST(CurlHttpRequestTest, GetRequest_Empty) {
FakeLibCurl libcurl("", 200);
CurlHttpRequest http_request(&libcurl);
std::vector<char> scratch;
scratch.resize(0);
http_request.SetUri("http:
http_request.AddAuthBearerHeader("fake-bearer");
http_request.SetRange(100, 199);
http_request.SetResultBuffer(&scratch);
TF_EXPECT_OK(http_request.Send());
EXPECT_TRUE(scratch.empty());
EXPECT_TRUE(libcurl.is_initialized_);
EXPECT_EQ("http:
EXPECT_EQ("100-199", libcurl.range_);
EXPECT_EQ("", libcurl.custom_request_);
EXPECT_EQ(1, libcurl.headers_->size());
EXPECT_EQ("Authorization: Bearer fake-bearer", (*libcurl.headers_)[0]);
EXPECT_FALSE(libcurl.is_post_);
EXPECT_EQ(200, http_request.GetResponseCode());
}
TEST(CurlHttpRequestTest, GetRequest_RangeOutOfBound) {
FakeLibCurl libcurl("get response", 416);
CurlHttpRequest http_request(&libcurl);
std::vector<char> scratch;
scratch.insert(scratch.end(), kTestContent.begin(), kTestContent.end());
http_request.SetUri("http:
http_request.AddAuthBearerHeader("fake-bearer");
http_request.SetRange(100, 199);
http_request.SetResultBuffer(&scratch);
TF_EXPECT_OK(http_request.Send());
EXPECT_TRUE(scratch.empty());
EXPECT_EQ(416, http_request.GetResponseCode());
}
TEST(CurlHttpRequestTest, GetRequest_503) {
FakeLibCurl libcurl("get response", 503);
CurlHttpRequest http_request(&libcurl);
std::vector<char> scratch;
scratch.insert(scratch.end(), kTestContent.begin(), kTestContent.end());
http_request.SetUri("http:
http_request.SetResultBuffer(&scratch);
const auto& status = http_request.Send();
EXPECT_EQ(error::UNAVAILABLE, status.code());
EXPECT_EQ(
"Error executing an HTTP request: HTTP response code 503 with body "
"'get response'",
status.message());
}
TEST(CurlHttpRequestTest, GetRequest_HttpCode0) {
FakeLibCurl libcurl("get response", 0);
libcurl.curl_easy_perform_result_ = CURLE_OPERATION_TIMEDOUT;
libcurl.curl_easy_perform_error_message_ = "Operation timed out";
CurlHttpRequest http_request(&libcurl);
std::vector<char> scratch;
scratch.insert(scratch.end(), kTestContent.begin(), kTestContent.end());
http_request.SetUri("http:
const auto& status = http_request.Send();
EXPECT_EQ(error::UNAVAILABLE, status.code());
EXPECT_EQ(
"Error executing an HTTP request: libcurl code 28 meaning "
"'Timeout was reached', error details: Operation timed out",
status.message());
EXPECT_EQ(0, http_request.GetResponseCode());
}
TEST(CurlHttpRequestTest, GetRequest_CouldntResolveHost) {
FakeLibCurl libcurl("get response", 0);
libcurl.curl_easy_perform_result_ = CURLE_COULDNT_RESOLVE_HOST;
libcurl.curl_easy_perform_error_message_ =
"Could not resolve host 'metadata'";
CurlHttpRequest http_request(&libcurl);
std::vector<char> scratch;
scratch.insert(scratch.end(), kTestContent.begin(), kTestContent.end());
http_request.SetUri("http:
const auto& status = http_request.Send();
EXPECT_EQ(error::FAILED_PRECONDITION, status.code());
EXPECT_EQ(
"Error executing an HTTP request: libcurl code 6 meaning "
"'Couldn't resolve host name', error details: Could not resolve host "
"'metadata'",
status.message());
EXPECT_EQ(0, http_request.GetResponseCode());
}
TEST(CurlHttpRequestTest, GetRequest_SslBadCertfile) {
FakeLibCurl libcurl("get response", 0);
libcurl.curl_easy_perform_result_ = CURLE_SSL_CACERT_BADFILE;
libcurl.curl_easy_perform_error_message_ =
"error setting certificate verify locations:";
CurlHttpRequest http_request(&libcurl);
std::vector<char> scratch;
scratch.insert(scratch.end(), kTestContent.begin(), kTestContent.end());
http_request.SetUri("http:
const auto& status = http_request.Send();
EXPECT_EQ(error::FAILED_PRECONDITION, status.code());
EXPECT_EQ(
"Error executing an HTTP request: libcurl code 77 meaning "
"'Problem with the SSL CA cert (path? access rights?)', error details: "
"error setting certificate verify locations:",
status.message());
EXPECT_EQ(0, http_request.GetResponseCode());
}
TEST(CurlHttpRequestTest, ResponseHeaders) {
FakeLibCurl libcurl(
"get response", 200,
{"Location: abcd", "Content-Type: text", "unparsable header"});
CurlHttpRequest http_request(&libcurl);
http_request.SetUri("http:
TF_EXPECT_OK(http_request.Send());
EXPECT_EQ("abcd", http_request.GetResponseHeader("Location"));
EXPECT_EQ("text", http_request.GetResponseHeader("Content-Type"));
EXPECT_EQ("", http_request.GetResponseHeader("Not-Seen-Header"));
}
TEST(CurlHttpRequestTest, PutRequest_WithBody_FromFile) {
FakeLibCurl libcurl("", 200);
CurlHttpRequest http_request(&libcurl);
auto content_filename = io::JoinPath(testing::TmpDir(), "content");
std::ofstream content(content_filename, std::ofstream::binary);
content << "post body content";
content.close();
http_request.SetUri("http:
http_request.AddAuthBearerHeader("fake-bearer");
TF_EXPECT_OK(http_request.SetPutFromFile(content_filename, 0));
TF_EXPECT_OK(http_request.Send());
EXPECT_TRUE(libcurl.is_initialized_);
EXPECT_EQ("http:
EXPECT_EQ("", libcurl.custom_request_);
EXPECT_EQ(2, libcurl.headers_->size());
EXPECT_EQ("Authorization: Bearer fake-bearer", (*libcurl.headers_)[0]);
EXPECT_EQ("Content-Length: 17", (*libcurl.headers_)[1]);
EXPECT_TRUE(libcurl.is_put_);
EXPECT_EQ("post body content", libcurl.posted_content_);
std::remove(content_filename.c_str());
}
TEST(CurlHttpRequestTest, PutRequest_WithBody_FromFile_NonZeroOffset) {
FakeLibCurl libcurl("", 200);
CurlHttpRequest http_request(&libcurl);
auto content_filename = io::JoinPath(testing::TmpDir(), "content");
std::ofstream content(content_filename, std::ofstream::binary);
content << "post body content";
content.close();
http_request.SetUri("http:
http_request.AddAuthBearerHeader("fake-bearer");
TF_EXPECT_OK(http_request.SetPutFromFile(content_filename, 7));
TF_EXPECT_OK(http_request.Send());
EXPECT_EQ("dy content", libcurl.posted_content_);
std::remove(content_filename.c_str());
}
TEST(CurlHttpRequestTest, PutRequest_WithoutBody) {
FakeLibCurl libcurl("", 200);
CurlHttpRequest http_request(&libcurl);
http_request.SetUri("http:
http_request.AddAuthBearerHeader("fake-bearer");
http_request.SetPutEmptyBody();
TF_EXPECT_OK(http_request.Send());
EXPECT_TRUE(libcurl.is_initialized_);
EXPECT_EQ("http:
EXPECT_EQ("", libcurl.custom_request_);
EXPECT_EQ(3, libcurl.headers_->size());
EXPECT_EQ("Authorization: Bearer fake-bearer", (*libcurl.headers_)[0]);
EXPECT_EQ("Content-Length: 0", (*libcurl.headers_)[1]);
EXPECT_EQ("Transfer-Encoding: identity", (*libcurl.headers_)[2]);
EXPECT_TRUE(libcurl.is_put_);
EXPECT_EQ("", libcurl.posted_content_);
}
TEST(CurlHttpRequestTest, PostRequest_WithBody_FromMemory) {
FakeLibCurl libcurl("", 200);
CurlHttpRequest http_request(&libcurl);
string content = "post body content";
http_request.SetUri("http:
http_request.AddAuthBearerHeader("fake-bearer");
http_request.SetPostFromBuffer(content.c_str(), content.size());
TF_EXPECT_OK(http_request.Send());
EXPECT_TRUE(libcurl.is_initialized_);
EXPECT_EQ("http:
EXPECT_EQ("", libcurl.custom_request_);
EXPECT_EQ(2, libcurl.headers_->size());
EXPECT_EQ("Authorization: Bearer fake-bearer", (*libcurl.headers_)[0]);
EXPECT_EQ("Content-Length: 17", (*libcurl.headers_)[1]);
EXPECT_TRUE(libcurl.is_post_);
EXPECT_EQ("post body content", libcurl.posted_content_);
}
TEST(CurlHttpRequestTest, PostRequest_WithoutBody) {
FakeLibCurl libcurl("", 200);
CurlHttpRequest http_request(&libcurl);
http_request.SetUri("http:
http_request.AddAuthBearerHeader("fake-bearer");
http_request.SetPostEmptyBody();
TF_EXPECT_OK(http_request.Send());
EXPECT_TRUE(libcurl.is_initialized_);
EXPECT_EQ("http:
EXPECT_EQ("", libcurl.custom_request_);
EXPECT_EQ(3, libcurl.headers_->size());
EXPECT_EQ("Authorization: Bearer fake-bearer", (*libcurl.headers_)[0]);
EXPECT_EQ("Content-Length: 0", (*libcurl.headers_)[1]);
EXPECT_EQ("Transfer-Encoding: identity", (*libcurl.headers_)[2]);
EXPECT_TRUE(libcurl.is_post_);
EXPECT_EQ("", libcurl.posted_content_);
}
TEST(CurlHttpRequestTest, DeleteRequest) {
FakeLibCurl libcurl("", 200);
CurlHttpRequest http_request(&libcurl);
http_request.SetUri("http:
http_request.AddAuthBearerHeader("fake-bearer");
http_request.SetDeleteRequest();
TF_EXPECT_OK(http_request.Send());
EXPECT_TRUE(libcurl.is_initialized_);
EXPECT_EQ("http:
EXPECT_EQ("DELETE", libcurl.custom_request_);
EXPECT_EQ(1, libcurl.headers_->size());
EXPECT_EQ("Authorization: Bearer fake-bearer", (*libcurl.headers_)[0]);
EXPECT_FALSE(libcurl.is_post_);
}
TEST(CurlHttpRequestTest, WrongSequenceOfCalls_NoUri) {
FakeLibCurl libcurl("", 200);
CurlHttpRequest http_request(&libcurl);
ASSERT_DEATH((void)http_request.Send(), "URI has not been set");
}
TEST(CurlHttpRequestTest, WrongSequenceOfCalls_TwoSends) {
FakeLibCurl libcurl("", 200);
CurlHttpRequest http_request(&libcurl);
http_request.SetUri("http:
TF_EXPECT_OK(http_request.Send());
ASSERT_DEATH((void)http_request.Send(), "The request has already been sent");
}
TEST(CurlHttpRequestTest, WrongSequenceOfCalls_ReusingAfterSend) {
FakeLibCurl libcurl("", 200);
CurlHttpRequest http_request(&libcurl);
http_request.SetUri("http:
TF_EXPECT_OK(http_request.Send());
ASSERT_DEATH(http_request.SetUri("http:
"The request has already been sent");
}
TEST(CurlHttpRequestTest, WrongSequenceOfCalls_SettingMethodTwice) {
FakeLibCurl libcurl("", 200);
CurlHttpRequest http_request(&libcurl);
http_request.SetDeleteRequest();
ASSERT_DEATH(http_request.SetPostEmptyBody(),
"HTTP method has been already set");
}
TEST(CurlHttpRequestTest, EscapeString) {
FakeLibCurl libcurl("get response", 200);
CurlHttpRequest http_request(&libcurl);
const string test_string = "a/b/c";
EXPECT_EQ("a%2Fb%2Fc", http_request.EscapeString(test_string));
}
TEST(CurlHttpRequestTest, ErrorReturnsNoResponse) {
FakeLibCurl libcurl("get response", 500);
CurlHttpRequest http_request(&libcurl);
std::vector<char> scratch;
scratch.insert(scratch.begin(), kTestContent.begin(), kTestContent.end());
scratch.reserve(100);
http_request.SetUri("http:
http_request.AddAuthBearerHeader("fake-bearer");
http_request.SetRange(100, 199);
http_request.SetResultBuffer(&scratch);
EXPECT_EQ(error::UNAVAILABLE, http_request.Send().code());
EXPECT_EQ("", string(scratch.begin(), scratch.end()));
}
TEST(CurlHttpRequestTest, ProgressIsOk) {
FakeEnv env;
FakeLibCurl libcurl(
"test", 200,
{
std::make_tuple(100, 0) ,
std::make_tuple(110, 0) ,
std::make_tuple(200, 100)
},
&env);
CurlHttpRequest http_request(&libcurl, &env);
http_request.SetUri("http:
TF_EXPECT_OK(http_request.Send());
}
TEST(CurlHttpRequestTest, ProgressIsStuck) {
FakeEnv env;
FakeLibCurl libcurl(
"test", 200,
{
std::make_tuple(100, 10) ,
std::make_tuple(130, 10) ,
std::make_tuple(170, 10)
},
&env);
CurlHttpRequest http_request(&libcurl, &env);
http_request.SetUri("http:
auto status = http_request.Send();
EXPECT_EQ(error::UNAVAILABLE, status.code());
EXPECT_EQ(
"Error executing an HTTP request: libcurl code 42 meaning 'Operation "
"was aborted by an application callback', error details: (none)",
status.message());
}
class TestStats : public HttpRequest::RequestStats {
public:
~TestStats() override = default;
void RecordRequest(const HttpRequest* request, const string& uri,
HttpRequest::RequestMethod method) override {
has_recorded_request_ = true;
record_request_request_ = request;
record_request_uri_ = uri;
record_request_method_ = method;
}
void RecordResponse(const HttpRequest* request, const string& uri,
HttpRequest::RequestMethod method,
const Status& result) override {
has_recorded_response_ = true;
record_response_request_ = request;
record_response_uri_ = uri;
record_response_method_ = method;
record_response_result_ = result;
}
const HttpRequest* record_request_request_ = nullptr;
string record_request_uri_ = "http:
HttpRequest::RequestMethod record_request_method_ =
HttpRequest::RequestMethod::kGet;
const HttpRequest* record_response_request_ = nullptr;
string record_response_uri_ = "http:
HttpRequest::RequestMethod record_response_method_ =
HttpRequest::RequestMethod::kGet;
Status record_response_result_;
bool has_recorded_request_ = false;
bool has_recorded_response_ = false;
};
class StatsTestFakeLibCurl : public FakeLibCurl {
public:
StatsTestFakeLibCurl(TestStats* stats, const string& response_content,
uint64 response_code)
: FakeLibCurl(response_content, response_code), stats_(stats) {}
CURLcode curl_easy_perform(CURL* curl) override {
CHECK(!performed_request_);
performed_request_ = true;
stats_had_recorded_request_ = stats_->has_recorded_request_;
stats_had_recorded_response_ = stats_->has_recorded_response_;
return FakeLibCurl::curl_easy_perform(curl);
};
TestStats* stats_;
bool performed_request_ = false;
bool stats_had_recorded_request_;
bool stats_had_recorded_response_;
};
TEST(CurlHttpRequestTest, StatsGetSuccessful) {
TestStats stats;
StatsTestFakeLibCurl libcurl(&stats, "get response", 200);
CurlHttpRequest http_request(&libcurl);
std::vector<char> scratch;
scratch.insert(scratch.begin(), kTestContent.begin(), kTestContent.end());
scratch.reserve(100);
http_request.SetRequestStats(&stats);
http_request.SetUri("http:
http_request.AddAuthBearerHeader("fake-bearer");
http_request.SetRange(100, 199);
http_request.SetResultBuffer(&scratch);
TF_EXPECT_OK(http_request.Send());
EXPECT_EQ("get response", string(scratch.begin(), scratch.end()));
ASSERT_TRUE(stats.has_recorded_request_);
EXPECT_EQ(&http_request, stats.record_request_request_);
EXPECT_EQ("http:
EXPECT_EQ(HttpRequest::RequestMethod::kGet, stats.record_request_method_);
ASSERT_TRUE(stats.has_recorded_response_);
EXPECT_EQ(&http_request, stats.record_response_request_);
EXPECT_EQ("http:
EXPECT_EQ(HttpRequest::RequestMethod::kGet, stats.record_response_method_);
TF_EXPECT_OK(stats.record_response_result_);
EXPECT_TRUE(libcurl.performed_request_);
EXPECT_TRUE(libcurl.stats_had_recorded_request_);
EXPECT_FALSE(libcurl.stats_had_recorded_response_);
}
TEST(CurlHttpRequestTest, StatsGetNotFound) {
TestStats stats;
StatsTestFakeLibCurl libcurl(&stats, "get other response", 404);
CurlHttpRequest http_request(&libcurl);
std::vector<char> scratch;
scratch.insert(scratch.begin(), kTestContent.begin(), kTestContent.end());
scratch.reserve(100);
http_request.SetRequestStats(&stats);
http_request.SetUri("http:
http_request.AddAuthBearerHeader("fake-bearer");
http_request.SetRange(100, 199);
http_request.SetResultBuffer(&scratch);
Status s = http_request.Send();
ASSERT_TRUE(stats.has_recorded_request_);
EXPECT_EQ(&http_request, stats.record_request_request_);
EXPECT_EQ("http:
EXPECT_EQ(HttpRequest::RequestMethod::kGet, stats.record_request_method_);
ASSERT_TRUE(stats.has_recorded_response_);
EXPECT_EQ(&http_request, stats.record_response_request_);
EXPECT_EQ("http:
EXPECT_EQ(HttpRequest::RequestMethod::kGet, stats.record_response_method_);
EXPECT_TRUE(absl::IsNotFound(stats.record_response_result_));
EXPECT_EQ(s, stats.record_response_result_);
EXPECT_TRUE(libcurl.performed_request_);
EXPECT_TRUE(libcurl.stats_had_recorded_request_);
EXPECT_FALSE(libcurl.stats_had_recorded_response_);
}
TEST(CurlHttpRequestTest, StatsPost) {
TestStats stats;
FakeLibCurl libcurl("", 200);
CurlHttpRequest http_request(&libcurl);
http_request.SetRequestStats(&stats);
string content = "post body content";
http_request.SetUri("http:
http_request.SetPostFromBuffer(content.c_str(), content.size());
TF_EXPECT_OK(http_request.Send());
ASSERT_TRUE(stats.has_recorded_request_);
EXPECT_EQ(&http_request, stats.record_request_request_);
EXPECT_EQ("http:
EXPECT_EQ(HttpR | 2,276 |
#ifndef TENSORFLOW_TSL_PLATFORM_CLOUD_TIME_UTIL_H_
#define TENSORFLOW_TSL_PLATFORM_CLOUD_TIME_UTIL_H_
#include "tsl/platform/status.h"
namespace tsl {
Status ParseRfc3339Time(const string& time, int64_t* mtime_nsec);
}
#endif
#include "tsl/platform/cloud/time_util.h"
#include <time.h>
#include <cmath>
#include <cstdio>
#include <ctime>
#ifdef _WIN32
#define timegm _mkgmtime
#endif
#include "tsl/platform/errors.h"
namespace tsl {
namespace {
constexpr int64_t kNanosecondsPerSecond = 1000 * 1000 * 1000;
}
Status ParseRfc3339Time(const string& time, int64_t* mtime_nsec) {
tm parsed{0};
float seconds;
if (sscanf(time.c_str(), "%4d-%2d-%2dT%2d:%2d:%fZ", &(parsed.tm_year),
&(parsed.tm_mon), &(parsed.tm_mday), &(parsed.tm_hour),
&(parsed.tm_min), &seconds) != 6) {
return errors::Internal(
strings::StrCat("Unrecognized RFC 3339 time format: ", time));
}
const int int_seconds = std::floor(seconds);
parsed.tm_year -= 1900;
parsed.tm_mon -= 1;
parsed.tm_sec = int_seconds;
*mtime_nsec = timegm(&parsed) * kNanosecondsPerSecond +
static_cast<int64_t>(std::floor((seconds - int_seconds) *
kNanosecondsPerSecond));
return OkStatus();
}
} | #include "tsl/platform/cloud/time_util.h"
#include "tsl/lib/core/status_test_util.h"
#include "tsl/platform/test.h"
namespace tsl {
TEST(TimeUtil, ParseRfc3339Time) {
int64_t mtime_nsec;
TF_EXPECT_OK(ParseRfc3339Time("2016-04-29T23:15:24.896Z", &mtime_nsec));
EXPECT_NEAR(1461971724896, mtime_nsec / 1000 / 1000, 1);
}
TEST(TimeUtil, ParseRfc3339Time_ParseError) {
int64_t mtime_nsec;
EXPECT_EQ("Unrecognized RFC 3339 time format: 2016-04-29",
ParseRfc3339Time("2016-04-29", &mtime_nsec).message());
}
} | 2,277 |
#ifndef TENSORFLOW_TSL_PLATFORM_CLOUD_GOOGLE_AUTH_PROVIDER_H_
#define TENSORFLOW_TSL_PLATFORM_CLOUD_GOOGLE_AUTH_PROVIDER_H_
#include <memory>
#include "tsl/platform/cloud/auth_provider.h"
#include "tsl/platform/cloud/compute_engine_metadata_client.h"
#include "tsl/platform/cloud/oauth_client.h"
#include "tsl/platform/mutex.h"
#include "tsl/platform/thread_annotations.h"
namespace tsl {
class GoogleAuthProvider : public AuthProvider {
public:
GoogleAuthProvider(std::shared_ptr<ComputeEngineMetadataClient>
compute_engine_metadata_client);
explicit GoogleAuthProvider(std::unique_ptr<OAuthClient> oauth_client,
std::shared_ptr<ComputeEngineMetadataClient>
compute_engine_metadata_client,
Env* env);
virtual ~GoogleAuthProvider() {}
Status GetToken(string* token) override;
private:
Status GetTokenFromFiles() TF_EXCLUSIVE_LOCKS_REQUIRED(mu_);
Status GetTokenFromGce() TF_EXCLUSIVE_LOCKS_REQUIRED(mu_);
Status GetTokenForTesting() TF_EXCLUSIVE_LOCKS_REQUIRED(mu_);
std::unique_ptr<OAuthClient> oauth_client_;
std::shared_ptr<ComputeEngineMetadataClient> compute_engine_metadata_client_;
Env* env_;
mutex mu_;
string current_token_ TF_GUARDED_BY(mu_);
uint64 expiration_timestamp_sec_ TF_GUARDED_BY(mu_) = 0;
GoogleAuthProvider(const GoogleAuthProvider&) = delete;
void operator=(const GoogleAuthProvider&) = delete;
};
}
#endif
#include "tsl/platform/cloud/google_auth_provider.h"
#ifndef _WIN32
#include <pwd.h>
#include <unistd.h>
#else
#include <sys/types.h>
#endif
#include <fstream>
#include <utility>
#include "absl/strings/match.h"
#include "json/json.h"
#include "tsl/platform/base64.h"
#include "tsl/platform/env.h"
#include "tsl/platform/errors.h"
#include "tsl/platform/path.h"
#include "tsl/platform/retrying_utils.h"
namespace tsl {
namespace {
constexpr char kGoogleApplicationCredentials[] =
"GOOGLE_APPLICATION_CREDENTIALS";
constexpr char kGoogleAuthTokenForTesting[] = "GOOGLE_AUTH_TOKEN_FOR_TESTING";
constexpr char kCloudSdkConfig[] = "CLOUDSDK_CONFIG";
constexpr char kNoGceCheck[] = "NO_GCE_CHECK";
constexpr char kGCloudConfigFolder[] = ".config/gcloud/";
constexpr char kWellKnownCredentialsFile[] =
"application_default_credentials.json";
constexpr int kExpirationTimeMarginSec = 60;
constexpr char kOAuthV3Url[] = "https:
constexpr char kOAuthV4Url[] = "https:
constexpr char kGceTokenPath[] = "instance/service-accounts/default/token";
constexpr char kOAuthScope[] = "https:
bool IsFile(const string& filename) {
std::ifstream fstream(filename.c_str());
return fstream.good();
}
Status GetEnvironmentVariableFileName(string* filename) {
if (!filename) {
return errors::FailedPrecondition("'filename' cannot be nullptr.");
}
const char* result = std::getenv(kGoogleApplicationCredentials);
if (!result || !IsFile(result)) {
return errors::NotFound(strings::StrCat("$", kGoogleApplicationCredentials,
" is not set or corrupt."));
}
*filename = result;
return OkStatus();
}
Status GetWellKnownFileName(string* filename) {
if (!filename) {
return errors::FailedPrecondition("'filename' cannot be nullptr.");
}
string config_dir;
const char* config_dir_override = std::getenv(kCloudSdkConfig);
if (config_dir_override) {
config_dir = config_dir_override;
} else {
const char* home_dir = std::getenv("HOME");
if (!home_dir) {
return errors::FailedPrecondition("Could not read $HOME.");
}
config_dir = io::JoinPath(home_dir, kGCloudConfigFolder);
}
auto result = io::JoinPath(config_dir, kWellKnownCredentialsFile);
if (!IsFile(result)) {
return errors::NotFound(
"Could not find the credentials file in the standard gcloud location.");
}
*filename = result;
return OkStatus();
}
}
GoogleAuthProvider::GoogleAuthProvider(
std::shared_ptr<ComputeEngineMetadataClient> compute_engine_metadata_client)
: GoogleAuthProvider(std::unique_ptr<OAuthClient>(new OAuthClient()),
std::move(compute_engine_metadata_client),
Env::Default()) {}
GoogleAuthProvider::GoogleAuthProvider(
std::unique_ptr<OAuthClient> oauth_client,
std::shared_ptr<ComputeEngineMetadataClient> compute_engine_metadata_client,
Env* env)
: oauth_client_(std::move(oauth_client)),
compute_engine_metadata_client_(
std::move(compute_engine_metadata_client)),
env_(env) {}
Status GoogleAuthProvider::GetToken(string* t) {
mutex_lock lock(mu_);
const uint64 now_sec = env_->NowSeconds();
if (now_sec + kExpirationTimeMarginSec < expiration_timestamp_sec_) {
*t = current_token_;
return OkStatus();
}
if (GetTokenForTesting().ok()) {
*t = current_token_;
return OkStatus();
}
auto token_from_files_status = GetTokenFromFiles();
if (token_from_files_status.ok()) {
*t = current_token_;
return OkStatus();
}
char* no_gce_check_var = std::getenv(kNoGceCheck);
bool skip_gce_check = no_gce_check_var != nullptr &&
absl::EqualsIgnoreCase(no_gce_check_var, "true");
Status token_from_gce_status;
if (skip_gce_check) {
token_from_gce_status =
Status(absl::StatusCode::kCancelled,
strings::StrCat("GCE check skipped due to presence of $",
kNoGceCheck, " environment variable."));
} else {
token_from_gce_status = GetTokenFromGce();
}
if (token_from_gce_status.ok()) {
*t = current_token_;
return OkStatus();
}
if (skip_gce_check) {
LOG(INFO)
<< "Attempting an empty bearer token since no token was retrieved "
<< "from files, and GCE metadata check was skipped.";
} else {
LOG(WARNING)
<< "All attempts to get a Google authentication bearer token failed, "
<< "returning an empty token. Retrieving token from files failed with "
"\""
<< token_from_files_status.ToString() << "\"."
<< " Retrieving token from GCE failed with \""
<< token_from_gce_status.ToString() << "\".";
}
*t = "";
if (skip_gce_check) {
expiration_timestamp_sec_ = 0;
} else {
expiration_timestamp_sec_ = UINT64_MAX;
}
current_token_ = "";
return OkStatus();
}
Status GoogleAuthProvider::GetTokenFromFiles() {
string credentials_filename;
if (!GetEnvironmentVariableFileName(&credentials_filename).ok() &&
!GetWellKnownFileName(&credentials_filename).ok()) {
return errors::NotFound("Could not locate the credentials file.");
}
Json::Value json;
Json::Reader reader;
std::ifstream credentials_fstream(credentials_filename);
if (!reader.parse(credentials_fstream, json)) {
return errors::FailedPrecondition(
"Couldn't parse the JSON credentials file.");
}
if (json.isMember("refresh_token")) {
TF_RETURN_IF_ERROR(oauth_client_->GetTokenFromRefreshTokenJson(
json, kOAuthV3Url, ¤t_token_, &expiration_timestamp_sec_));
} else if (json.isMember("private_key")) {
TF_RETURN_IF_ERROR(oauth_client_->GetTokenFromServiceAccountJson(
json, kOAuthV4Url, kOAuthScope, ¤t_token_,
&expiration_timestamp_sec_));
} else {
return errors::FailedPrecondition(
"Unexpected content of the JSON credentials file.");
}
return OkStatus();
}
Status GoogleAuthProvider::GetTokenFromGce() {
std::vector<char> response_buffer;
const uint64 request_timestamp_sec = env_->NowSeconds();
TF_RETURN_IF_ERROR(compute_engine_metadata_client_->GetMetadata(
kGceTokenPath, &response_buffer));
StringPiece response =
StringPiece(&response_buffer[0], response_buffer.size());
TF_RETURN_IF_ERROR(oauth_client_->ParseOAuthResponse(
response, request_timestamp_sec, ¤t_token_,
&expiration_timestamp_sec_));
return OkStatus();
}
Status GoogleAuthProvider::GetTokenForTesting() {
const char* token = std::getenv(kGoogleAuthTokenForTesting);
if (!token) {
return errors::NotFound("The env variable for testing was not set.");
}
expiration_timestamp_sec_ = UINT64_MAX;
current_token_ = token;
return OkStatus();
}
} | #include "tsl/platform/cloud/google_auth_provider.h"
#include <stdlib.h>
#include "tsl/lib/core/status_test_util.h"
#include "tsl/platform/cloud/http_request_fake.h"
#include "tsl/platform/path.h"
#include "tsl/platform/test.h"
namespace tsl {
namespace {
string TestData() {
return io::JoinPath(testing::TslSrcRoot(), "platform", "cloud", "testdata");
}
class FakeEnv : public EnvWrapper {
public:
FakeEnv() : EnvWrapper(Env::Default()) {}
uint64 NowSeconds() const override { return now; }
uint64 now = 10000;
};
class FakeOAuthClient : public OAuthClient {
public:
Status GetTokenFromServiceAccountJson(
Json::Value json, StringPiece oauth_server_uri, StringPiece scope,
string* token, uint64* expiration_timestamp_sec) override {
provided_credentials_json = json;
*token = return_token;
*expiration_timestamp_sec = return_expiration_timestamp;
return OkStatus();
}
Status GetTokenFromRefreshTokenJson(
Json::Value json, StringPiece oauth_server_uri, string* token,
uint64* expiration_timestamp_sec) override {
provided_credentials_json = json;
*token = return_token;
*expiration_timestamp_sec = return_expiration_timestamp;
return OkStatus();
}
string return_token;
uint64 return_expiration_timestamp;
Json::Value provided_credentials_json;
};
}
class GoogleAuthProviderTest : public ::testing::Test {
protected:
void SetUp() override { ClearEnvVars(); }
void TearDown() override { ClearEnvVars(); }
void ClearEnvVars() {
unsetenv("CLOUDSDK_CONFIG");
unsetenv("GOOGLE_APPLICATION_CREDENTIALS");
unsetenv("GOOGLE_AUTH_TOKEN_FOR_TESTING");
unsetenv("NO_GCE_CHECK");
}
};
TEST_F(GoogleAuthProviderTest, EnvironmentVariable_Caching) {
setenv("GOOGLE_APPLICATION_CREDENTIALS",
io::JoinPath(TestData(), "service_account_credentials.json").c_str(),
1);
setenv("CLOUDSDK_CONFIG", TestData().c_str(),
1);
auto oauth_client = new FakeOAuthClient;
std::vector<HttpRequest*> requests;
FakeEnv env;
std::shared_ptr<HttpRequest::Factory> fakeHttpRequestFactory =
std::make_shared<FakeHttpRequestFactory>(&requests);
auto metadataClient = std::make_shared<ComputeEngineMetadataClient>(
fakeHttpRequestFactory, RetryConfig(0 ));
GoogleAuthProvider provider(std::unique_ptr<OAuthClient>(oauth_client),
metadataClient, &env);
oauth_client->return_token = "fake-token";
oauth_client->return_expiration_timestamp = env.NowSeconds() + 3600;
string token;
TF_EXPECT_OK(provider.GetToken(&token));
EXPECT_EQ("fake-token", token);
EXPECT_EQ("fake_key_id",
oauth_client->provided_credentials_json.get("private_key_id", "")
.asString());
oauth_client->return_token = "new-fake-token";
env.now += 3000;
TF_EXPECT_OK(provider.GetToken(&token));
EXPECT_EQ("fake-token", token);
env.now += 598;
TF_EXPECT_OK(provider.GetToken(&token));
EXPECT_EQ("new-fake-token", token);
}
TEST_F(GoogleAuthProviderTest, GCloudRefreshToken) {
setenv("CLOUDSDK_CONFIG", TestData().c_str(), 1);
auto oauth_client = new FakeOAuthClient;
std::vector<HttpRequest*> requests;
FakeEnv env;
std::shared_ptr<HttpRequest::Factory> fakeHttpRequestFactory =
std::make_shared<FakeHttpRequestFactory>(&requests);
auto metadataClient = std::make_shared<ComputeEngineMetadataClient>(
fakeHttpRequestFactory, RetryConfig(0 ));
GoogleAuthProvider provider(std::unique_ptr<OAuthClient>(oauth_client),
metadataClient, &env);
oauth_client->return_token = "fake-token";
oauth_client->return_expiration_timestamp = env.NowSeconds() + 3600;
string token;
TF_EXPECT_OK(provider.GetToken(&token));
EXPECT_EQ("fake-token", token);
EXPECT_EQ("fake-refresh-token",
oauth_client->provided_credentials_json.get("refresh_token", "")
.asString());
}
TEST_F(GoogleAuthProviderTest, RunningOnGCE) {
auto oauth_client = new FakeOAuthClient;
std::vector<HttpRequest*> requests(
{new FakeHttpRequest(
"Uri: http:
"/service-accounts/default/token\n"
"Header Metadata-Flavor: Google\n",
R"(
{
"access_token":"fake-gce-token",
"expires_in": 3920,
"token_type":"Bearer"
})"),
new FakeHttpRequest(
"Uri: http:
"/service-accounts/default/token\n"
"Header Metadata-Flavor: Google\n",
"", errors::Unavailable("503"), 503),
new FakeHttpRequest(
"Uri: http:
"/service-accounts/default/token\n"
"Header Metadata-Flavor: Google\n",
R"(
{
"access_token":"new-fake-gce-token",
"expires_in": 3920,
"token_type":"Bearer"
})")});
FakeEnv env;
std::shared_ptr<HttpRequest::Factory> fakeHttpRequestFactory =
std::make_shared<FakeHttpRequestFactory>(&requests);
auto metadataClient = std::make_shared<ComputeEngineMetadataClient>(
fakeHttpRequestFactory, RetryConfig(0 ));
GoogleAuthProvider provider(std::unique_ptr<OAuthClient>(oauth_client),
metadataClient, &env);
string token;
TF_EXPECT_OK(provider.GetToken(&token));
EXPECT_EQ("fake-gce-token", token);
env.now += 3700;
TF_EXPECT_OK(provider.GetToken(&token));
EXPECT_EQ("fake-gce-token", token);
env.now += 598;
TF_EXPECT_OK(provider.GetToken(&token));
EXPECT_EQ("new-fake-gce-token", token);
}
TEST_F(GoogleAuthProviderTest, OverrideForTesting) {
setenv("GOOGLE_AUTH_TOKEN_FOR_TESTING", "tokenForTesting", 1);
auto oauth_client = new FakeOAuthClient;
std::vector<HttpRequest*> empty_requests;
FakeEnv env;
std::shared_ptr<HttpRequest::Factory> fakeHttpRequestFactory =
std::make_shared<FakeHttpRequestFactory>(&empty_requests);
auto metadataClient = std::make_shared<ComputeEngineMetadataClient>(
fakeHttpRequestFactory, RetryConfig(0 ));
GoogleAuthProvider provider(std::unique_ptr<OAuthClient>(oauth_client),
metadataClient, &env);
string token;
TF_EXPECT_OK(provider.GetToken(&token));
EXPECT_EQ("tokenForTesting", token);
}
TEST_F(GoogleAuthProviderTest, NothingAvailable) {
auto oauth_client = new FakeOAuthClient;
std::vector<HttpRequest*> requests({new FakeHttpRequest(
"Uri: http:
"/service-accounts/default/token\n"
"Header Metadata-Flavor: Google\n",
"", errors::NotFound("404"), 404)});
FakeEnv env;
std::shared_ptr<HttpRequest::Factory> fakeHttpRequestFactory =
std::make_shared<FakeHttpRequestFactory>(&requests);
auto metadataClient = std::make_shared<ComputeEngineMetadataClient>(
fakeHttpRequestFactory, RetryConfig(0 ));
GoogleAuthProvider provider(std::unique_ptr<OAuthClient>(oauth_client),
metadataClient, &env);
string token;
TF_EXPECT_OK(provider.GetToken(&token));
EXPECT_EQ("", token);
}
TEST_F(GoogleAuthProviderTest, NoGceCheckEnvironmentVariable) {
setenv("NO_GCE_CHECK", "True", 1);
auto oauth_client = new FakeOAuthClient;
FakeEnv env;
GoogleAuthProvider provider(std::unique_ptr<OAuthClient>(oauth_client),
nullptr, &env);
string token;
TF_EXPECT_OK(provider.GetToken(&token));
EXPECT_EQ("", token);
setenv("NO_GCE_CHECK", "true", 1);
TF_EXPECT_OK(provider.GetToken(&token));
EXPECT_EQ("", token);
setenv("GOOGLE_AUTH_TOKEN_FOR_TESTING", "newToken", 1);
TF_EXPECT_OK(provider.GetToken(&token));
EXPECT_EQ("newToken", token);
}
} | 2,278 |
#ifndef TENSORFLOW_TSL_PLATFORM_CLOUD_GCS_FILE_SYSTEM_H_
#define TENSORFLOW_TSL_PLATFORM_CLOUD_GCS_FILE_SYSTEM_H_
#include <string>
#include <unordered_set>
#include <utility>
#include <vector>
#include "tsl/platform/cloud/auth_provider.h"
#include "tsl/platform/cloud/compute_engine_metadata_client.h"
#include "tsl/platform/cloud/compute_engine_zone_provider.h"
#include "tsl/platform/cloud/expiring_lru_cache.h"
#include "tsl/platform/cloud/file_block_cache.h"
#include "tsl/platform/cloud/gcs_dns_cache.h"
#include "tsl/platform/cloud/gcs_throttle.h"
#include "tsl/platform/cloud/http_request.h"
#include "tsl/platform/file_system.h"
#include "tsl/platform/retrying_file_system.h"
#include "tsl/platform/status.h"
namespace tsl {
class GcsFileSystem;
constexpr char kBlockSize[] = "GCS_READ_CACHE_BLOCK_SIZE_MB";
#if defined(LIBTPU_ON_GCE)
constexpr size_t kDefaultBlockSize = 512 * 1024 * 1024;
#else
constexpr size_t kDefaultBlockSize = 64 * 1024 * 1024;
#endif
constexpr char kMaxCacheSize[] = "GCS_READ_CACHE_MAX_SIZE_MB";
#if defined(LIBTPU_ON_GCE)
constexpr size_t kDefaultMaxCacheSize = 163840LL * 1024LL * 1024LL;
#else
constexpr size_t kDefaultMaxCacheSize = 0;
#endif
constexpr char kMaxStaleness[] = "GCS_READ_CACHE_MAX_STALENESS";
constexpr uint64 kDefaultMaxStaleness = 0;
template <typename T>
bool GetEnvVar(const char* varname, bool (*convert)(StringPiece, T*),
T* value) {
const char* env_value = std::getenv(varname);
if (env_value == nullptr) {
return false;
}
return convert(env_value, value);
}
class GcsStatsInterface {
public:
virtual void Configure(GcsFileSystem* fs, GcsThrottle* throttle,
const FileBlockCache* block_cache) = 0;
virtual void RecordBlockLoadRequest(const string& file, size_t offset) = 0;
virtual void RecordBlockRetrieved(const string& file, size_t offset,
size_t bytes_transferred) = 0;
virtual void RecordStatObjectRequest() = 0;
virtual HttpRequest::RequestStats* HttpStats() = 0;
virtual ~GcsStatsInterface() = default;
};
struct UploadSessionHandle {
std::string session_uri;
bool resumable;
};
class GcsFileSystem : public FileSystem {
public:
struct TimeoutConfig;
explicit GcsFileSystem(bool make_default_cache = true);
GcsFileSystem(std::unique_ptr<AuthProvider> auth_provider,
std::unique_ptr<HttpRequest::Factory> http_request_factory,
std::unique_ptr<ZoneProvider> zone_provider, size_t block_size,
size_t max_bytes, uint64 max_staleness,
uint64 stat_cache_max_age, size_t stat_cache_max_entries,
uint64 matching_paths_cache_max_age,
size_t matching_paths_cache_max_entries,
RetryConfig retry_config, TimeoutConfig timeouts,
const std::unordered_set<string>& allowed_locations,
std::pair<const string, const string>* additional_header,
bool compose_append);
TF_USE_FILESYSTEM_METHODS_WITH_NO_TRANSACTION_SUPPORT;
Status NewRandomAccessFile(
const string& fname, TransactionToken* token,
std::unique_ptr<RandomAccessFile>* result) override;
Status NewWritableFile(const string& fname, TransactionToken* token,
std::unique_ptr<WritableFile>* result) override;
Status NewAppendableFile(const string& fname, TransactionToken* token,
std::unique_ptr<WritableFile>* result) override;
Status NewReadOnlyMemoryRegionFromFile(
const string& fname, TransactionToken* token,
std::unique_ptr<ReadOnlyMemoryRegion>* result) override;
Status FileExists(const string& fname, TransactionToken* token) override;
Status Stat(const string& fname, TransactionToken* token,
FileStatistics* stat) override;
Status GetChildren(const string& dir, TransactionToken* token,
std::vector<string>* result) override;
Status GetMatchingPaths(const string& pattern, TransactionToken* token,
std::vector<string>* results) override;
Status DeleteFile(const string& fname, TransactionToken* token) override;
Status CreateDir(const string& dirname, TransactionToken* token) override;
Status DeleteDir(const string& dirname, TransactionToken* token) override;
Status GetFileSize(const string& fname, TransactionToken* token,
uint64* file_size) override;
Status RenameFile(const string& src, const string& target,
TransactionToken* token) override;
Status IsDirectory(const string& fname, TransactionToken* token) override;
Status DeleteRecursively(const string& dirname, TransactionToken* token,
int64_t* undeleted_files,
int64_t* undeleted_dirs) override;
void FlushCaches(TransactionToken* token) override;
void SetStats(GcsStatsInterface* stats);
void SetCacheStats(FileBlockCacheStatsInterface* cache_stats);
size_t block_size() {
tf_shared_lock l(block_cache_lock_);
return file_block_cache_->block_size();
}
size_t max_bytes() {
tf_shared_lock l(block_cache_lock_);
return file_block_cache_->max_bytes();
}
uint64 max_staleness() {
tf_shared_lock l(block_cache_lock_);
return file_block_cache_->max_staleness();
}
TimeoutConfig timeouts() const { return timeouts_; }
std::unordered_set<string> allowed_locations() const {
return allowed_locations_;
}
bool compose_append() const { return compose_append_; }
string additional_header_name() const {
return additional_header_ ? additional_header_->first : "";
}
string additional_header_value() const {
return additional_header_ ? additional_header_->second : "";
}
uint64 stat_cache_max_age() const { return stat_cache_->max_age(); }
size_t stat_cache_max_entries() const { return stat_cache_->max_entries(); }
uint64 matching_paths_cache_max_age() const {
return matching_paths_cache_->max_age();
}
size_t matching_paths_cache_max_entries() const {
return matching_paths_cache_->max_entries();
}
struct TimeoutConfig {
uint32 connect = 120;
uint32 idle = 60;
uint32 metadata = 3600;
uint32 read = 3600;
uint32 write = 3600;
TimeoutConfig() {}
TimeoutConfig(uint32 connect, uint32 idle, uint32 metadata, uint32 read,
uint32 write)
: connect(connect),
idle(idle),
metadata(metadata),
read(read),
write(write) {}
};
Status CreateHttpRequest(std::unique_ptr<HttpRequest>* request);
void SetAuthProvider(std::unique_ptr<AuthProvider> auth_provider);
void ResetFileBlockCache(size_t block_size_bytes, size_t max_bytes,
uint64 max_staleness_secs);
protected:
virtual std::unique_ptr<FileBlockCache> MakeFileBlockCache(
size_t block_size, size_t max_bytes, uint64 max_staleness);
virtual Status LoadBufferFromGCS(const string& fname, size_t offset, size_t n,
char* buffer, size_t* bytes_transferred);
virtual Status CreateNewUploadSession(uint64 start_offset,
const std::string& object_to_upload,
const std::string& bucket,
uint64 file_size,
const std::string& gcs_path,
UploadSessionHandle* session_handle);
virtual Status UploadToSession(const std::string& session_uri,
uint64 start_offset, uint64 already_uploaded,
const std::string& tmp_content_filename,
uint64 file_size,
const std::string& file_path);
virtual Status RequestUploadSessionStatus(const string& session_uri,
uint64 file_size,
const std::string& gcs_path,
bool* completed, uint64* uploaded);
Status ParseGcsPathForScheme(StringPiece fname, string scheme,
bool empty_object_ok, string* bucket,
string* object);
virtual Status ParseGcsPath(StringPiece fname, bool empty_object_ok,
string* bucket, string* object);
std::shared_ptr<ComputeEngineMetadataClient> compute_engine_metadata_client_;
TimeoutConfig timeouts_;
RetryConfig retry_config_;
private:
struct GcsFileStat {
FileStatistics base;
int64_t generation_number = 0;
};
Status BucketExists(const string& bucket, bool* result);
Status GetBucketLocation(const string& bucket, string* location);
Status CheckBucketLocationConstraint(const string& bucket);
Status GetBucketMetadata(const string& bucket,
std::vector<char>* result_buffer);
Status ObjectExists(const string& fname, const string& bucket,
const string& object, bool* result);
Status FolderExists(const string& dirname, bool* result);
Status GetChildrenBounded(const string& dir, uint64 max_results,
std::vector<string>* result, bool recursively,
bool include_self_directory_marker);
Status StatForObject(const string& fname, const string& bucket,
const string& object, GcsFileStat* stat);
Status UncachedStatForObject(const string& fname, const string& bucket,
const string& object, GcsFileStat* stat);
Status RenameObject(const string& src, const string& target);
void ClearFileCaches(const string& fname);
mutex mu_;
std::unique_ptr<AuthProvider> auth_provider_ TF_GUARDED_BY(mu_);
std::shared_ptr<HttpRequest::Factory> http_request_factory_;
std::unique_ptr<ZoneProvider> zone_provider_;
uint64 block_size_;
mutex block_cache_lock_;
std::unique_ptr<FileBlockCache> file_block_cache_
TF_GUARDED_BY(block_cache_lock_);
bool cache_enabled_;
std::unique_ptr<GcsDnsCache> dns_cache_;
GcsThrottle throttle_;
using StatCache = ExpiringLRUCache<GcsFileStat>;
std::unique_ptr<StatCache> stat_cache_;
using MatchingPathsCache = ExpiringLRUCache<std::vector<string>>;
std::unique_ptr<MatchingPathsCache> matching_paths_cache_;
using BucketLocationCache = ExpiringLRUCache<string>;
std::unique_ptr<BucketLocationCache> bucket_location_cache_;
std::unordered_set<string> allowed_locations_;
bool compose_append_;
GcsStatsInterface* stats_ = nullptr;
std::unique_ptr<std::pair<const string, const string>> additional_header_;
GcsFileSystem(const GcsFileSystem&) = delete;
void operator=(const GcsFileSystem&) = delete;
};
class RetryingGcsFileSystem : public RetryingFileSystem<GcsFileSystem> {
public:
RetryingGcsFileSystem();
};
}
#endif
#include "tsl/platform/cloud/gcs_file_system.h"
#include <stdio.h>
#include "absl/status/status.h"
#include "absl/strings/str_cat.h"
#ifndef _WIN32
#include <unistd.h>
#endif
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <functional>
#include <string>
#include <utility>
#include <vector>
#include "tsl/platform/file_statistics.h"
#include "tsl/platform/strcat.h"
#ifdef _WIN32
#include <io.h>
#endif
#include "absl/base/macros.h"
#include "json/json.h"
#include "tsl/platform/cloud/curl_http_request.h"
#include "tsl/platform/cloud/file_block_cache.h"
#include "tsl/platform/cloud/google_auth_provider.h"
#include "tsl/platform/cloud/ram_file_block_cache.h"
#include "tsl/platform/cloud/time_util.h"
#include "tsl/platform/env.h"
#include "tsl/platform/errors.h"
#include "tsl/platform/mutex.h"
#include "tsl/platform/numbers.h"
#include "tsl/platform/path.h"
#include "tsl/platform/protobuf.h"
#include "tsl/platform/retrying_utils.h"
#include "tsl/platform/str_util.h"
#include "tsl/platform/stringprintf.h"
#include "tsl/platform/thread_annotations.h"
#include "tsl/profiler/lib/traceme.h"
#ifdef _WIN32
#ifdef DeleteFile
#undef DeleteFile
#endif
#endif
namespace tsl {
namespace {
constexpr char kGcsUriBase[] = "https:
constexpr char kGcsUploadUriBase[] =
"https:
constexpr char kStorageHost[] = "storage.googleapis.com";
constexpr char kBucketMetadataLocationKey[] = "location";
constexpr size_t kReadAppendableFileBufferSize = 1024 * 1024;
constexpr int kGetChildrenDefaultPageSize = 1000;
constexpr uint64 HTTP_CODE_RESUME_INCOMPLETE = 308;
constexpr uint64 HTTP_CODE_PRECONDITION_FAILED = 412;
ABSL_DEPRECATED("Use GCS_READ_CACHE_BLOCK_SIZE_MB instead.")
constexpr char kReadaheadBufferSize[] = "GCS_READAHEAD_BUFFER_SIZE_BYTES";
constexpr char kStatCacheMaxAge[] = "GCS_STAT_CACHE_MAX_AGE";
constexpr uint64 kStatCacheDefaultMaxAge = 5;
constexpr char kStatCacheMaxEntries[] = "GCS_STAT_CACHE_MAX_ENTRIES";
constexpr size_t kStatCacheDefaultMaxEntries = 1024;
constexpr char kMatchingPathsCacheMaxAge[] = "GCS_MATCHING_PATHS_CACHE_MAX_AGE";
constexpr uint64 kMatchingPathsCacheDefaultMaxAge = 0;
constexpr char kMatchingPathsCacheMaxEntries[] =
"GCS_MATCHING_PATHS_CACHE_MAX_ENTRIES";
constexpr size_t kMatchingPathsCacheDefaultMaxEntries = 1024;
constexpr size_t kBucketLocationCacheMaxEntries = 10;
constexpr size_t kCacheNeverExpire = std::numeric_limits<uint64>::max();
const FileStatistics DIRECTORY_STAT(0, 0, true);
constexpr char kResolveCacheSecs[] = "GCS_RESOLVE_REFRESH_SECS";
constexpr char kRequestConnectionTimeout[] =
"GCS_REQUEST_CONNECTION_TIMEOUT_SECS";
constexpr char kRequestIdleTimeout[] = "GCS_REQUEST_IDLE_TIMEOUT_SECS";
constexpr char kMetadataRequestTimeout[] = "GCS_METADATA_REQUEST_TIMEOUT_SECS";
constexpr char kReadRequestTimeout[] = "GCS_READ_REQUEST_TIMEOUT_SECS";
constexpr char kWriteRequestTimeout[] = "GCS_WRITE_REQUEST_TIMEOUT_SECS";
constexpr char kAdditionalRequestHeader[] = "GCS_ADDITIONAL_REQUEST_HEADER";
constexpr char kThrottleRate[] = "GCS_THROTTLE_TOKEN_RATE";
constexpr char kThrottleBucket[] = "GCS_THROTTLE_BUCKET_SIZE";
constexpr char kTokensPerRequest[] = "GCS_TOKENS_PER_REQUEST";
constexpr char kInitialTokens[] = "GCS_INITIAL_TOKENS";
constexpr char kRetryConfigInitialDelayTimeUs[] =
"GCS_RETRY_CONFIG_INIT_DELAY_TIME_US";
constexpr char kRetryConfigMaxDelayTimeUs[] =
"GCS_RETRY_CONFIG_MAX_DELAY_TIME_US";
constexpr char kRetryConfigMaxRetries[] = "GCS_RETRY_CONFIG_MAX_RETRIES";
constexpr char kAllowedBucketLocations[] = "GCS_ALLOWED_BUCKET_LOCATIONS";
constexpr char kDetectZoneSentinelValue[] = "auto";
constexpr char kAppendMode[] = "GCS_APPEND_MODE";
constexpr char kComposeAppend[] = "compose";
Status GetTmpFilename(string* filename) {
*filename = io::GetTempFilename("");
return OkStatus();
}
string MaybeAppendSlash(const string& name) {
if (name.empty()) {
return "/";
}
if (name.back() != '/') {
return strings::StrCat(name, "/");
}
return name;
}
string JoinGcsPath(const string& path, const string& subpath) {
return strings::StrCat(MaybeAppendSlash(path), subpath);
}
std::set<string> AddAllSubpaths(const std::vector<string>& paths) {
std::set<string> result;
result.insert(paths.begin(), paths.end());
for (const string& path : paths) {
StringPiece subpath = io::Dirname(path);
while (!(subpath.empty() || subpath == "/")) {
result.emplace(string(subpath));
subpath = io::Dirname(subpath);
}
}
return result;
}
Status ParseJson(StringPiece json, Json::Value* result) {
Json::Reader reader;
if (!reader.parse(json.data(), json.data() + json.size(), *result)) {
return errors::Internal("Couldn't parse JSON response from GCS.");
}
return OkStatus();
}
Status ParseJson(const std::vector<char>& json, Json::Value* result) {
return ParseJson(StringPiece{json.data(), json.size()}, result);
}
Status GetValue(const Json::Value& parent, const char* name,
Json::Value* result) {
*result = parent.get(name, Json::Value::null);
if (result->isNull()) {
return errors::Internal("The field '", name,
"' was expected in the JSON response.");
}
return OkStatus();
}
Status GetStringValue(const Json::Value& parent, const char* name,
string* result) {
Json::Value result_value;
TF_RETURN_IF_ERROR(GetValue(parent, name, &result_value));
if (!result_value.isString()) {
return errors::Internal(
"The field '", name,
"' in the JSON response was expected to be a string.");
}
*result = result_value.asString();
return OkStatus();
}
Status GetInt64Value(const Json::Value& parent, const char* name,
int64_t* result) {
Json::Value result_value;
TF_RETURN_IF_ERROR(GetValue(parent, name, &result_value));
if (result_value.isNumeric()) {
*result = result_value.asInt64();
return OkStatus();
}
if (result_value.isString() &&
strings::safe_strto64(result_value.asCString(), result)) {
return OkStatus();
}
return errors::Internal(
"The field '", name,
"' in the JSON response was expected to be a number.");
}
Status GetBoolValue(const Json::Value& parent, const char* name, bool* result) {
Json::Value result_value;
TF_RETURN_IF_ERROR(GetValue(parent, name, &result_value));
if (!result_value.isBool()) {
return errors::Internal(
"The field '", name,
"' in the JSON response was expected to be a boolean.");
}
*result = result_value.asBool();
return OkStatus();
}
RetryConfig GetGcsRetryConfig() {
RetryConfig retryConfig(
1000 * 1000,
32 * 1000 * 1000,
10);
uint64 init_delay_time_us;
if (GetEnvVar(kRetryConfigInitialDelayTimeUs, strings::safe_strtou64,
&init_delay_time_us)) {
retryConfig.init_delay_time_us = init_delay_time_us;
}
uint64 max_delay_time_us;
if (GetEnvVar(kRetryConfigMaxDelayTimeUs, strings::safe_strtou64,
&max_delay_time_us)) {
retryConfig.max_delay_time_us = max_delay_time_us;
}
uint32 max_retries;
if (GetEnvVar(kRetryConfigMaxRetries, strings::safe_strtou32, &max_retries)) {
retryConfig.max_retries = max_retries;
}
VLOG(1) << "GCS RetryConfig: "
<< "init_delay_time_us = " << retryConfig.init_delay_time_us << " ; "
<< "max_delay_time_us = " << retryConfig.max_delay_time_us << " ; "
<< "max_retries = " << retryConfig.max_retries;
return retryConfig;
}
class GcsRandomAccessFile : public RandomAccessFile {
public:
using ReadFn =
std::function<Status(const string& filename, uint64 offset, size_t n,
StringPiece* result, char* scratch)>;
GcsRandomAccessFile(const string& filename, ReadFn read_fn)
: filename_(filename), read_fn_(std::move(read_fn)) {}
Status Name(StringPiece* result) const override {
*result = filename_;
return OkStatus();
}
Status Read(uint64 offset, size_t n, StringPiece* result,
char* scratch) const override {
return read_fn_(filename_, offset, n, result, scratch);
}
private:
const string filename_;
const ReadFn read_fn_;
};
class BufferedGcsRandomAccessFile : public RandomAccessFile {
public:
using ReadFn =
std::function<Status(const string& filename, uint64 offset, size_t n,
StringPiece* result, char* scratch)>;
BufferedGcsRandomAccessFile(const string& filename, uint64 buffer_size,
ReadFn read_fn)
: filename_(filename), | #include "tsl/platform/cloud/gcs_file_system.h"
#include <fstream>
#include "tsl/lib/core/status_test_util.h"
#include "tsl/platform/cloud/http_request_fake.h"
#include "tsl/platform/errors.h"
#include "tsl/platform/str_util.h"
#include "tsl/platform/strcat.h"
#include "tsl/platform/test.h"
#ifdef PLATFORM_WINDOWS
#undef DeleteFile
#endif
namespace tsl {
namespace {
static GcsFileSystem::TimeoutConfig kTestTimeoutConfig(5, 1, 10, 20, 30);
static RetryConfig kTestRetryConfig(0 );
static std::unordered_set<string>* kAllowedLocationsDefault =
new std::unordered_set<string>();
static std::unordered_set<string>* kAllowedLocationsAuto =
new std::unordered_set<string>({"auto"});
class FakeAuthProvider : public AuthProvider {
public:
Status GetToken(string* token) override {
*token = "fake_token";
return OkStatus();
}
};
class FakeZoneProvider : public ZoneProvider {
public:
Status GetZone(string* zone) override {
*zone = "us-east1-b";
return OkStatus();
}
};
TEST(GcsFileSystemTest, NewRandomAccessFile_NoBlockCache) {
std::vector<HttpRequest*> requests(
{new FakeHttpRequest(
"Uri: https:
"Auth Token: fake_token\n"
"Range: 0-5\n"
"Timeouts: 5 1 20\n",
"012345"),
new FakeHttpRequest(
"Uri: https:
"Auth Token: fake_token\n"
"Range: 6-11\n"
"Timeouts: 5 1 20\n",
"6789")});
GcsFileSystem fs(
std::unique_ptr<AuthProvider>(new FakeAuthProvider),
std::unique_ptr<HttpRequest::Factory>(
new FakeHttpRequestFactory(&requests)),
std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 0 ,
0 , 0 , 0 ,
0 , 0 ,
0 , kTestRetryConfig,
kTestTimeoutConfig, *kAllowedLocationsDefault,
nullptr , false );
std::unique_ptr<RandomAccessFile> file;
TF_EXPECT_OK(
fs.NewRandomAccessFile("gs:
StringPiece filename;
TF_EXPECT_OK(file->Name(&filename));
EXPECT_EQ(filename, "gs:
char scratch[6];
StringPiece result;
TF_EXPECT_OK(file->Read(0, sizeof(scratch), &result, scratch));
EXPECT_EQ("012345", result);
EXPECT_TRUE(errors::IsOutOfRange(
file->Read(sizeof(scratch), sizeof(scratch), &result, scratch)));
EXPECT_EQ("6789", result);
}
TEST(GcsFileSystemTest, NewRandomAccessFile_Buffered) {
std::vector<HttpRequest*> requests({
new FakeHttpRequest(
"Uri: https:
"Auth Token: fake_token\n"
"Range: 0-9\n"
"Timeouts: 5 1 20\n",
"0123456789"),
new FakeHttpRequest(
"Uri: https:
"Auth Token: fake_token\n"
"Range: 10-19\n"
"Timeouts: 5 1 20\n",
""),
});
GcsFileSystem fs(
std::unique_ptr<AuthProvider>(new FakeAuthProvider),
std::unique_ptr<HttpRequest::Factory>(
new FakeHttpRequestFactory(&requests)),
std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 10 ,
0 , 0 , 0 ,
0 , 0 ,
0 , kTestRetryConfig,
kTestTimeoutConfig, *kAllowedLocationsDefault,
nullptr , false );
std::unique_ptr<RandomAccessFile> file;
TF_EXPECT_OK(
fs.NewRandomAccessFile("gs:
StringPiece filename;
TF_EXPECT_OK(file->Name(&filename));
EXPECT_EQ(filename, "gs:
char scratch[6];
StringPiece result;
TF_EXPECT_OK(file->Read(0, sizeof(scratch), &result, scratch));
EXPECT_EQ("012345", result);
EXPECT_TRUE(errors::IsOutOfRange(
file->Read(sizeof(scratch), sizeof(scratch), &result, scratch)));
EXPECT_EQ("6789", result);
}
TEST(GcsFileSystemTest, NewRandomAccessFile_Buffered_Errors) {
std::vector<HttpRequest*> requests({
new FakeHttpRequest(
"Uri: https:
"Auth Token: fake_token\n"
"Range: 0-9\n"
"Timeouts: 5 1 20\n",
"Server Not", errors::Unavailable("important HTTP error 308"),
nullptr, {}, 308),
new FakeHttpRequest(
"Uri: https:
"Auth Token: fake_token\n"
"Range: 6-15\n"
"Timeouts: 5 1 20\n",
"123"),
});
GcsFileSystem fs(
std::unique_ptr<AuthProvider>(new FakeAuthProvider),
std::unique_ptr<HttpRequest::Factory>(
new FakeHttpRequestFactory(&requests)),
std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 10 ,
0 , 0 , 0 ,
0 , 0 ,
0 , kTestRetryConfig,
kTestTimeoutConfig, *kAllowedLocationsDefault,
nullptr , false );
std::unique_ptr<RandomAccessFile> file;
TF_EXPECT_OK(
fs.NewRandomAccessFile("gs:
StringPiece filename;
TF_EXPECT_OK(file->Name(&filename));
EXPECT_EQ(filename, "gs:
char scratch[6];
StringPiece result;
EXPECT_TRUE(
errors::IsUnavailable(file->Read(0, sizeof(scratch), &result, scratch)));
EXPECT_EQ("", result);
EXPECT_TRUE(errors::IsOutOfRange(
file->Read(sizeof(scratch), sizeof(scratch), &result, scratch)));
EXPECT_EQ("123", result);
}
TEST(GcsFileSystemTest, NewRandomAccessFile_Buffered_ReadAtEOF) {
std::vector<HttpRequest*> requests(
{new FakeHttpRequest(
"Uri: https:
"Auth Token: fake_token\n"
"Range: 0-9\n"
"Timeouts: 5 1 20\n",
"0123456789"),
new FakeHttpRequest(
"Uri: https:
"Auth Token: fake_token\n"
"Range: 10-19\n"
"Timeouts: 5 1 20\n",
"")});
GcsFileSystem fs(
std::unique_ptr<AuthProvider>(new FakeAuthProvider),
std::unique_ptr<HttpRequest::Factory>(
new FakeHttpRequestFactory(&requests)),
std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 10 ,
0 , 0 , 0 ,
0 , 0 ,
0 , kTestRetryConfig,
kTestTimeoutConfig, *kAllowedLocationsDefault,
nullptr , false );
std::unique_ptr<RandomAccessFile> file;
TF_EXPECT_OK(
fs.NewRandomAccessFile("gs:
StringPiece filename;
TF_EXPECT_OK(file->Name(&filename));
EXPECT_EQ(filename, "gs:
char scratch[10];
StringPiece result;
TF_EXPECT_OK(file->Read(0, sizeof(scratch), &result, scratch));
EXPECT_EQ("0123456789", result);
EXPECT_TRUE(errors::IsOutOfRange(
file->Read(sizeof(scratch), sizeof(scratch), &result, scratch)));
EXPECT_EQ("", result);
}
TEST(GcsFileSystemTest, NewRandomAccessFile_Buffered_CachedOutOfRange) {
std::vector<HttpRequest*> requests({new FakeHttpRequest(
"Uri: https:
"Auth Token: fake_token\n"
"Range: 0-9\n"
"Timeouts: 5 1 20\n",
"012345678")});
GcsFileSystem fs(
std::unique_ptr<AuthProvider>(new FakeAuthProvider),
std::unique_ptr<HttpRequest::Factory>(
new FakeHttpRequestFactory(&requests)),
std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 10 ,
0 , 0 , 0 ,
0 , 0 ,
0 , kTestRetryConfig,
kTestTimeoutConfig, *kAllowedLocationsDefault,
nullptr , false );
std::unique_ptr<RandomAccessFile> file;
TF_EXPECT_OK(
fs.NewRandomAccessFile("gs:
StringPiece filename;
TF_EXPECT_OK(file->Name(&filename));
EXPECT_EQ(filename, "gs:
char scratch[5];
StringPiece result;
TF_EXPECT_OK(file->Read(0, sizeof(scratch), &result, scratch));
EXPECT_EQ("01234", result);
TF_EXPECT_OK(file->Read(4, sizeof(scratch), &result, scratch));
EXPECT_EQ("45678", result);
EXPECT_TRUE(
errors::IsOutOfRange(file->Read(5, sizeof(scratch), &result, scratch)));
EXPECT_EQ("5678", result);
}
TEST(GcsFileSystemTest, NewRandomAccessFile_Buffered_CachedNotSequential) {
std::vector<HttpRequest*> requests(
{new FakeHttpRequest(
"Uri: https:
"Auth Token: fake_token\n"
"Range: 1-10\n"
"Timeouts: 5 1 20\n",
"12345678"),
new FakeHttpRequest(
"Uri: https:
"Auth Token: fake_token\n"
"Range: 0-9\n"
"Timeouts: 5 1 20\n",
"012345678")});
GcsFileSystem fs(
std::unique_ptr<AuthProvider>(new FakeAuthProvider),
std::unique_ptr<HttpRequest::Factory>(
new FakeHttpRequestFactory(&requests)),
std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 10 ,
0 , 0 , 0 ,
0 , 0 ,
0 , kTestRetryConfig,
kTestTimeoutConfig, *kAllowedLocationsDefault,
nullptr , false );
std::unique_ptr<RandomAccessFile> file;
TF_EXPECT_OK(
fs.NewRandomAccessFile("gs:
StringPiece filename;
TF_EXPECT_OK(file->Name(&filename));
EXPECT_EQ(filename, "gs:
char scratch[5];
StringPiece result;
TF_EXPECT_OK(file->Read(1, sizeof(scratch), &result, scratch));
EXPECT_EQ("12345", result);
TF_EXPECT_OK(file->Read(0, sizeof(scratch), &result, scratch));
EXPECT_EQ("01234", result);
}
TEST(GcsFileSystemTest, NewRandomAccessFile_Buffered_Growing) {
std::vector<HttpRequest*> requests(
{new FakeHttpRequest(
"Uri: https:
"Auth Token: fake_token\n"
"Range: 0-9\n"
"Timeouts: 5 1 20\n",
"012345678"),
new FakeHttpRequest(
"Uri: https:
"Auth Token: fake_token\n"
"Range: 9-18\n"
"Timeouts: 5 1 20\n",
"9")});
GcsFileSystem fs(
std::unique_ptr<AuthProvider>(new FakeAuthProvider),
std::unique_ptr<HttpRequest::Factory>(
new FakeHttpRequestFactory(&requests)),
std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 10 ,
0 , 0 , 0 ,
0 , 0 ,
0 , kTestRetryConfig,
kTestTimeoutConfig, *kAllowedLocationsDefault,
nullptr , false );
std::unique_ptr<RandomAccessFile> file;
TF_EXPECT_OK(
fs.NewRandomAccessFile("gs:
StringPiece filename;
TF_EXPECT_OK(file->Name(&filename));
EXPECT_EQ(filename, "gs:
char scratch[10];
StringPiece result;
EXPECT_TRUE(
errors::IsOutOfRange(file->Read(0, sizeof(scratch), &result, scratch)));
EXPECT_EQ("012345678", result);
TF_EXPECT_OK(file->Read(0, sizeof(scratch), &result, scratch));
EXPECT_EQ("0123456789", result);
}
TEST(GcsFileSystemTest, NewRandomAccessFile_Buffered_ReadBackwards) {
std::vector<HttpRequest*> requests(
{new FakeHttpRequest(
"Uri: https:
"Auth Token: fake_token\n"
"Range: 5-14\n"
"Timeouts: 5 1 20\n",
"56789"),
new FakeHttpRequest(
"Uri: https:
"Auth Token: fake_token\n"
"Range: 0-9\n"
"Timeouts: 5 1 20\n",
"0123456789")});
GcsFileSystem fs(
std::unique_ptr<AuthProvider>(new FakeAuthProvider),
std::unique_ptr<HttpRequest::Factory>(
new FakeHttpRequestFactory(&requests)),
std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 10 ,
0 , 0 , 0 ,
0 , 0 ,
0 , kTestRetryConfig,
kTestTimeoutConfig, *kAllowedLocationsDefault,
nullptr , false );
std::unique_ptr<RandomAccessFile> file;
TF_EXPECT_OK(
fs.NewRandomAccessFile("gs:
StringPiece filename;
TF_EXPECT_OK(file->Name(&filename));
EXPECT_EQ(filename, "gs:
char scratch[10];
StringPiece result;
EXPECT_TRUE(
errors::IsOutOfRange(file->Read(5, sizeof(scratch), &result, scratch)));
EXPECT_EQ("56789", result);
TF_EXPECT_OK(file->Read(0, sizeof(scratch), &result, scratch));
EXPECT_EQ("0123456789", result);
}
TEST(GcsFileSystemTest,
NewRandomAccessFile_WithLocationConstraintInSameLocation) {
std::vector<HttpRequest*> requests({new FakeHttpRequest(
"Uri: https:
"Auth Token: fake_token\n"
"Timeouts: 5 1 10\n",
R"(
{
"location":"US-EAST1"
})")});
GcsFileSystem fs(
std::unique_ptr<AuthProvider>(new FakeAuthProvider),
std::unique_ptr<HttpRequest::Factory>(
new FakeHttpRequestFactory(&requests)),
std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 0 ,
0 , 0 , 0 ,
0 , 0 ,
0 , kTestRetryConfig,
kTestTimeoutConfig, *kAllowedLocationsAuto,
nullptr , false );
std::unique_ptr<RandomAccessFile> file;
TF_EXPECT_OK(
fs.NewRandomAccessFile("gs:
}
TEST(GcsFileSystemTest, NewRandomAccessFile_WithLocationConstraintCaching) {
std::vector<HttpRequest*> requests(
{new FakeHttpRequest(
"Uri: https:
"Auth Token: fake_token\n"
"Timeouts: 5 1 10\n",
R"(
{
"location":"US-EAST1"
})"),
new FakeHttpRequest(
"Uri: https:
"Auth Token: fake_token\n"
"Timeouts: 5 1 10\n",
R"(
{
"location":"US-EAST1"
})"),
new FakeHttpRequest(
"Uri: https:
"Auth Token: fake_token\n"
"Timeouts: 5 1 10\n",
R"(
{
"location":"US-EAST1"
})")});
GcsFileSystem fs(
std::unique_ptr<AuthProvider>(new FakeAuthProvider),
std::unique_ptr<HttpRequest::Factory>(
new FakeHttpRequestFactory(&requests)),
std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 0 ,
0 , 0 , 0 ,
0 , 0 ,
0 , kTestRetryConfig,
kTestTimeoutConfig, *kAllowedLocationsAuto,
nullptr , false );
std::unique_ptr<RandomAccessFile> file;
string bucket = "gs:
string another_bucket = "gs:
TF_EXPECT_OK(fs.NewRandomAccessFile(bucket, nullptr, &file));
TF_EXPECT_OK(fs.NewRandomAccessFile(bucket, nullptr, &file));
TF_EXPECT_OK(fs.NewRandomAccessFile(another_bucket, nullptr, &file));
TF_EXPECT_OK(fs.NewRandomAccessFile(bucket, nullptr, &file));
TF_EXPECT_OK(fs.NewRandomAccessFile(another_bucket, nullptr, &file));
fs.FlushCaches(nullptr);
TF_EXPECT_OK(fs.NewRandomAccessFile(bucket, nullptr, &file));
}
TEST(GcsFileSystemTest,
NewRandomAccessFile_WithLocationConstraintInDifferentLocation) {
std::vector<HttpRequest*> requests({new FakeHttpRequest(
"Uri: https:
"Auth Token: fake_token\n"
"Timeouts: 5 1 10\n",
R"(
{
"location":"BARFOO"
})")});
GcsFileSystem fs(
std::unique_ptr<AuthProvider>(new FakeAuthProvider),
std::unique_ptr<HttpRequest::Factory>(
new FakeHttpRequestFactory(&requests)),
std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 0 ,
0 , 0 , 0 ,
0 , 0 ,
0 , kTestRetryConfig,
kTestTimeoutConfig, *kAllowedLocationsAuto,
nullptr , false );
std::unique_ptr<RandomAccessFile> file;
EXPECT_EQ(
errors::FailedPrecondition(
"Bucket 'bucket' is in 'barfoo' location, allowed locations "
"are: (us-east1)."),
fs.NewRandomAccessFile("gs:
}
TEST(GcsFileSystemTest, NewRandomAccessFile_NoBlockCache_DifferentN) {
std::vector<HttpRequest*> requests(
{new FakeHttpRequest(
"Uri: https:
"Auth Token: fake_token\n"
"Range: 0-2\n"
"Timeouts: 5 1 20\n",
"012"),
new FakeHttpRequest(
"Uri: https:
"Auth Token: fake_token\n"
"Range: 3-12\n"
"Timeouts: 5 1 20\n",
"3456789")});
GcsFileSystem fs(
std::unique_ptr<AuthProvider>(new FakeAuthProvider),
std::unique_ptr<HttpRequest::Factory>(
new FakeHttpRequestFactory(&requests)),
std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 0 ,
0 , 0 , 0 ,
0 , 0 ,
0 , kTestRetryConfig,
kTestTimeoutConfig, *kAllowedLocationsDefault,
nullptr , false );
std::unique_ptr<RandomAccessFile> file;
TF_EXPECT_OK(
fs.NewRandomAccessFile("gs:
char small_scratch[3];
StringPiece result;
TF_EXPECT_OK(file->Read(0, sizeof(small_scratch), &result, small_scratch));
EXPECT_EQ("012", result);
char large_scratch[10];
EXPECT_TRUE(errors::IsOutOfRange(file->Read(
sizeof(small_scratch), sizeof(large_scratch), &result, large_scratch)));
EXPECT_EQ("3456789", result);
}
TEST(GcsFileSystemTest, NewRandomAccessFile_WithBlockCache) {
std::vector<HttpRequest*> requests(
{new FakeHttpRequest(
"Uri: https:
"random_access.txt?fields=size%2Cgeneration%2Cupdated\n"
"Auth Token: fake_token\n"
"Timeouts: 5 1 10\n",
strings::StrCat("{\"size\": \"15\",\"generation\": \"1\","
"\"updated\": \"2016-04-29T23:15:24.896Z\"}")),
new FakeHttpRequest(
"Uri: https:
"Auth Token: fake_token\n"
"Range: 0-8\n"
"Timeouts: 5 1 20\n",
"012345678"),
new FakeHttpRequest(
"Uri: https:
"Auth Token: fake_token\n"
"Range: 9-17\n"
"Timeouts: 5 1 20\n",
"9abcde"),
new FakeHttpRequest(
"Uri: https:
"Auth Token: fake_token\n"
"Range: 18-26\n"
"Timeouts: 5 1 20\n",
"")});
GcsFileSystem fs(
std::unique_ptr<AuthProvider>(new FakeAuthProvider),
std::unique_ptr<HttpRequest::Factory>(
new FakeHttpRequestFactory(&requests)),
std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 9 ,
18 , 0 , 3600 ,
0 , 0 ,
0 , kTestRetryConfig,
kTestTimeoutConfig, *kAllowedLocationsDefault,
nullptr , false );
char scratch[100];
StringPiece result;
{
std::unique_ptr<RandomAccessFile> file;
TF_EXPECT_OK(fs.NewRandomAccessFile("gs:
nullptr, &file));
scratch[5] = 'x';
TF_EXPECT_OK(file->Read(0, 4, &result, scratch));
EXPECT_EQ("0123", result);
EXPECT_EQ(scratch[5], 'x');
TF_EXPECT_OK(file->Read(4, 4, &result, scratch));
EXPECT_EQ("4567", result);
TF_EXPECT_OK(file->Read(6, 5, &result, scratch));
EXPECT_EQ("6789a", result);
EXPECT_TRUE(errors::IsOutOfRange(file->Read(6, 10, &result, scratch)));
EXPECT_EQ("6789abcde", result);
EXPECT_TRUE(errors::IsOutOfRange(file->Read(20, 10, &result, scratch)));
EXPECT_TRUE(result.empty());
TF_EXPECT_OK(file->Read(0, 4, &result, scratch));
}
EXPECT_EQ("0123", result);
}
TEST(GcsFileSystemTest, NewRandomAccessFile_WithBlockCache_Flush) {
std::vector<HttpRequest*> requests(
{new FakeHttpRequest(
"Uri: https:
"random_access.txt?fields=size%2Cgeneration%2Cupdated\n"
"Auth Token: fake_token\n"
"Timeouts: 5 1 10\n",
strings::StrCat("{\"size\": \"15\",\"generation\": \"1\","
"\"updated\": \"2016-04-29T23:15:24.896Z\"}")),
new FakeHttpRequest(
"Uri: https:
"Auth Token: fake_token\n"
"Range: 0-8\n"
"Timeouts: 5 1 20\n",
"012345678"),
new FakeHttpRequest(
"Uri: https:
"random_access.txt?fields=size%2Cgeneration%2Cupdated\n"
"Auth Token: fake_token\n"
"Timeouts: 5 1 10\n",
strings::StrCat("{\"size\": \"15\",\"generation\": \"1\","
"\"updated\": \"2016-04-29T23:15:24.896Z\"}")),
new FakeHttpRequest(
"Uri: https:
"Auth Token: fake_token\n"
"Range: 0-8\n"
"Timeouts: 5 1 20\n",
"012345678")});
GcsFileSystem fs(
std::unique_ptr<AuthProvider>(new FakeAuthProvider),
std::unique_ptr<HttpRequest::Factory>(
new FakeHttpRequestFactory(&requests)),
std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 9 ,
18 , 0 , 3600 ,
0 , 0 ,
0 , kTestRetryConfig,
kTestTimeoutConfig, *kAllowedLocationsDefault,
nullptr , false );
char scratch[100];
StringPiece result;
std::unique_ptr<RandomAccessFile> file;
TF_EXPECT_OK(
fs.NewRandomAccessFile("gs:
scratch[5] = 'x';
TF_EXPECT_OK(file->Read(0, 4, &result, scratch));
EXPECT_EQ("0123", result);
EXPECT_EQ(scratch[5], 'x');
fs.FlushCaches(nullptr);
TF_EXPECT_OK(file->Read(4, 4, &result, scratch));
EXPECT_EQ("4567", result);
}
TEST(GcsFileSystemTest, NewRandomAccessFile_WithBlockCache_MaxStaleness) {
std::vector<HttpRequest*> requests(
{new FakeHttpRequest(
"Uri: https:
"object?fields=size%2Cgeneration%2Cupdated\n"
"Auth Token: fake_token\n"
"Timeouts: 5 1 10\n",
strings::StrCat("{\"size\": \"16\",\"generation\": \"1\","
"\"updated\": \"2016-04-29T23:15:24.896Z\"}")),
new FakeHttpRequest("Uri: https:
"Auth Token: fake_token\n"
"Range: 0-7\n"
"Timeouts: 5 1 20\n",
"01234567"),
new FakeHttpRequest("Uri: https:
"Auth Token: fake_token\n"
"Range: 8-15\n"
"Timeouts: 5 1 20\n",
"89abcdef")});
GcsFileSystem fs(
std::unique_ptr<AuthProvider>(new FakeAuthProvider),
std::unique_ptr<HttpRequest::Factory>(
new FakeHttpRequestFactory(&requests)),
std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 8 ,
16 , 3600 ,
3600 , 0 ,
0 ,
0 , kTestRetryConfig,
kTestTimeoutConfig, *kAllowedLocationsDefault,
nullptr , false );
char scratch[100];
StringPiece result;
for (int i = 0; i < 10; i++) {
std::unique_ptr<RandomAccessFile> file1;
std::unique_ptr<RandomAccessFile> file2;
TF_EXPECT_OK(fs.NewRandomAccessFile("gs:
TF_EXPECT_OK(fs.NewRandomAccessFile("gs:
TF_EXPECT_OK(file1->Read(0, 8, &result, scratch));
EXPECT_EQ("01234567", result);
TF_EXPECT_OK(file2->Read(0, 8, &result, scratch));
EXPECT_EQ("01234567", result);
TF_EXPECT_OK(file2->Read(8, 8, &result, scratch));
EXPECT_EQ("89abcdef", result);
TF_EXPECT_OK(file1->Read(8, 8, &result, scratch));
EXPECT_EQ("89abcdef", result);
}
}
TEST(GcsFileSystemTest,
NewRandomAccessFile_WithBlockCache_FileSignatureChanges) {
std::vector<HttpRequest*> requests(
{new FakeHttpRequest(
"Uri: https:
"random_access.txt?fields=size%2Cgeneration%2Cupdated\n"
"Auth Token: fake_token\n"
"Timeouts: 5 1 10\n",
strings::StrCat("{\"size\": \"5\",\"generation\": \"1\","
"\"updated\": \"2016-04-29T23:15:24.896Z\"}")),
new FakeHttpR | 2,279 |
#ifndef TENSORFLOW_TSL_PLATFORM_CLOUD_GCS_DNS_CACHE_H_
#define TENSORFLOW_TSL_PLATFORM_CLOUD_GCS_DNS_CACHE_H_
#include <random>
#include "tsl/platform/cloud/http_request.h"
#include "tsl/platform/env.h"
namespace tsl {
const int64_t kDefaultRefreshRateSecs = 60;
class GcsDnsCache {
public:
GcsDnsCache() : GcsDnsCache(kDefaultRefreshRateSecs) {}
GcsDnsCache(int64_t refresh_rate_secs)
: GcsDnsCache(Env::Default(), refresh_rate_secs) {}
GcsDnsCache(Env* env, int64_t refresh_rate_secs);
~GcsDnsCache() {
mutex_lock l(mu_);
cancelled_ = true;
cond_var_.notify_one();
}
void AnnotateRequest(HttpRequest* request);
private:
static std::vector<string> ResolveName(const string& name);
static std::vector<std::vector<string>> ResolveNames(
const std::vector<string>& names);
void WorkerThread();
friend class GcsDnsCacheTest;
mutex mu_;
Env* env_;
condition_variable cond_var_;
std::default_random_engine random_ TF_GUARDED_BY(mu_);
bool started_ TF_GUARDED_BY(mu_) = false;
bool cancelled_ TF_GUARDED_BY(mu_) = false;
std::unique_ptr<Thread> worker_ TF_GUARDED_BY(mu_);
const int64_t refresh_rate_secs_;
std::vector<std::vector<string>> addresses_ TF_GUARDED_BY(mu_);
};
}
#endif
#include "tsl/platform/cloud/gcs_dns_cache.h"
#include <cstring>
#include "absl/status/status.h"
#include "absl/strings/str_cat.h"
#include "tsl/platform/errors.h"
#include "tsl/platform/retrying_utils.h"
#include "tsl/platform/status.h"
#ifndef _WIN32
#include <arpa/inet.h>
#include <netdb.h>
#include <netinet/in.h>
#include <sys/socket.h>
#else
#include <Windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#endif
#include <sys/types.h>
namespace tsl {
namespace {
const std::vector<string>& kCachedDomainNames =
*new std::vector<string>{"www.googleapis.com", "storage.googleapis.com"};
inline void print_getaddrinfo_error(const string& name, Status return_status) {
LOG(ERROR) << "Error resolving " << name << ": " << return_status;
}
template <typename T>
const T& SelectRandomItemUniform(std::default_random_engine* random,
const std::vector<T>& items) {
CHECK_GT(items.size(), 0);
std::uniform_int_distribution<size_t> distribution(0u, items.size() - 1u);
size_t choice_index = distribution(*random);
return items[choice_index];
}
}
GcsDnsCache::GcsDnsCache(Env* env, int64_t refresh_rate_secs)
: env_(env), refresh_rate_secs_(refresh_rate_secs) {}
void GcsDnsCache::AnnotateRequest(HttpRequest* request) {
mutex_lock l(mu_);
if (!started_) {
VLOG(1) << "Starting GCS DNS cache.";
DCHECK(!worker_) << "Worker thread already exists!";
addresses_ = ResolveNames(kCachedDomainNames);
worker_.reset(env_->StartThread({}, "gcs_dns_worker",
[this]() { return WorkerThread(); }));
started_ = true;
}
CHECK_EQ(kCachedDomainNames.size(), addresses_.size());
for (size_t i = 0; i < kCachedDomainNames.size(); ++i) {
const string& name = kCachedDomainNames[i];
const std::vector<string>& addresses = addresses_[i];
if (!addresses.empty()) {
const string& chosen_address =
SelectRandomItemUniform(&random_, addresses);
request->AddResolveOverride(name, 443, chosen_address);
VLOG(1) << "Annotated DNS mapping: " << name << " --> " << chosen_address;
} else {
LOG(WARNING) << "No IP addresses available for " << name;
}
}
}
std::vector<string> GcsDnsCache::ResolveName(const string& name) {
VLOG(1) << "Resolving DNS name: " << name;
addrinfo hints;
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
addrinfo* result = nullptr;
RetryConfig retryConfig(
5000,
50 * 1000 * 5000,
5);
const Status getaddrinfo_status = RetryingUtils::CallWithRetries(
[&name, &hints, &result]() {
int return_code = getaddrinfo(name.c_str(), nullptr, &hints, &result);
absl::Status return_status;
switch (return_code) {
case 0:
return_status = OkStatus();
break;
#ifndef _WIN32
case EAI_ADDRFAMILY:
case EAI_SERVICE:
case EAI_SOCKTYPE:
case EAI_NONAME:
return_status = absl::FailedPreconditionError(
absl::StrCat("System in invalid state for getaddrinfo call: ",
gai_strerror(return_code)));
break;
case EAI_AGAIN:
case EAI_NODATA:
return_status = absl::UnavailableError(absl::StrCat(
"Resolving ", name, " is temporarily unavailable"));
break;
case EAI_BADFLAGS:
case EAI_FAMILY:
return_status = absl::InvalidArgumentError(absl::StrCat(
"Bad arguments for getaddrinfo: ", gai_strerror(return_code)));
break;
case EAI_FAIL:
return_status = absl::NotFoundError(
absl::StrCat("Permanent failure resolving ", name, ": ",
gai_strerror(return_code)));
break;
case EAI_MEMORY:
return_status = absl::ResourceExhaustedError("Out of memory");
break;
case EAI_SYSTEM:
default:
return_status = absl::UnknownError(strerror(return_code));
#else
case WSATYPE_NOT_FOUND:
case WSAESOCKTNOSUPPORT:
case WSAHOST_NOT_FOUND:
return_status = absl::FailedPreconditionError(
absl::StrCat("System in invalid state for getaddrinfo call: ",
gai_strerror(return_code)));
break;
case WSATRY_AGAIN:
return_status = absl::UnavailableError(absl::StrCat(
"Resolving ", name, " is temporarily unavailable"));
break;
case WSAEINVAL:
case WSAEAFNOSUPPORT:
return_status = absl::InvalidArgumentError(absl::StrCat(
"Bad arguments for getaddrinfo: ", gai_strerror(return_code)));
break;
case WSANO_RECOVERY:
return_status = absl::NotFoundError(
absl::StrCat("Permanent failure resolving ", name, ": ",
gai_strerror(return_code)));
break;
case WSA_NOT_ENOUGH_MEMORY:
return_status = absl::ResourceExhaustedError("Out of memory");
break;
default:
return_status = absl::UnknownError(strerror(return_code));
#endif
}
return Status(return_status);
},
retryConfig);
std::vector<string> output;
if (getaddrinfo_status.ok()) {
for (const addrinfo* i = result; i != nullptr; i = i->ai_next) {
if (i->ai_family != AF_INET || i->ai_addr->sa_family != AF_INET) {
LOG(WARNING) << "Non-IPv4 address returned. ai_family: " << i->ai_family
<< ". sa_family: " << i->ai_addr->sa_family << ".";
continue;
}
char buf[INET_ADDRSTRLEN];
void* address_ptr =
&(reinterpret_cast<sockaddr_in*>(i->ai_addr)->sin_addr);
const char* formatted = nullptr;
if ((formatted = inet_ntop(i->ai_addr->sa_family, address_ptr, buf,
INET_ADDRSTRLEN)) == nullptr) {
LOG(ERROR) << "Error converting response to IP address for " << name
<< ": " << strerror(errno);
} else {
output.emplace_back(buf);
VLOG(1) << "... address: " << buf;
}
}
} else {
print_getaddrinfo_error(name, getaddrinfo_status);
}
if (result != nullptr) {
freeaddrinfo(result);
}
return output;
}
std::vector<std::vector<string>> GcsDnsCache::ResolveNames(
const std::vector<string>& names) {
std::vector<std::vector<string>> all_addresses;
all_addresses.reserve(names.size());
for (const string& name : names) {
all_addresses.push_back(ResolveName(name));
}
return all_addresses;
}
void GcsDnsCache::WorkerThread() {
while (true) {
{
mutex_lock l(mu_);
if (cancelled_) return;
cond_var_.wait_for(l, std::chrono::seconds(refresh_rate_secs_));
if (cancelled_) return;
}
auto new_addresses = ResolveNames(kCachedDomainNames);
{
mutex_lock l(mu_);
addresses_.swap(new_addresses);
}
}
}
} | #include "tsl/platform/cloud/gcs_dns_cache.h"
#include "tsl/platform/str_util.h"
#include "tsl/platform/test.h"
namespace tsl {
class TestHttpRequest : public HttpRequest {
public:
void SetUri(const string& uri) override {}
void SetRange(uint64 start, uint64 end) override {}
void AddHeader(const string& name, const string& value) override {}
void AddResolveOverride(const string& hostname, int64_t port,
const string& ip_addr) override {
EXPECT_EQ(port, 443) << "Unexpected port set for hostname: " << hostname;
auto itr = resolve_overrides_.find(hostname);
EXPECT_EQ(itr, resolve_overrides_.end())
<< "Hostname " << hostname << "already in map: " << itr->second;
resolve_overrides_.insert(
std::map<string, string>::value_type(hostname, ip_addr));
}
void AddAuthBearerHeader(const string& auth_token) override {}
void SetRequestStats(HttpRequest::RequestStats* stats) override {}
void SetDeleteRequest() override {}
Status SetPutFromFile(const string& body_filepath, size_t offset) override {
return OkStatus();
}
void SetPutEmptyBody() override {}
void SetPostFromBuffer(const char* buffer, size_t size) override {}
void SetPostEmptyBody() override {}
void SetResultBuffer(std::vector<char>* out_buffer) override {}
void SetResultBufferDirect(char* buffer, size_t size) override {}
size_t GetResultBufferDirectBytesTransferred() override { return 0; }
string GetResponseHeader(const string& name) const override { return ""; }
uint64 GetResponseCode() const override { return 0; }
Status Send() override { return OkStatus(); }
string EscapeString(const string& str) override { return ""; }
void SetTimeouts(uint32 connection, uint32 inactivity,
uint32 total) override {}
std::map<string, string> resolve_overrides_;
};
class GcsDnsCacheTest : public ::testing::Test {
protected:
void ResolveNameTest() {
auto response = GcsDnsCache::ResolveName("www.googleapis.com");
EXPECT_LT(1, response.size()) << absl::StrJoin(response, ", ");
}
void AnnotateRequestTest() {
GcsDnsCache d;
{
mutex_lock l(d.mu_);
d.started_ = true;
d.addresses_ = {{"192.168.1.1"}, {"172.134.1.1"}};
}
TestHttpRequest req;
d.AnnotateRequest(&req);
EXPECT_EQ("192.168.1.1", req.resolve_overrides_["www.googleapis.com"]);
EXPECT_EQ("172.134.1.1", req.resolve_overrides_["storage.googleapis.com"]);
}
void SuccessfulCleanupTest() {
GcsDnsCache d;
TestHttpRequest req;
d.AnnotateRequest(&req);
}
};
TEST_F(GcsDnsCacheTest, AnnotateRequest) { AnnotateRequestTest(); }
TEST_F(GcsDnsCacheTest, SuccessfulCleanup) { SuccessfulCleanupTest(); }
} | 2,280 |
#ifndef TENSORFLOW_TSL_PLATFORM_CLOUD_COMPUTE_ENGINE_METADATA_CLIENT_H_
#define TENSORFLOW_TSL_PLATFORM_CLOUD_COMPUTE_ENGINE_METADATA_CLIENT_H_
#include "tsl/platform/cloud/http_request.h"
#include "tsl/platform/retrying_utils.h"
#include "tsl/platform/status.h"
namespace tsl {
class ComputeEngineMetadataClient {
public:
explicit ComputeEngineMetadataClient(
std::shared_ptr<HttpRequest::Factory> http_request_factory,
const RetryConfig& config = RetryConfig(
10000,
1000000
));
virtual ~ComputeEngineMetadataClient() {}
virtual Status GetMetadata(const string& path,
std::vector<char>* response_buffer);
private:
std::shared_ptr<HttpRequest::Factory> http_request_factory_;
const RetryConfig retry_config_;
ComputeEngineMetadataClient(const ComputeEngineMetadataClient&) = delete;
void operator=(const ComputeEngineMetadataClient&) = delete;
};
}
#endif
#include "tsl/platform/cloud/compute_engine_metadata_client.h"
#include <cstdlib>
#include <utility>
#include "absl/strings/str_cat.h"
#include "tsl/platform/cloud/curl_http_request.h"
namespace tsl {
namespace {
constexpr char kGceMetadataHost[] = "GCE_METADATA_HOST";
constexpr char kGceMetadataBaseUrl[] =
"http:
}
ComputeEngineMetadataClient::ComputeEngineMetadataClient(
std::shared_ptr<HttpRequest::Factory> http_request_factory,
const RetryConfig& config)
: http_request_factory_(std::move(http_request_factory)),
retry_config_(config) {}
Status ComputeEngineMetadataClient::GetMetadata(
const string& path, std::vector<char>* response_buffer) {
const auto get_metadata_from_gce = [path, response_buffer, this]() {
string metadata_url;
const char* metadata_url_override = std::getenv(kGceMetadataHost);
if (metadata_url_override) {
metadata_url = absl::StrCat("http:
"/computeMetadata/v1/");
} else {
metadata_url = kGceMetadataBaseUrl;
}
std::unique_ptr<HttpRequest> request(http_request_factory_->Create());
request->SetUri(metadata_url + path);
request->AddHeader("Metadata-Flavor", "Google");
request->SetResultBuffer(response_buffer);
TF_RETURN_IF_ERROR(request->Send());
return OkStatus();
};
return RetryingUtils::CallWithRetries(get_metadata_from_gce, retry_config_);
}
} | #include "tsl/platform/cloud/compute_engine_metadata_client.h"
#include "tsl/platform/cloud/http_request_fake.h"
#include "tsl/platform/env.h"
#include "tsl/platform/test.h"
namespace tsl {
class ComputeEngineMetadataClientTest : public ::testing::Test {
protected:
void SetUp() override { ClearEnvVars(); }
void TearDown() override { ClearEnvVars(); }
void ClearEnvVars() { unsetenv("GCE_METADATA_HOST"); }
};
TEST_F(ComputeEngineMetadataClientTest, GetMetadata) {
const string example_response = "example response";
std::vector<HttpRequest*> requests({new FakeHttpRequest(
"Uri: http:
"/service-accounts/default/token\n"
"Header Metadata-Flavor: Google\n",
example_response)});
std::shared_ptr<HttpRequest::Factory> http_factory =
std::make_shared<FakeHttpRequestFactory>(&requests);
ComputeEngineMetadataClient client(http_factory,
RetryConfig(0 ));
std::vector<char> result;
TF_EXPECT_OK(
client.GetMetadata("instance/service-accounts/default/token", &result));
std::vector<char> expected(example_response.begin(), example_response.end());
EXPECT_EQ(expected, result);
}
TEST_F(ComputeEngineMetadataClientTest, GetCustomMetadataEndpoint) {
const string example_response = "example response";
setenv("GCE_METADATA_HOST", "foo.bar", 1);
std::vector<HttpRequest*> requests(
{new FakeHttpRequest("Uri: http:
"/service-accounts/default/token\n"
"Header Metadata-Flavor: Google\n",
example_response)});
std::shared_ptr<HttpRequest::Factory> http_factory =
std::make_shared<FakeHttpRequestFactory>(&requests);
ComputeEngineMetadataClient client(http_factory,
RetryConfig(0 ));
std::vector<char> result;
TF_EXPECT_OK(
client.GetMetadata("instance/service-accounts/default/token", &result));
std::vector<char> expected(example_response.begin(), example_response.end());
EXPECT_EQ(expected, result);
}
TEST_F(ComputeEngineMetadataClientTest, RetryOnFailure) {
const string example_response = "example response";
std::vector<HttpRequest*> requests(
{new FakeHttpRequest(
"Uri: http:
"/service-accounts/default/token\n"
"Header Metadata-Flavor: Google\n",
"", errors::Unavailable("503"), 503),
new FakeHttpRequest(
"Uri: http:
"/service-accounts/default/token\n"
"Header Metadata-Flavor: Google\n",
example_response)});
std::shared_ptr<HttpRequest::Factory> http_factory =
std::make_shared<FakeHttpRequestFactory>(&requests);
ComputeEngineMetadataClient client(http_factory,
RetryConfig(0 ));
std::vector<char> result;
TF_EXPECT_OK(
client.GetMetadata("instance/service-accounts/default/token", &result));
std::vector<char> expected(example_response.begin(), example_response.end());
EXPECT_EQ(expected, result);
}
} | 2,281 |
#ifndef TENSORFLOW_TSL_PLATFORM_CLOUD_OAUTH_CLIENT_H_
#define TENSORFLOW_TSL_PLATFORM_CLOUD_OAUTH_CLIENT_H_
#include <memory>
#include "json/json.h"
#include "tsl/platform/cloud/http_request.h"
#include "tsl/platform/env.h"
#include "tsl/platform/status.h"
namespace tsl {
class OAuthClient {
public:
OAuthClient();
explicit OAuthClient(
std::unique_ptr<HttpRequest::Factory> http_request_factory, Env* env);
virtual ~OAuthClient() {}
virtual Status GetTokenFromServiceAccountJson(
Json::Value json, StringPiece oauth_server_uri, StringPiece scope,
string* token, uint64* expiration_timestamp_sec);
virtual Status GetTokenFromRefreshTokenJson(Json::Value json,
StringPiece oauth_server_uri,
string* token,
uint64* expiration_timestamp_sec);
virtual Status ParseOAuthResponse(StringPiece response,
uint64 request_timestamp_sec, string* token,
uint64* expiration_timestamp_sec);
private:
std::unique_ptr<HttpRequest::Factory> http_request_factory_;
Env* env_;
OAuthClient(const OAuthClient&) = delete;
void operator=(const OAuthClient&) = delete;
};
}
#endif
#include "tsl/platform/cloud/oauth_client.h"
#ifndef _WIN32
#include <pwd.h>
#include <sys/types.h>
#include <unistd.h>
#else
#include <sys/types.h>
#endif
#include <fstream>
#include <openssl/bio.h>
#include <openssl/evp.h>
#include <openssl/pem.h>
#include <openssl/rsa.h>
#include "tsl/platform/base64.h"
#include "tsl/platform/cloud/curl_http_request.h"
#include "tsl/platform/env.h"
#include "tsl/platform/errors.h"
namespace tsl {
namespace {
constexpr int kRequestedTokenLifetimeSec = 3600;
constexpr char kCryptoAlgorithm[] = "RS256";
constexpr char kJwtType[] = "JWT";
constexpr char kGrantType[] =
"urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer";
Status ReadJsonValue(const Json::Value& json, const string& name,
Json::Value* value) {
if (!value) {
return errors::FailedPrecondition("'value' cannot be nullptr.");
}
*value = json.get(name, Json::Value::null);
if (*value == Json::Value::null) {
return errors::FailedPrecondition(
strings::StrCat("Couldn't read a JSON value '", name, "'."));
}
return OkStatus();
}
Status ReadJsonString(const Json::Value& json, const string& name,
string* value) {
Json::Value json_value;
TF_RETURN_IF_ERROR(ReadJsonValue(json, name, &json_value));
if (!json_value.isString()) {
return errors::FailedPrecondition(
strings::StrCat("JSON value '", name, "' is not string."));
}
*value = json_value.asString();
return OkStatus();
}
Status ReadJsonInt(const Json::Value& json, const string& name,
int64_t* value) {
Json::Value json_value;
TF_RETURN_IF_ERROR(ReadJsonValue(json, name, &json_value));
if (!json_value.isIntegral()) {
return errors::FailedPrecondition(
strings::StrCat("JSON value '", name, "' is not integer."));
}
*value = json_value.asInt64();
return OkStatus();
}
Status CreateSignature(RSA* private_key, StringPiece to_sign,
string* signature) {
if (!private_key || !signature) {
return errors::FailedPrecondition(
"'private_key' and 'signature' cannot be nullptr.");
}
const auto md = EVP_sha256();
if (!md) {
return errors::Internal("Could not get a sha256 encryptor.");
}
std::unique_ptr<EVP_MD_CTX, std::function<void(EVP_MD_CTX*)>> md_ctx(
EVP_MD_CTX_create(), [](EVP_MD_CTX* ptr) { EVP_MD_CTX_destroy(ptr); });
if (!md_ctx) {
return errors::Internal("Could not create MD_CTX.");
}
std::unique_ptr<EVP_PKEY, std::function<void(EVP_PKEY*)>> key(
EVP_PKEY_new(), [](EVP_PKEY* ptr) { EVP_PKEY_free(ptr); });
EVP_PKEY_set1_RSA(key.get(), private_key);
if (EVP_DigestSignInit(md_ctx.get(), nullptr, md, nullptr, key.get()) != 1) {
return errors::Internal("DigestInit failed.");
}
if (EVP_DigestSignUpdate(md_ctx.get(), to_sign.data(), to_sign.size()) != 1) {
return errors::Internal("DigestUpdate failed.");
}
size_t sig_len = 0;
if (EVP_DigestSignFinal(md_ctx.get(), nullptr, &sig_len) != 1) {
return errors::Internal("DigestFinal (get signature length) failed.");
}
std::unique_ptr<unsigned char[]> sig(new unsigned char[sig_len]);
if (EVP_DigestSignFinal(md_ctx.get(), sig.get(), &sig_len) != 1) {
return errors::Internal("DigestFinal (signature compute) failed.");
}
return Base64Encode(StringPiece(reinterpret_cast<char*>(sig.get()), sig_len),
signature);
}
Status EncodeJwtClaim(StringPiece client_email, StringPiece scope,
StringPiece audience, uint64 request_timestamp_sec,
string* encoded) {
Json::Value root;
root["iss"] = Json::Value(client_email.data(),
client_email.data() + client_email.size());
root["scope"] = Json::Value(scope.data(), scope.data() + scope.size());
root["aud"] = Json::Value(audience.data(), audience.data() + audience.size());
const auto expiration_timestamp_sec =
request_timestamp_sec + kRequestedTokenLifetimeSec;
root["iat"] = Json::Value::UInt64(request_timestamp_sec);
root["exp"] = Json::Value::UInt64(expiration_timestamp_sec);
string claim = root.toStyledString();
return Base64Encode(claim, encoded);
}
Status EncodeJwtHeader(StringPiece key_id, string* encoded) {
Json::Value root;
root["alg"] = kCryptoAlgorithm;
root["typ"] = kJwtType;
root["kid"] = Json::Value(key_id.data(), key_id.data() + key_id.size());
const string header = root.toStyledString();
return Base64Encode(header, encoded);
}
}
OAuthClient::OAuthClient()
: OAuthClient(
std::unique_ptr<HttpRequest::Factory>(new CurlHttpRequest::Factory()),
Env::Default()) {}
OAuthClient::OAuthClient(
std::unique_ptr<HttpRequest::Factory> http_request_factory, Env* env)
: http_request_factory_(std::move(http_request_factory)), env_(env) {}
Status OAuthClient::GetTokenFromServiceAccountJson(
Json::Value json, StringPiece oauth_server_uri, StringPiece scope,
string* token, uint64* expiration_timestamp_sec) {
if (!token || !expiration_timestamp_sec) {
return errors::FailedPrecondition(
"'token' and 'expiration_timestamp_sec' cannot be nullptr.");
}
string private_key_serialized, private_key_id, client_id, client_email;
TF_RETURN_IF_ERROR(
ReadJsonString(json, "private_key", &private_key_serialized));
TF_RETURN_IF_ERROR(ReadJsonString(json, "private_key_id", &private_key_id));
TF_RETURN_IF_ERROR(ReadJsonString(json, "client_id", &client_id));
TF_RETURN_IF_ERROR(ReadJsonString(json, "client_email", &client_email));
std::unique_ptr<BIO, std::function<void(BIO*)>> bio(
BIO_new(BIO_s_mem()), [](BIO* ptr) { BIO_free_all(ptr); });
if (BIO_puts(bio.get(), private_key_serialized.c_str()) !=
static_cast<int>(private_key_serialized.size())) {
return errors::Internal("Could not load the private key.");
}
std::unique_ptr<RSA, std::function<void(RSA*)>> private_key(
PEM_read_bio_RSAPrivateKey(bio.get(), nullptr, nullptr, nullptr),
[](RSA* ptr) { RSA_free(ptr); });
if (!private_key) {
return errors::Internal("Could not deserialize the private key.");
}
const uint64 request_timestamp_sec = env_->NowSeconds();
string encoded_claim, encoded_header;
TF_RETURN_IF_ERROR(EncodeJwtHeader(private_key_id, &encoded_header));
TF_RETURN_IF_ERROR(EncodeJwtClaim(client_email, scope, oauth_server_uri,
request_timestamp_sec, &encoded_claim));
const string to_sign = encoded_header + "." + encoded_claim;
string signature;
TF_RETURN_IF_ERROR(CreateSignature(private_key.get(), to_sign, &signature));
const string jwt = to_sign + "." + signature;
const string request_body =
strings::StrCat("grant_type=", kGrantType, "&assertion=", jwt);
std::unique_ptr<HttpRequest> request(http_request_factory_->Create());
std::vector<char> response_buffer;
request->SetUri(string(oauth_server_uri));
request->SetPostFromBuffer(request_body.c_str(), request_body.size());
request->SetResultBuffer(&response_buffer);
TF_RETURN_IF_ERROR(request->Send());
StringPiece response =
StringPiece(response_buffer.data(), response_buffer.size());
TF_RETURN_IF_ERROR(ParseOAuthResponse(response, request_timestamp_sec, token,
expiration_timestamp_sec));
return OkStatus();
}
Status OAuthClient::GetTokenFromRefreshTokenJson(
Json::Value json, StringPiece oauth_server_uri, string* token,
uint64* expiration_timestamp_sec) {
if (!token || !expiration_timestamp_sec) {
return errors::FailedPrecondition(
"'token' and 'expiration_timestamp_sec' cannot be nullptr.");
}
string client_id, client_secret, refresh_token;
TF_RETURN_IF_ERROR(ReadJsonString(json, "client_id", &client_id));
TF_RETURN_IF_ERROR(ReadJsonString(json, "client_secret", &client_secret));
TF_RETURN_IF_ERROR(ReadJsonString(json, "refresh_token", &refresh_token));
const auto request_body = strings::StrCat(
"client_id=", client_id, "&client_secret=", client_secret,
"&refresh_token=", refresh_token, "&grant_type=refresh_token");
const uint64 request_timestamp_sec = env_->NowSeconds();
std::unique_ptr<HttpRequest> request(http_request_factory_->Create());
std::vector<char> response_buffer;
request->SetUri(string(oauth_server_uri));
request->SetPostFromBuffer(request_body.c_str(), request_body.size());
request->SetResultBuffer(&response_buffer);
TF_RETURN_IF_ERROR(request->Send());
StringPiece response =
StringPiece(response_buffer.data(), response_buffer.size());
TF_RETURN_IF_ERROR(ParseOAuthResponse(response, request_timestamp_sec, token,
expiration_timestamp_sec));
return OkStatus();
}
Status OAuthClient::ParseOAuthResponse(StringPiece response,
uint64 request_timestamp_sec,
string* token,
uint64* expiration_timestamp_sec) {
if (!token || !expiration_timestamp_sec) {
return errors::FailedPrecondition(
"'token' and 'expiration_timestamp_sec' cannot be nullptr.");
}
Json::Value root;
Json::Reader reader;
if (!reader.parse(response.data(), response.data() + response.size(), root)) {
return errors::Internal("Couldn't parse JSON response from OAuth server.");
}
string token_type;
TF_RETURN_IF_ERROR(ReadJsonString(root, "token_type", &token_type));
if (token_type != "Bearer") {
return errors::FailedPrecondition("Unexpected Oauth token type: " +
token_type);
}
int64_t expires_in = 0;
TF_RETURN_IF_ERROR(ReadJsonInt(root, "expires_in", &expires_in));
*expiration_timestamp_sec = request_timestamp_sec + expires_in;
TF_RETURN_IF_ERROR(ReadJsonString(root, "access_token", token));
return OkStatus();
}
} | #include "tsl/platform/cloud/oauth_client.h"
#include <fstream>
#include <openssl/bio.h>
#include <openssl/evp.h>
#include <openssl/pem.h>
#include "tsl/lib/core/status_test_util.h"
#include "tsl/platform/base64.h"
#include "tsl/platform/cloud/http_request_fake.h"
#include "tsl/platform/env.h"
#include "tsl/platform/path.h"
#include "tsl/platform/scanner.h"
#include "tsl/platform/test.h"
namespace tsl {
namespace {
string TestData() {
return io::JoinPath(testing::TslSrcRoot(), "platform", "cloud", "testdata");
}
constexpr char kTokenJson[] = R"(
{
"access_token":"WITH_FAKE_ACCESS_TOKEN_TEST_SHOULD_BE_HAPPY",
"expires_in":3920,
"token_type":"Bearer"
})";
class FakeEnv : public EnvWrapper {
public:
FakeEnv() : EnvWrapper(Env::Default()) {}
uint64 NowSeconds() const override { return now; }
uint64 now = 10000;
};
}
TEST(OAuthClientTest, ParseOAuthResponse) {
const uint64 request_timestamp = 100;
string token;
uint64 expiration_timestamp;
TF_EXPECT_OK(OAuthClient().ParseOAuthResponse(kTokenJson, request_timestamp,
&token, &expiration_timestamp));
EXPECT_EQ("WITH_FAKE_ACCESS_TOKEN_TEST_SHOULD_BE_HAPPY", token);
EXPECT_EQ(4020, expiration_timestamp);
}
TEST(OAuthClientTest, GetTokenFromRefreshTokenJson) {
const string credentials_json = R"(
{
"client_id": "test_client_id",
"client_secret": "@@@test_client_secret@@@",
"refresh_token": "test_refresh_token",
"type": "authorized_user"
})";
Json::Value json;
Json::Reader reader;
ASSERT_TRUE(reader.parse(credentials_json, json));
std::vector<HttpRequest*> requests({new FakeHttpRequest(
"Uri: https:
"Post body: client_id=test_client_id&"
"client_secret=@@@test_client_secret@@@&"
"refresh_token=test_refresh_token&grant_type=refresh_token\n",
kTokenJson)});
FakeEnv env;
OAuthClient client(std::unique_ptr<HttpRequest::Factory>(
new FakeHttpRequestFactory(&requests)),
&env);
string token;
uint64 expiration_timestamp;
TF_EXPECT_OK(client.GetTokenFromRefreshTokenJson(
json, "https:
&expiration_timestamp));
EXPECT_EQ("WITH_FAKE_ACCESS_TOKEN_TEST_SHOULD_BE_HAPPY", token);
EXPECT_EQ(13920, expiration_timestamp);
}
TEST(OAuthClientTest, GetTokenFromServiceAccountJson) {
std::ifstream credentials(
io::JoinPath(TestData(), "service_account_credentials.json"));
ASSERT_TRUE(credentials.is_open());
Json::Value json;
Json::Reader reader;
ASSERT_TRUE(reader.parse(credentials, json));
string post_body;
std::vector<HttpRequest*> requests(
{new FakeHttpRequest("Uri: https:
kTokenJson, &post_body)});
FakeEnv env;
OAuthClient client(std::unique_ptr<HttpRequest::Factory>(
new FakeHttpRequestFactory(&requests)),
&env);
string token;
uint64 expiration_timestamp;
TF_EXPECT_OK(client.GetTokenFromServiceAccountJson(
json, "https:
"https:
EXPECT_EQ("WITH_FAKE_ACCESS_TOKEN_TEST_SHOULD_BE_HAPPY", token);
EXPECT_EQ(13920, expiration_timestamp);
StringPiece grant_type, assertion;
ASSERT_TRUE(strings::Scanner(post_body)
.OneLiteral("grant_type=")
.RestartCapture()
.ScanEscapedUntil('&')
.StopCapture()
.OneLiteral("&assertion=")
.GetResult(&assertion, &grant_type));
EXPECT_EQ("urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer",
grant_type);
int last_dot = assertion.rfind('.');
string header_dot_claim(assertion.substr(0, last_dot));
string signature_encoded(assertion.substr(last_dot + 1));
std::ifstream public_key_stream(
io::JoinPath(TestData(), "service_account_public_key.txt"));
string public_key_serialized(
(std::istreambuf_iterator<char>(public_key_stream)),
(std::istreambuf_iterator<char>()));
auto bio = BIO_new(BIO_s_mem());
RSA* public_key = nullptr;
EXPECT_EQ(public_key_serialized.size(),
BIO_puts(bio, public_key_serialized.c_str()));
public_key = PEM_read_bio_RSA_PUBKEY(bio, nullptr, nullptr, nullptr);
EXPECT_TRUE(public_key) << "Could not load the public key from testdata.";
string signature;
TF_EXPECT_OK(Base64Decode(signature_encoded, &signature));
const auto md = EVP_sha256();
auto md_ctx = EVP_MD_CTX_create();
auto key = EVP_PKEY_new();
EVP_PKEY_set1_RSA(key, public_key);
ASSERT_EQ(1, EVP_DigestVerifyInit(md_ctx, nullptr, md, nullptr, key));
ASSERT_EQ(1, EVP_DigestVerifyUpdate(md_ctx, header_dot_claim.c_str(),
header_dot_claim.size()));
ASSERT_EQ(1,
EVP_DigestVerifyFinal(
md_ctx,
const_cast<unsigned char*>(
reinterpret_cast<const unsigned char*>(signature.data())),
signature.size()));
EVP_PKEY_free(key);
EVP_MD_CTX_destroy(md_ctx);
RSA_free(public_key);
BIO_free_all(bio);
int dot = header_dot_claim.find_last_of('.');
string header_encoded = header_dot_claim.substr(0, dot);
string claim_encoded = header_dot_claim.substr(dot + 1);
string header, claim;
TF_EXPECT_OK(Base64Decode(header_encoded, &header));
TF_EXPECT_OK(Base64Decode(claim_encoded, &claim));
Json::Value header_json, claim_json;
EXPECT_TRUE(reader.parse(header, header_json));
EXPECT_EQ("RS256", header_json.get("alg", Json::Value::null).asString());
EXPECT_EQ("JWT", header_json.get("typ", Json::Value::null).asString());
EXPECT_EQ("fake_key_id",
header_json.get("kid", Json::Value::null).asString());
EXPECT_TRUE(reader.parse(claim, claim_json));
EXPECT_EQ("fake-test-project.iam.gserviceaccount.com",
claim_json.get("iss", Json::Value::null).asString());
EXPECT_EQ("https:
claim_json.get("scope", Json::Value::null).asString());
EXPECT_EQ("https:
claim_json.get("aud", Json::Value::null).asString());
EXPECT_EQ(10000, claim_json.get("iat", Json::Value::null).asInt64());
EXPECT_EQ(13600, claim_json.get("exp", Json::Value::null).asInt64());
}
} | 2,282 |
#ifndef TENSORFLOW_TSL_PLATFORM_CLOUD_COMPUTE_ENGINE_ZONE_PROVIDER_H_
#define TENSORFLOW_TSL_PLATFORM_CLOUD_COMPUTE_ENGINE_ZONE_PROVIDER_H_
#include "tsl/platform/cloud/compute_engine_metadata_client.h"
#include "tsl/platform/cloud/zone_provider.h"
namespace tsl {
class ComputeEngineZoneProvider : public ZoneProvider {
public:
explicit ComputeEngineZoneProvider(
std::shared_ptr<ComputeEngineMetadataClient> google_metadata_client);
virtual ~ComputeEngineZoneProvider();
Status GetZone(string* zone) override;
private:
std::shared_ptr<ComputeEngineMetadataClient> google_metadata_client_;
string cached_zone;
ComputeEngineZoneProvider(const ComputeEngineZoneProvider&) = delete;
void operator=(const ComputeEngineZoneProvider&) = delete;
};
}
#endif
#include "tsl/platform/cloud/compute_engine_zone_provider.h"
#include <utility>
#include "tsl/platform/str_util.h"
namespace tsl {
namespace {
constexpr char kGceMetadataZonePath[] = "instance/zone";
}
ComputeEngineZoneProvider::ComputeEngineZoneProvider(
std::shared_ptr<ComputeEngineMetadataClient> google_metadata_client)
: google_metadata_client_(std::move(google_metadata_client)) {}
Status ComputeEngineZoneProvider::GetZone(string* zone) {
if (!cached_zone.empty()) {
*zone = cached_zone;
return OkStatus();
}
std::vector<char> response_buffer;
TF_RETURN_IF_ERROR(google_metadata_client_->GetMetadata(kGceMetadataZonePath,
&response_buffer));
StringPiece location(&response_buffer[0], response_buffer.size());
std::vector<string> elems = str_util::Split(location, "/");
if (elems.size() == 4) {
cached_zone = elems.back();
*zone = cached_zone;
} else {
LOG(ERROR) << "Failed to parse the zone name from location: "
<< string(location);
}
return OkStatus();
}
ComputeEngineZoneProvider::~ComputeEngineZoneProvider() {}
} | #include "tsl/platform/cloud/compute_engine_zone_provider.h"
#include "tsl/platform/cloud/http_request_fake.h"
#include "tsl/platform/test.h"
namespace tsl {
class ComputeEngineZoneProviderTest : public ::testing::Test {
protected:
void SetUp() override {}
void TearDown() override {}
};
TEST_F(ComputeEngineZoneProviderTest, GetZone) {
std::vector<HttpRequest*> requests({new FakeHttpRequest(
"Uri: http:
"Header Metadata-Flavor: Google\n",
"projects/123456789/zones/us-west1-b")});
auto httpRequestFactory = std::make_shared<FakeHttpRequestFactory>(&requests);
auto metadata_client = std::make_shared<ComputeEngineMetadataClient>(
httpRequestFactory, RetryConfig(0 ));
ComputeEngineZoneProvider provider(metadata_client);
string zone;
TF_EXPECT_OK(provider.GetZone(&zone));
EXPECT_EQ("us-west1-b", zone);
TF_EXPECT_OK(provider.GetZone(&zone));
}
TEST_F(ComputeEngineZoneProviderTest, InvalidZoneString) {
std::vector<HttpRequest*> requests({new FakeHttpRequest(
"Uri: http:
"Header Metadata-Flavor: Google\n",
"invalidresponse")});
auto httpRequestFactory = std::make_shared<FakeHttpRequestFactory>(&requests);
auto metadata_client = std::make_shared<ComputeEngineMetadataClient>(
httpRequestFactory, RetryConfig(0 ));
ComputeEngineZoneProvider provider(metadata_client);
string zone;
TF_EXPECT_OK(provider.GetZone(&zone));
EXPECT_EQ("", zone);
}
} | 2,283 |
#ifndef TENSORFLOW_TSL_PLATFORM_PROFILE_UTILS_CPU_UTILS_H_
#define TENSORFLOW_TSL_PLATFORM_PROFILE_UTILS_CPU_UTILS_H_
#include <chrono>
#include <memory>
#include "tsl/platform/macros.h"
#include "tsl/platform/profile_utils/i_cpu_utils_helper.h"
#include "tsl/platform/types.h"
#if defined(ARMV6) || defined(__ARM_ARCH_7A__)
#include <sys/time.h>
#endif
#if defined(_WIN32)
#include <intrin.h>
#endif
namespace tsl {
namespace profile_utils {
class CpuUtils {
public:
static constexpr int64_t INVALID_FREQUENCY = -1;
static constexpr uint64 DUMMY_CYCLE_CLOCK = 1;
static inline uint64 GetCurrentClockCycle() {
#if defined(__ANDROID__)
return GetCpuUtilsHelperSingletonInstance().GetCurrentClockCycle();
#elif defined(_WIN32)
return __rdtsc();
#elif defined(__x86_64__) || defined(__amd64__)
uint64_t high, low;
__asm__ volatile("rdtsc" : "=a"(low), "=d"(high));
return (high << 32) | low;
#elif defined(__aarch64__)
uint64_t virtual_timer_value;
asm volatile("mrs %0, cntvct_el0" : "=r"(virtual_timer_value));
return virtual_timer_value;
#elif defined(ARMV6) || defined(__ARM_ARCH_7A__)
uint32_t pmccntr;
uint32_t pmuseren;
uint32_t pmcntenset;
asm volatile("mrc p15, 0, %0, c9, c14, 0" : "=r"(pmuseren));
if (pmuseren & 1) {
asm volatile("mrc p15, 0, %0, c9, c12, 1" : "=r"(pmcntenset));
if (pmcntenset & 0x80000000ul) {
asm volatile("mrc p15, 0, %0, c9, c13, 0" : "=r"(pmccntr));
return static_cast<uint64>(pmccntr) * 64;
}
}
return DUMMY_CYCLE_CLOCK;
#elif defined(__powerpc64__) || defined(__ppc64__)
uint64 __t;
__asm__ __volatile__("mfspr %0,268" : "=r"(__t));
return __t;
#elif defined(__powerpc__) || defined(__ppc__)
uint64 upper, lower, tmp;
__asm__ volatile(
"0: \n"
"\tmftbu %0 \n"
"\tmftb %1 \n"
"\tmftbu %2 \n"
"\tcmpw %2,%0 \n"
"\tbne 0b \n"
: "=r"(upper), "=r"(lower), "=r"(tmp));
return ((static_cast<uint64>(upper) << 32) | lower);
#elif defined(__s390x__)
uint64 t;
__asm__ __volatile__("stckf %0" : "=Q"(t));
return t;
#else
return DUMMY_CYCLE_CLOCK;
#endif
}
#if (defined(__powerpc__) || \
defined(__ppc__) && (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__)) || \
(defined(__s390x__))
static uint64 GetCycleCounterFrequency();
#else
static int64_t GetCycleCounterFrequency();
#endif
static double GetMicroSecPerClock();
static void ResetClockCycle();
static void EnableClockCycleProfiling();
static void DisableClockCycleProfiling();
static std::chrono::duration<double> ConvertClockCycleToTime(
const int64_t clock_cycle);
private:
class DefaultCpuUtilsHelper : public ICpuUtilsHelper {
public:
DefaultCpuUtilsHelper() = default;
void ResetClockCycle() final {}
uint64 GetCurrentClockCycle() final { return DUMMY_CYCLE_CLOCK; }
void EnableClockCycleProfiling() final {}
void DisableClockCycleProfiling() final {}
int64_t CalculateCpuFrequency() final { return INVALID_FREQUENCY; }
private:
DefaultCpuUtilsHelper(const DefaultCpuUtilsHelper&) = delete;
void operator=(const DefaultCpuUtilsHelper&) = delete;
};
static int64_t GetCycleCounterFrequencyImpl();
static ICpuUtilsHelper& GetCpuUtilsHelperSingletonInstance();
CpuUtils(const CpuUtils&) = delete;
void operator=(const CpuUtils&) = delete;
};
}
}
#endif
#include "tsl/platform/profile_utils/cpu_utils.h"
#include <fstream>
#include <limits>
#include <mutex>
#if defined(_WIN32)
#include <windows.h>
#endif
#if defined(__APPLE__)
#include <sys/sysctl.h>
#endif
#include "absl/base/call_once.h"
#include "tsl/platform/logging.h"
#include "tsl/platform/profile_utils/android_armv7a_cpu_utils_helper.h"
namespace tsl {
namespace profile_utils {
constexpr int64_t CpuUtils::INVALID_FREQUENCY;
static ICpuUtilsHelper* cpu_utils_helper_instance_ = nullptr;
#if (defined(__powerpc__) || \
defined(__ppc__) && (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__)) || \
(defined(__s390x__))
uint64 CpuUtils::GetCycleCounterFrequency() {
static const uint64 cpu_frequency = GetCycleCounterFrequencyImpl();
return cpu_frequency;
}
#else
int64_t CpuUtils::GetCycleCounterFrequency() {
static const int64_t cpu_frequency = GetCycleCounterFrequencyImpl();
return cpu_frequency;
}
#endif
double CpuUtils::GetMicroSecPerClock() {
static const double micro_sec_per_clock =
(1000.0 * 1000.0) / static_cast<double>(GetCycleCounterFrequency());
return micro_sec_per_clock;
}
void CpuUtils::ResetClockCycle() {
GetCpuUtilsHelperSingletonInstance().ResetClockCycle();
}
void CpuUtils::EnableClockCycleProfiling() {
GetCpuUtilsHelperSingletonInstance().EnableClockCycleProfiling();
}
void CpuUtils::DisableClockCycleProfiling() {
GetCpuUtilsHelperSingletonInstance().DisableClockCycleProfiling();
}
std::chrono::duration<double> CpuUtils::ConvertClockCycleToTime(
const int64_t clock_cycle) {
return std::chrono::duration<double>(static_cast<double>(clock_cycle) /
GetCycleCounterFrequency());
}
int64_t CpuUtils::GetCycleCounterFrequencyImpl() {
#if defined(__ANDROID__)
return GetCpuUtilsHelperSingletonInstance().CalculateCpuFrequency();
#elif defined(__linux__)
std::ifstream cpuinfo("/proc/cpuinfo");
if (!cpuinfo) {
LOG(WARNING) << "Failed to open /proc/cpuinfo";
return INVALID_FREQUENCY;
}
string line;
while (std::getline(cpuinfo, line)) {
double cpu_freq = 0.0;
int retval = 0;
double freq_factor = 2.0;
#if (defined(__powerpc__) || \
defined(__ppc__) && (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__))
retval = sscanf(line.c_str(), "clock : %lfMHz", &cpu_freq);
freq_factor = 1.0;
#elif defined(__s390x__)
retval = sscanf(line.c_str(), "bogomips per cpu: %lf", &cpu_freq);
#elif defined(__aarch64__)
retval = sscanf(line.c_str(), "BogoMIPS : %lf", &cpu_freq);
#else
retval = sscanf(line.c_str(), "bogomips : %lf", &cpu_freq);
#endif
if (retval > 0) {
const double freq_ghz = cpu_freq / 1000.0 / freq_factor;
if (retval != 1 || freq_ghz < 0.01) {
LOG(WARNING) << "Failed to get CPU frequency: " << freq_ghz << " GHz";
return INVALID_FREQUENCY;
}
const int64_t freq_n =
static_cast<int64_t>(freq_ghz * 1000.0 * 1000.0 * 1000.0);
VLOG(1) << "CPU Frequency: " << freq_n << " Hz";
return freq_n;
}
}
LOG(WARNING)
<< "Failed to find bogomips or clock in /proc/cpuinfo; cannot determine "
"CPU frequency";
return INVALID_FREQUENCY;
#elif defined(__APPLE__)
int64_t freq_hz = 0;
size_t freq_hz_size = sizeof(freq_hz);
int retval =
sysctlbyname("hw.cpufrequency_max", &freq_hz, &freq_hz_size, NULL, 0);
if (retval != 0 || freq_hz < 1e6) {
int64_t tbfrequency = 0;
size_t tbfrequency_size = sizeof(tbfrequency);
retval = sysctlbyname("hw.tbfrequency", &tbfrequency, &tbfrequency_size,
NULL, 0);
if (retval == 0) {
clockinfo clock_info;
size_t clock_info_size = sizeof(clock_info);
retval = sysctlbyname("kern.clockrate", &clock_info, &clock_info_size,
NULL, 0);
if (retval == 0) {
freq_hz = clock_info.hz * tbfrequency;
}
}
if (retval != 0 || freq_hz < 1e6) {
LOG(WARNING) << "Failed to get CPU frequency: " << freq_hz << " Hz";
return INVALID_FREQUENCY;
}
}
return freq_hz;
#elif defined(_WIN32)
LARGE_INTEGER freq;
QueryPerformanceFrequency(&freq);
return freq.QuadPart;
#else
return INVALID_FREQUENCY;
#endif
}
ICpuUtilsHelper& CpuUtils::GetCpuUtilsHelperSingletonInstance() {
static absl::once_flag flag;
absl::call_once(flag, []() {
if (cpu_utils_helper_instance_ != nullptr) {
LOG(FATAL) << "cpu_utils_helper_instance_ is already instantiated.";
}
#if defined(__ANDROID__) && (__ANDROID_API__ >= 21) && \
(defined(__ARM_ARCH_7A__) || defined(__aarch64__))
cpu_utils_helper_instance_ = new AndroidArmV7ACpuUtilsHelper();
#else
cpu_utils_helper_instance_ = new DefaultCpuUtilsHelper();
#endif
});
return *cpu_utils_helper_instance_;
}
}
} | #include "tsl/platform/profile_utils/cpu_utils.h"
#include "tsl/platform/logging.h"
#include "tsl/platform/profile_utils/clock_cycle_profiler.h"
#include "tsl/platform/test.h"
namespace tsl {
namespace profile_utils {
static constexpr bool DBG = false;
class CpuUtilsTest : public ::testing::Test {
protected:
void SetUp() override { CpuUtils::EnableClockCycleProfiling(); }
};
TEST_F(CpuUtilsTest, SetUpTestCase) {}
TEST_F(CpuUtilsTest, TearDownTestCase) {}
TEST_F(CpuUtilsTest, CheckGetCurrentClockCycle) {
static constexpr int LOOP_COUNT = 10;
const uint64 start_clock_count = CpuUtils::GetCurrentClockCycle();
CHECK_GT(start_clock_count, 0);
uint64 prev_clock_count = start_clock_count;
for (int i = 0; i < LOOP_COUNT; ++i) {
const uint64 clock_count = CpuUtils::GetCurrentClockCycle();
CHECK_GE(clock_count, prev_clock_count);
prev_clock_count = clock_count;
}
const uint64 end_clock_count = CpuUtils::GetCurrentClockCycle();
if (DBG) {
LOG(INFO) << "start clock = " << start_clock_count;
LOG(INFO) << "end clock = " << end_clock_count;
LOG(INFO) << "average clock = "
<< ((end_clock_count - start_clock_count) / LOOP_COUNT);
}
}
TEST_F(CpuUtilsTest, CheckCycleCounterFrequency) {
#if (defined(__powerpc__) || \
defined(__ppc__) && (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__)) || \
(defined(__s390x__))
const uint64 cpu_frequency = CpuUtils::GetCycleCounterFrequency();
CHECK_GT(cpu_frequency, 0);
CHECK_NE(cpu_frequency, unsigned(CpuUtils::INVALID_FREQUENCY));
#else
const int64_t cpu_frequency = CpuUtils::GetCycleCounterFrequency();
CHECK_GT(cpu_frequency, 0);
CHECK_NE(cpu_frequency, CpuUtils::INVALID_FREQUENCY);
#endif
if (DBG) {
LOG(INFO) << "Cpu frequency = " << cpu_frequency;
}
}
TEST_F(CpuUtilsTest, CheckMicroSecPerClock) {
const double micro_sec_per_clock = CpuUtils::GetMicroSecPerClock();
CHECK_GT(micro_sec_per_clock, 0.0);
if (DBG) {
LOG(INFO) << "Micro sec per clock = " << micro_sec_per_clock;
}
}
TEST_F(CpuUtilsTest, SimpleUsageOfClockCycleProfiler) {
static constexpr int LOOP_COUNT = 10;
ClockCycleProfiler prof;
for (int i = 0; i < LOOP_COUNT; ++i) {
prof.Start();
prof.Stop();
}
EXPECT_EQ(LOOP_COUNT, static_cast<int>(prof.GetCount() + 0.5));
if (DBG) {
prof.DumpStatistics("CpuUtilsTest");
}
}
}
} | 2,284 |
#ifndef TENSORFLOW_TSL_PLATFORM_NET_H_
#define TENSORFLOW_TSL_PLATFORM_NET_H_
namespace tsl {
namespace internal {
int PickUnusedPortOrDie();
}
}
#endif
#include "tsl/platform/net.h"
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#include <cerrno>
#include <cstdlib>
#include <cstring>
#include <random>
#include <unordered_set>
#include "tsl/platform/logging.h"
#include "tsl/platform/strcat.h"
#define MAX_EPHEMERAL_PORT 60999
#define MIN_EPHEMERAL_PORT 32768
namespace tsl {
namespace internal {
namespace {
bool IsPortAvailable(int* port, bool is_tcp) {
const int protocol = is_tcp ? IPPROTO_TCP : 0;
const int fd = socket(AF_INET, is_tcp ? SOCK_STREAM : SOCK_DGRAM, protocol);
struct sockaddr_in addr;
socklen_t addr_len = sizeof(addr);
int actual_port;
CHECK_GE(*port, 0);
CHECK_LE(*port, MAX_EPHEMERAL_PORT);
if (fd < 0) {
LOG(ERROR) << "socket() failed: " << strerror(errno);
return false;
}
int one = 1;
if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)) < 0) {
LOG(ERROR) << "setsockopt() failed: " << strerror(errno);
if (close(fd) < 0) {
LOG(ERROR) << "close() failed: " << strerror(errno);
};
return false;
}
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = INADDR_ANY;
addr.sin_port = htons(static_cast<uint16_t>(*port));
if (bind(fd, reinterpret_cast<struct sockaddr*>(&addr), sizeof(addr)) < 0) {
LOG(WARNING) << "bind(port=" << *port << ") failed: " << strerror(errno);
if (close(fd) < 0) {
LOG(ERROR) << "close() failed: " << strerror(errno);
};
return false;
}
if (getsockname(fd, reinterpret_cast<struct sockaddr*>(&addr), &addr_len) <
0) {
LOG(WARNING) << "getsockname() failed: " << strerror(errno);
if (close(fd) < 0) {
LOG(ERROR) << "close() failed: " << strerror(errno);
};
return false;
}
CHECK_LE(addr_len, sizeof(addr));
actual_port = ntohs(addr.sin_port);
CHECK_GT(actual_port, 0);
if (*port == 0) {
*port = actual_port;
} else {
CHECK_EQ(*port, actual_port);
}
if (close(fd) < 0) {
LOG(ERROR) << "close() failed: " << strerror(errno);
};
return true;
}
const int kNumRandomPortsToPick = 100;
const int kMaximumTrials = 1000;
}
int PickUnusedPortOrDie() {
static std::unordered_set<int> chosen_ports;
bool is_tcp = true;
int trial = 0;
std::default_random_engine rgen(std::random_device{}());
std::uniform_int_distribution<int> rdist(MIN_EPHEMERAL_PORT,
MAX_EPHEMERAL_PORT - 1);
while (true) {
int port;
trial++;
CHECK_LE(trial, kMaximumTrials)
<< "Failed to pick an unused port for testing.";
if (trial == 1) {
port = getpid() % (MAX_EPHEMERAL_PORT - MIN_EPHEMERAL_PORT) +
MIN_EPHEMERAL_PORT;
} else if (trial <= kNumRandomPortsToPick) {
port = rdist(rgen);
} else {
port = 0;
}
if (chosen_ports.find(port) != chosen_ports.end()) {
continue;
}
if (!IsPortAvailable(&port, is_tcp)) {
continue;
}
CHECK_GT(port, 0);
if (!IsPortAvailable(&port, !is_tcp)) {
is_tcp = !is_tcp;
continue;
}
chosen_ports.insert(port);
return port;
}
return 0;
}
}
} | #include "tsl/platform/net.h"
#include "tsl/platform/logging.h"
#include "tsl/platform/test.h"
namespace tsl {
namespace internal {
TEST(Net, PickUnusedPortOrDie) {
int port0 = PickUnusedPortOrDie();
int port1 = PickUnusedPortOrDie();
CHECK_GE(port0, 0);
CHECK_LT(port0, 65536);
CHECK_GE(port1, 0);
CHECK_LT(port1, 65536);
CHECK_NE(port0, port1);
}
}
} | 2,285 |
#ifndef TENSORFLOW_TSL_PLATFORM_DEFAULT_SUBPROCESS_H_
#define TENSORFLOW_TSL_PLATFORM_DEFAULT_SUBPROCESS_H_
#include <errno.h>
#include <unistd.h>
#include <string>
#include <vector>
#include "tsl/platform/macros.h"
#include "tsl/platform/mutex.h"
#include "tsl/platform/types.h"
namespace tsl {
class SubProcess {
public:
explicit SubProcess(int nfds = 3);
virtual ~SubProcess();
virtual void SetChannelAction(Channel chan, ChannelAction action);
virtual void SetProgram(const string& file, const std::vector<string>& argv);
virtual bool Start();
virtual bool Kill(int signal);
virtual bool Wait();
virtual int Communicate(const string* stdin_input, string* stdout_output,
string* stderr_output);
private:
static constexpr int kNFds = 3;
static bool chan_valid(int chan) { return ((chan >= 0) && (chan < kNFds)); }
static bool retry(int e) {
return ((e == EINTR) || (e == EAGAIN) || (e == EWOULDBLOCK));
}
void FreeArgs() TF_EXCLUSIVE_LOCKS_REQUIRED(data_mu_);
void ClosePipes() TF_EXCLUSIVE_LOCKS_REQUIRED(data_mu_);
bool WaitInternal(int* status);
mutable mutex proc_mu_;
bool running_ TF_GUARDED_BY(proc_mu_);
pid_t pid_ TF_GUARDED_BY(proc_mu_);
mutable mutex data_mu_ TF_ACQUIRED_AFTER(proc_mu_);
char* exec_path_ TF_GUARDED_BY(data_mu_);
char** exec_argv_ TF_GUARDED_BY(data_mu_);
ChannelAction action_[kNFds] TF_GUARDED_BY(data_mu_);
int parent_pipe_[kNFds] TF_GUARDED_BY(data_mu_);
int child_pipe_[kNFds] TF_GUARDED_BY(data_mu_);
SubProcess(const SubProcess&) = delete;
void operator=(const SubProcess&) = delete;
};
}
#endif
#include "tsl/platform/subprocess.h"
#include <fcntl.h>
#include <poll.h>
#include <signal.h>
#include <spawn.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <memory>
#include <vector>
#include "tsl/platform/logging.h"
#if !defined(__ANDROID_API__) || __ANDROID_API__ >= 28
#define USE_POSIX_SPAWN 1
#else
#define USE_POSIX_SPAWN 0
#endif
extern "C" {
extern char** environ;
}
namespace tsl {
SubProcess::SubProcess(int nfds)
: running_(false), pid_(-1), exec_path_(nullptr), exec_argv_(nullptr) {
for (int i = 0; i < kNFds; i++) {
action_[i] = ACTION_CLOSE;
parent_pipe_[i] = -1;
child_pipe_[i] = -1;
}
}
SubProcess::~SubProcess() {
mutex_lock procLock(proc_mu_);
mutex_lock dataLock(data_mu_);
pid_ = -1;
running_ = false;
FreeArgs();
ClosePipes();
}
void SubProcess::FreeArgs() {
free(exec_path_);
exec_path_ = nullptr;
if (exec_argv_) {
for (char** p = exec_argv_; *p != nullptr; p++) {
free(*p);
}
delete[] exec_argv_;
exec_argv_ = nullptr;
}
}
void SubProcess::ClosePipes() {
for (int i = 0; i < kNFds; i++) {
if (parent_pipe_[i] >= 0) {
if (close(parent_pipe_[i]) < 0) {
LOG(ERROR) << "close() failed: " << strerror(errno);
}
parent_pipe_[i] = -1;
}
if (child_pipe_[i] >= 0) {
if (close(child_pipe_[i]) < 0) {
LOG(ERROR) << "close() failed: " << strerror(errno);
}
child_pipe_[i] = -1;
}
}
}
void SubProcess::SetProgram(const string& file,
const std::vector<string>& argv) {
mutex_lock procLock(proc_mu_);
mutex_lock dataLock(data_mu_);
if (running_) {
LOG(FATAL) << "SetProgram called after the process was started.";
return;
}
FreeArgs();
exec_path_ = strdup(file.c_str());
if (exec_path_ == nullptr) {
LOG(FATAL) << "SetProgram failed to allocate file string.";
return;
}
int argc = argv.size();
exec_argv_ = new char*[argc + 1];
for (int i = 0; i < argc; i++) {
exec_argv_[i] = strdup(argv[i].c_str());
if (exec_argv_[i] == nullptr) {
LOG(FATAL) << "SetProgram failed to allocate command argument.";
return;
}
}
exec_argv_[argc] = nullptr;
}
void SubProcess::SetChannelAction(Channel chan, ChannelAction action) {
mutex_lock procLock(proc_mu_);
mutex_lock dataLock(data_mu_);
if (running_) {
LOG(FATAL) << "SetChannelAction called after the process was started.";
} else if (!chan_valid(chan)) {
LOG(FATAL) << "SetChannelAction called with invalid channel: " << chan;
} else if ((action != ACTION_CLOSE) && (action != ACTION_PIPE) &&
(action != ACTION_DUPPARENT)) {
LOG(FATAL) << "SetChannelAction called with invalid action: " << action;
} else {
action_[chan] = action;
}
}
#if USE_POSIX_SPAWN
bool SubProcess::Start() {
mutex_lock procLock(proc_mu_);
mutex_lock dataLock(data_mu_);
if (running_) {
LOG(ERROR) << "Start called after the process was started.";
return false;
}
if ((exec_path_ == nullptr) || (exec_argv_ == nullptr)) {
LOG(ERROR) << "Start called without setting a program.";
return false;
}
for (int i = 0; i < kNFds; i++) {
if (action_[i] == ACTION_PIPE) {
int pipe_fds[2];
if (pipe(pipe_fds) < 0) {
LOG(ERROR) << "Start cannot create pipe: " << strerror(errno);
ClosePipes();
return false;
}
if (i == 0) {
parent_pipe_[i] = pipe_fds[1];
child_pipe_[i] = pipe_fds[0];
} else {
parent_pipe_[i] = pipe_fds[0];
child_pipe_[i] = pipe_fds[1];
}
if (fcntl(parent_pipe_[i], F_SETFL, O_NONBLOCK) < 0) {
LOG(ERROR) << "Start cannot make pipe non-blocking: "
<< strerror(errno);
ClosePipes();
return false;
}
if (fcntl(parent_pipe_[i], F_SETFD, FD_CLOEXEC) < 0) {
LOG(ERROR) << "Start cannot make pipe close-on-exec: "
<< strerror(errno);
ClosePipes();
return false;
}
}
}
posix_spawn_file_actions_t file_actions;
int ret;
ret = posix_spawn_file_actions_init(&file_actions);
if (ret != 0) {
LOG(ERROR) << "Start cannot initialize POSIX file actions: "
<< strerror(ret);
ClosePipes();
return false;
}
int devnull_fd = -1;
for (int i = 0; i < kNFds; i++) {
if (parent_pipe_[i] >= 0) {
ret = posix_spawn_file_actions_addclose(&file_actions, parent_pipe_[i]);
if (ret != 0) {
LOG(ERROR) << "posix_spawn_file_actions_addclose() failed: "
<< strerror(ret);
}
}
switch (action_[i]) {
case ACTION_DUPPARENT:
break;
case ACTION_PIPE:
ret =
posix_spawn_file_actions_adddup2(&file_actions, child_pipe_[i], i);
if (ret != 0) {
LOG(ERROR) << "posix_spawn_file_actions_adddup2() failed: "
<< strerror(ret);
}
ret = posix_spawn_file_actions_addclose(&file_actions, child_pipe_[i]);
if (ret != 0) {
LOG(ERROR) << "posix_spawn_file_actions_addclose() failed: "
<< strerror(ret);
}
break;
case ACTION_CLOSE:
default:
if (i <= CHAN_STDERR) {
if (devnull_fd < 0) {
ret = posix_spawn_file_actions_addopen(&file_actions, i,
"/dev/null", O_RDWR, 0);
if (ret != 0) {
LOG(ERROR) << "posix_spawn_file_actions_addopen() failed: "
<< strerror(ret);
}
devnull_fd = i;
} else {
ret =
posix_spawn_file_actions_adddup2(&file_actions, devnull_fd, i);
if (ret != 0) {
LOG(ERROR) << "posix_spawn_file_actions_adddup2() failed: "
<< strerror(ret);
}
}
} else {
ret = posix_spawn_file_actions_addclose(&file_actions, i);
if (ret != 0) {
LOG(ERROR) << "posix_spawn_file_actions_addclose() failed: "
<< strerror(ret);
}
}
break;
}
}
ret = posix_spawnp(&pid_, exec_path_, &file_actions, nullptr, exec_argv_,
environ);
if (ret != 0) {
LOG(INFO) << "Start cannot spawn child process: " << strerror(ret);
ClosePipes();
return false;
}
ret = posix_spawn_file_actions_destroy(&file_actions);
if (ret != 0) {
LOG(WARNING) << "Start cannot destroy POSIX file actions: "
<< strerror(ret);
}
running_ = true;
for (int i = 0; i < kNFds; i++) {
if (child_pipe_[i] >= 0) {
if (close(child_pipe_[i]) < 0) {
LOG(ERROR) << "close() failed: " << strerror(errno);
}
child_pipe_[i] = -1;
}
}
return true;
}
#else
bool SubProcess::Start() {
mutex_lock procLock(proc_mu_);
mutex_lock dataLock(data_mu_);
if (running_) {
LOG(ERROR) << "Start called after the process was started.";
return false;
}
if ((exec_path_ == nullptr) || (exec_argv_ == nullptr)) {
LOG(ERROR) << "Start called without setting a program.";
return false;
}
for (int i = 0; i < kNFds; i++) {
if (action_[i] == ACTION_PIPE) {
int pipe_fds[2];
if (pipe(pipe_fds) < 0) {
LOG(ERROR) << "Start cannot create pipe: " << strerror(errno);
ClosePipes();
return false;
}
if (i == 0) {
parent_pipe_[i] = pipe_fds[1];
child_pipe_[i] = pipe_fds[0];
} else {
parent_pipe_[i] = pipe_fds[0];
child_pipe_[i] = pipe_fds[1];
}
if (fcntl(parent_pipe_[i], F_SETFL, O_NONBLOCK) < 0) {
LOG(ERROR) << "Start cannot make pipe non-blocking: "
<< strerror(errno);
ClosePipes();
return false;
}
if (fcntl(parent_pipe_[i], F_SETFD, FD_CLOEXEC) < 0) {
LOG(ERROR) << "Start cannot make pipe close-on-exec: "
<< strerror(errno);
ClosePipes();
return false;
}
}
}
pid_ = fork();
if (pid_ < 0) {
LOG(ERROR) << "Start cannot fork() child process: " << strerror(errno);
ClosePipes();
return false;
}
if (pid_ > 0) {
running_ = true;
for (int i = 0; i < kNFds; i++) {
if (child_pipe_[i] >= 0) {
if (close(child_pipe_[i]) < 0) {
LOG(ERROR) << "close() failed: " << strerror(errno);
}
child_pipe_[i] = -1;
}
}
return true;
}
int devnull_fd = -1;
for (int i = 0; i < kNFds; i++) {
if (parent_pipe_[i] >= 0) {
if (close(parent_pipe_[i]) < 0) {
LOG(ERROR) << "close() failed: " << strerror(errno);
}
parent_pipe_[i] = -1;
}
switch (action_[i]) {
case ACTION_DUPPARENT:
break;
case ACTION_PIPE:
while (dup2(child_pipe_[i], i) < 0) {
if (!retry(errno)) {
_exit(1);
}
}
if (close(child_pipe_[i]) < 0) {
LOG(ERROR) << "close() failed: " << strerror(errno);
}
child_pipe_[i] = -1;
break;
case ACTION_CLOSE:
default:
if (i <= CHAN_STDERR) {
if (devnull_fd < 0) {
while ((devnull_fd = open("/dev/null", O_RDWR, 0)) < 0) {
if (!retry(errno)) {
_exit(1);
}
}
}
while (dup2(devnull_fd, i) < 0) {
if (!retry(errno)) {
_exit(1);
}
}
} else {
if (close(i) < 0) {
LOG(ERROR) << "close() failed: " << strerror(errno);
}
}
break;
}
}
if (devnull_fd >= 0) {
if (close(devnull_fd) < 0) {
LOG(ERROR) << "close() failed: " << strerror(errno);
}
}
execvp(exec_path_, exec_argv_);
_exit(1);
}
#endif
bool SubProcess::Wait() {
int status;
return WaitInternal(&status);
}
bool SubProcess::WaitInternal(int* status) {
proc_mu_.lock();
bool running = running_;
pid_t pid = pid_;
proc_mu_.unlock();
bool ret = false;
if (running && (pid > 1)) {
pid_t cpid;
int cstat;
bool done = false;
while (!done) {
cpid = waitpid(pid, &cstat, 0);
if ((cpid < 0) && !retry(errno)) {
done = true;
} else if ((cpid == pid) && (WIFEXITED(cstat) || WIFSIGNALED(cstat))) {
*status = cstat;
ret = true;
done = true;
}
}
}
proc_mu_.lock();
if ((running_ == running) && (pid_ == pid)) {
running_ = false;
pid_ = -1;
}
proc_mu_.unlock();
return ret;
}
bool SubProcess::Kill(int signal) {
proc_mu_.lock();
bool running = running_;
pid_t pid = pid_;
proc_mu_.unlock();
bool ret = false;
if (running && (pid > 1)) {
ret = (kill(pid, signal) == 0);
}
return ret;
}
int SubProcess::Communicate(const string* stdin_input, string* stdout_output,
string* stderr_output) {
struct pollfd fds[kNFds];
size_t nbytes[kNFds];
string* iobufs[kNFds];
int fd_count = 0;
proc_mu_.lock();
bool running = running_;
proc_mu_.unlock();
if (!running) {
LOG(ERROR) << "Communicate called without a running process.";
return 1;
}
struct sigaction act;
if (sigaction(SIGPIPE, nullptr, &act) < 0) {
LOG(ERROR) << "Communicate cannot get SIGPIPE handler: " << strerror(errno);
return 1;
}
if (act.sa_handler == SIG_DFL) {
memset(&act, 0, sizeof(act));
act.sa_handler = SIG_IGN;
sigemptyset(&act.sa_mask);
if (sigaction(SIGPIPE, &act, nullptr) < 0) {
LOG(ERROR) << "Communicate cannot ignore SIGPIPE: " << strerror(errno);
return 1;
}
}
data_mu_.lock();
for (int i = 0; i < kNFds; i++) {
if (action_[i] == ACTION_PIPE) {
switch (i) {
case CHAN_STDIN:
if (stdin_input == nullptr) {
if (close(parent_pipe_[i]) < 0) {
LOG(ERROR) << "close() failed: " << strerror(errno);
}
parent_pipe_[i] = -1;
continue;
}
iobufs[fd_count] = const_cast<string*>(stdin_input);
break;
case CHAN_STDOUT:
iobufs[fd_count] = stdout_output;
break;
case CHAN_STDERR:
iobufs[fd_count] = stderr_output;
break;
default:
iobufs[fd_count] = nullptr;
break;
}
nbytes[fd_count] = 0;
fds[fd_count].fd = parent_pipe_[i];
fds[fd_count].events = (i > 0) ? POLLIN : POLLOUT;
fds[fd_count].revents = 0;
fd_count++;
}
}
int fd_remain = fd_count;
char buf[4096];
while (fd_remain > 0) {
int n = poll(fds, fd_count, -1);
if ((n < 0) && !retry(errno)) {
LOG(ERROR) << "Communicate cannot poll(): " << strerror(errno);
fd_remain = 0;
} else if (n == 0) {
LOG(ERROR) << "Communicate cannot poll(): timeout not possible";
fd_remain = 0;
} else if (n > 0) {
for (int i = 0; i < fd_count; i++) {
if ((fds[i].revents & (POLLIN | POLLHUP)) != 0) {
ssize_t n = read(fds[i].fd, buf, sizeof(buf));
if (n > 0) {
if (iobufs[i] != nullptr) {
iobufs[i]->append(buf, n);
nbytes[i] += n;
}
} else if ((n == 0) || !retry(errno)) {
fds[i].fd = -1;
fd_remain--;
}
} else if ((fds[i].revents & POLLOUT) != 0) {
ssize_t n = iobufs[i]->size() - nbytes[i];
if (n > 0) {
n = write(fds[i].fd, iobufs[i]->c_str() + nbytes[i], n);
}
if (n >= 0) {
nbytes[i] += n;
if (nbytes[i] >= iobufs[i]->size()) {
fds[i].fd = -1;
fd_remain--;
if (close(parent_pipe_[CHAN_STDIN]) < 0) {
LOG(ERROR) << "close() failed: " << strerror(errno);
}
parent_pipe_[CHAN_STDIN] = -1;
}
} else if (!retry(errno)) {
fds[i].fd = -1;
fd_remain--;
}
} else if ((fds[i].revents & (POLLERR | POLLNVAL)) != 0) {
fds[i].fd = -1;
fd_remain--;
}
}
}
}
data_mu_.unlock();
int status;
return WaitInternal(&status) ? status : -1;
}
std::unique_ptr<SubProcess> CreateSubProcess(const std::vector<string>& argv) {
std::unique_ptr<SubProcess> proc(new SubProcess());
proc->SetProgram(argv[0], argv);
proc->SetChannelAction(CHAN_STDERR, ACTION_DUPPARENT);
proc->SetChannelAction(CHAN_STDOUT, ACTION_DUPPARENT);
return proc;
}
} | #include "tsl/platform/subprocess.h"
#include <stdlib.h>
#include <algorithm>
#include <string>
#include "tsl/lib/core/status_test_util.h"
#include "tsl/platform/path.h"
#include "tsl/platform/strcat.h"
#include "tsl/platform/test.h"
#ifdef PLATFORM_WINDOWS
#define WIFEXITED(code) ((code) != 3)
#define WEXITSTATUS(code) (code)
#define SIGKILL 9
#else
#include <sys/wait.h>
#endif
namespace tsl {
namespace {
string EchoProgram() {
std::string path =
io::JoinPath(testing::TslSrcRoot(), "platform", "testdata", "test_echo");
return tsl::io::AppendDotExeIfWindows(path);
}
string EchoArgv1Program() {
std::string path = io::JoinPath(testing::TslSrcRoot(), "platform", "testdata",
"test_echo_argv_1");
return tsl::io::AppendDotExeIfWindows(path);
}
string NoopProgram() {
std::string path =
io::JoinPath(testing::TslSrcRoot(), "platform", "testdata", "test_noop");
return tsl::io::AppendDotExeIfWindows(path);
}
string StdErrProgram() {
std::string path = io::JoinPath(testing::TslSrcRoot(), "platform", "testdata",
"test_stderr");
return tsl::io::AppendDotExeIfWindows(path);
}
class SubProcessTest : public ::testing::Test {};
TEST_F(SubProcessTest, NoOutputNoComm) {
tsl::SubProcess proc;
proc.SetProgram(NoopProgram().c_str(), {NoopProgram()});
EXPECT_TRUE(proc.Start());
EXPECT_TRUE(proc.Wait());
}
TEST_F(SubProcessTest, NoOutput) {
tsl::SubProcess proc;
proc.SetProgram(NoopProgram().c_str(), {NoopProgram()});
proc.SetChannelAction(CHAN_STDOUT, ACTION_PIPE);
proc.SetChannelAction(CHAN_STDERR, ACTION_PIPE);
EXPECT_TRUE(proc.Start());
string out, err;
int status = proc.Communicate(nullptr, &out, &err);
EXPECT_TRUE(WIFEXITED(status));
EXPECT_EQ(0, WEXITSTATUS(status));
EXPECT_EQ("", out);
EXPECT_EQ("", err);
}
TEST_F(SubProcessTest, Stdout) {
tsl::SubProcess proc;
const char test_string[] = "hello_world";
proc.SetProgram(EchoArgv1Program().c_str(),
{EchoArgv1Program(), test_string});
proc.SetChannelAction(CHAN_STDOUT, ACTION_PIPE);
proc.SetChannelAction(CHAN_STDERR, ACTION_PIPE);
EXPECT_TRUE(proc.Start());
string out, err;
int status = proc.Communicate(nullptr, &out, &err);
EXPECT_TRUE(WIFEXITED(status));
EXPECT_EQ(0, WEXITSTATUS(status));
EXPECT_EQ(test_string, out);
EXPECT_EQ("", err);
}
TEST_F(SubProcessTest, StdoutIgnored) {
tsl::SubProcess proc;
const char test_string[] = "hello_world";
proc.SetProgram(EchoArgv1Program().c_str(),
{EchoArgv1Program(), test_string});
proc.SetChannelAction(CHAN_STDOUT, ACTION_PIPE);
proc.SetChannelAction(CHAN_STDERR, ACTION_PIPE);
EXPECT_TRUE(proc.Start());
int status = proc.Communicate(nullptr, nullptr, nullptr);
EXPECT_TRUE(WIFEXITED(status));
EXPECT_EQ(0, WEXITSTATUS(status));
}
TEST_F(SubProcessTest, Stderr) {
tsl::SubProcess proc;
const char test_string[] = "muh_failure!";
proc.SetProgram(StdErrProgram().c_str(), {StdErrProgram(), test_string});
proc.SetChannelAction(CHAN_STDOUT, ACTION_PIPE);
proc.SetChannelAction(CHAN_STDERR, ACTION_PIPE);
EXPECT_TRUE(proc.Start());
string out, err;
int status = proc.Communicate(nullptr, &out, &err);
EXPECT_TRUE(WIFEXITED(status));
EXPECT_NE(0, WEXITSTATUS(status));
EXPECT_EQ("", out);
EXPECT_EQ(test_string, err);
}
TEST_F(SubProcessTest, StderrIgnored) {
tsl::SubProcess proc;
const char test_string[] = "muh_failure!";
proc.SetProgram(StdErrProgram().c_str(), {StdErrProgram(), test_string});
proc.SetChannelAction(CHAN_STDOUT, ACTION_PIPE);
proc.SetChannelAction(CHAN_STDERR, ACTION_PIPE);
EXPECT_TRUE(proc.Start());
int status = proc.Communicate(nullptr, nullptr, nullptr);
EXPECT_TRUE(WIFEXITED(status));
EXPECT_NE(0, WEXITSTATUS(status));
}
TEST_F(SubProcessTest, Stdin) {
tsl::SubProcess proc;
proc.SetProgram(EchoProgram().c_str(), {EchoProgram()});
proc.SetChannelAction(CHAN_STDIN, ACTION_PIPE);
EXPECT_TRUE(proc.Start());
string in = "foobar\nbarfoo\nhaha\n";
int status = proc.Communicate(&in, nullptr, nullptr);
EXPECT_TRUE(WIFEXITED(status));
EXPECT_EQ(0, WEXITSTATUS(status));
}
TEST_F(SubProcessTest, StdinStdout) {
tsl::SubProcess proc;
proc.SetProgram(EchoProgram().c_str(), {EchoProgram()});
proc.SetChannelAction(CHAN_STDIN, ACTION_PIPE);
proc.SetChannelAction(CHAN_STDOUT, ACTION_PIPE);
EXPECT_TRUE(proc.Start());
string in = "foobar\nbarfoo\nhaha\n";
string out;
int status = proc.Communicate(&in, &out, nullptr);
EXPECT_TRUE(WIFEXITED(status));
EXPECT_EQ(0, WEXITSTATUS(status));
out.erase(std::remove(out.begin(), out.end(), '\r'), out.end());
EXPECT_EQ(in, out);
}
TEST_F(SubProcessTest, StdinChildExit) {
tsl::SubProcess proc;
proc.SetProgram(NoopProgram().c_str(), {NoopProgram()});
proc.SetChannelAction(CHAN_STDIN, ACTION_PIPE);
EXPECT_TRUE(proc.Start());
string in;
in.reserve(1000000);
for (int i = 0; i < 100000; i++) {
in += "hello xyz\n";
}
int status = proc.Communicate(&in, nullptr, nullptr);
EXPECT_TRUE(WIFEXITED(status));
EXPECT_EQ(0, WEXITSTATUS(status));
}
TEST_F(SubProcessTest, StdinStdoutOverlap) {
tsl::SubProcess proc;
proc.SetProgram(EchoProgram().c_str(), {EchoProgram()});
proc.SetChannelAction(CHAN_STDIN, ACTION_PIPE);
proc.SetChannelAction(CHAN_STDOUT, ACTION_PIPE);
EXPECT_TRUE(proc.Start());
string in;
in.reserve(1000000);
for (int i = 0; i < 100000; i++) {
in += "hello xyz\n";
}
string out;
int status = proc.Communicate(&in, &out, nullptr);
EXPECT_TRUE(WIFEXITED(status));
EXPECT_EQ(0, WEXITSTATUS(status));
out.erase(std::remove(out.begin(), out.end(), '\r'), out.end());
EXPECT_EQ(in, out);
}
TEST_F(SubProcessTest, KillProc) {
tsl::SubProcess proc;
proc.SetProgram(EchoProgram().c_str(), {EchoProgram()});
proc.SetChannelAction(CHAN_STDIN, ACTION_PIPE);
proc.SetChannelAction(CHAN_STDOUT, ACTION_PIPE);
EXPECT_TRUE(proc.Start());
EXPECT_TRUE(proc.Kill(SIGKILL));
EXPECT_TRUE(proc.Wait());
EXPECT_FALSE(proc.Kill(SIGKILL));
}
}
} | 2,286 |